]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/sqlite/lib/contrib/sqlite3.c
a5b93c4e25a4bc8890015b5a647dcd55e3c13b69
[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.4.  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% or 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 65536.  This a limit
219 ** imposed by the use of 16-bit offsets within each page.
220 **
221 ** Earlier versions of SQLite allowed the user to change this value at
222 ** compile time. This is no longer permitted, on the grounds that it creates
223 ** a library that is technically incompatible with an SQLite library 
224 ** compiled with a different limit. If a process operating on a database 
225 ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
226 ** compiled with the default page-size limit will not be able to rollback 
227 ** the aborted transaction. This could lead to database corruption.
228 */
229 #ifdef SQLITE_MAX_PAGE_SIZE
230 # undef SQLITE_MAX_PAGE_SIZE
231 #endif
232 #define SQLITE_MAX_PAGE_SIZE 65536
233
234
235 /*
236 ** The default size of a database page.
237 */
238 #ifndef SQLITE_DEFAULT_PAGE_SIZE
239 # define SQLITE_DEFAULT_PAGE_SIZE 1024
240 #endif
241 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242 # undef SQLITE_DEFAULT_PAGE_SIZE
243 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244 #endif
245
246 /*
247 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
248 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249 ** device characteristics (sector-size and atomic write() support),
250 ** SQLite may choose a larger value. This constant is the maximum value
251 ** SQLite will choose on its own.
252 */
253 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255 #endif
256 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259 #endif
260
261
262 /*
263 ** Maximum number of pages in one database file.
264 **
265 ** This is really just the default value for the max_page_count pragma.
266 ** This value can be lowered (or raised) at run-time using that the
267 ** max_page_count macro.
268 */
269 #ifndef SQLITE_MAX_PAGE_COUNT
270 # define SQLITE_MAX_PAGE_COUNT 1073741823
271 #endif
272
273 /*
274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275 ** operator.
276 */
277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279 #endif
280
281 /*
282 ** Maximum depth of recursion for triggers.
283 **
284 ** A value of 1 means that a trigger program will not be able to itself
285 ** fire any triggers. A value of 0 means that no trigger programs at all 
286 ** may be executed.
287 */
288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
290 #endif
291
292 /************** End of sqliteLimit.h *****************************************/
293 /************** Continuing where we left off in sqliteInt.h ******************/
294
295 /* Disable nuisance warnings on Borland compilers */
296 #if defined(__BORLANDC__)
297 #pragma warn -rch /* unreachable code */
298 #pragma warn -ccc /* Condition is always true or false */
299 #pragma warn -aus /* Assigned value is never used */
300 #pragma warn -csu /* Comparing signed and unsigned */
301 #pragma warn -spa /* Suspicious pointer arithmetic */
302 #endif
303
304 /* Needed for various definitions... */
305 #ifndef _GNU_SOURCE
306 # define _GNU_SOURCE
307 #endif
308
309 /*
310 ** Include standard header files as necessary
311 */
312 #ifdef HAVE_STDINT_H
313 #include <stdint.h>
314 #endif
315 #ifdef HAVE_INTTYPES_H
316 #include <inttypes.h>
317 #endif
318
319 /*
320 ** The number of samples of an index that SQLite takes in order to 
321 ** construct a histogram of the table content when running ANALYZE
322 ** and with SQLITE_ENABLE_STAT2
323 */
324 #define SQLITE_INDEX_SAMPLES 10
325
326 /*
327 ** The following macros are used to cast pointers to integers and
328 ** integers to pointers.  The way you do this varies from one compiler
329 ** to the next, so we have developed the following set of #if statements
330 ** to generate appropriate macros for a wide range of compilers.
331 **
332 ** The correct "ANSI" way to do this is to use the intptr_t type. 
333 ** Unfortunately, that typedef is not available on all compilers, or
334 ** if it is available, it requires an #include of specific headers
335 ** that vary from one machine to the next.
336 **
337 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
338 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
339 ** So we have to define the macros in different ways depending on the
340 ** compiler.
341 */
342 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
343 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
344 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
345 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
346 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
347 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
348 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
349 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
350 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
351 #else                          /* Generates a warning - but it always works */
352 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
353 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
354 #endif
355
356 /*
357 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
358 ** 0 means mutexes are permanently disable and the library is never
359 ** threadsafe.  1 means the library is serialized which is the highest
360 ** level of threadsafety.  2 means the libary is multithreaded - multiple
361 ** threads can use SQLite as long as no two threads try to use the same
362 ** database connection at the same time.
363 **
364 ** Older versions of SQLite used an optional THREADSAFE macro.
365 ** We support that for legacy.
366 */
367 #if !defined(SQLITE_THREADSAFE)
368 #if defined(THREADSAFE)
369 # define SQLITE_THREADSAFE THREADSAFE
370 #else
371 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
372 #endif
373 #endif
374
375 /*
376 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
377 ** It determines whether or not the features related to 
378 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
379 ** be overridden at runtime using the sqlite3_config() API.
380 */
381 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
382 # define SQLITE_DEFAULT_MEMSTATUS 1
383 #endif
384
385 /*
386 ** Exactly one of the following macros must be defined in order to
387 ** specify which memory allocation subsystem to use.
388 **
389 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
390 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
391 **
392 ** (Historical note:  There used to be several other options, but we've
393 ** pared it down to just these two.)
394 **
395 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
396 ** the default.
397 */
398 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
399 # error "At most one of the following compile-time configuration options\
400  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
401 #endif
402 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
403 # define SQLITE_SYSTEM_MALLOC 1
404 #endif
405
406 /*
407 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
408 ** sizes of memory allocations below this value where possible.
409 */
410 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
411 # define SQLITE_MALLOC_SOFT_LIMIT 1024
412 #endif
413
414 /*
415 ** We need to define _XOPEN_SOURCE as follows in order to enable
416 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
417 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
418 ** so it is omitted there.  See ticket #2673.
419 **
420 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
421 ** implemented on some systems.  So we avoid defining it at all
422 ** if it is already defined or if it is unneeded because we are
423 ** not doing a threadsafe build.  Ticket #2681.
424 **
425 ** See also ticket #2741.
426 */
427 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
428 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
429 #endif
430
431 /*
432 ** The TCL headers are only needed when compiling the TCL bindings.
433 */
434 #if defined(SQLITE_TCL) || defined(TCLSH)
435 # include <tcl.h>
436 #endif
437
438 /*
439 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
440 ** Setting NDEBUG makes the code smaller and run faster.  So the following
441 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
442 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
443 ** feature.
444 */
445 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
446 # define NDEBUG 1
447 #endif
448
449 /*
450 ** The testcase() macro is used to aid in coverage testing.  When 
451 ** doing coverage testing, the condition inside the argument to
452 ** testcase() must be evaluated both true and false in order to
453 ** get full branch coverage.  The testcase() macro is inserted
454 ** to help ensure adequate test coverage in places where simple
455 ** condition/decision coverage is inadequate.  For example, testcase()
456 ** can be used to make sure boundary values are tested.  For
457 ** bitmask tests, testcase() can be used to make sure each bit
458 ** is significant and used at least once.  On switch statements
459 ** where multiple cases go to the same block of code, testcase()
460 ** can insure that all cases are evaluated.
461 **
462 */
463 #ifdef SQLITE_COVERAGE_TEST
464 SQLITE_PRIVATE   void sqlite3Coverage(int);
465 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
466 #else
467 # define testcase(X)
468 #endif
469
470 /*
471 ** The TESTONLY macro is used to enclose variable declarations or
472 ** other bits of code that are needed to support the arguments
473 ** within testcase() and assert() macros.
474 */
475 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
476 # define TESTONLY(X)  X
477 #else
478 # define TESTONLY(X)
479 #endif
480
481 /*
482 ** Sometimes we need a small amount of code such as a variable initialization
483 ** to setup for a later assert() statement.  We do not want this code to
484 ** appear when assert() is disabled.  The following macro is therefore
485 ** used to contain that setup code.  The "VVA" acronym stands for
486 ** "Verification, Validation, and Accreditation".  In other words, the
487 ** code within VVA_ONLY() will only run during verification processes.
488 */
489 #ifndef NDEBUG
490 # define VVA_ONLY(X)  X
491 #else
492 # define VVA_ONLY(X)
493 #endif
494
495 /*
496 ** The ALWAYS and NEVER macros surround boolean expressions which 
497 ** are intended to always be true or false, respectively.  Such
498 ** expressions could be omitted from the code completely.  But they
499 ** are included in a few cases in order to enhance the resilience
500 ** of SQLite to unexpected behavior - to make the code "self-healing"
501 ** or "ductile" rather than being "brittle" and crashing at the first
502 ** hint of unplanned behavior.
503 **
504 ** In other words, ALWAYS and NEVER are added for defensive code.
505 **
506 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
507 ** be true and false so that the unreachable code then specify will
508 ** not be counted as untested code.
509 */
510 #if defined(SQLITE_COVERAGE_TEST)
511 # define ALWAYS(X)      (1)
512 # define NEVER(X)       (0)
513 #elif !defined(NDEBUG)
514 # define ALWAYS(X)      ((X)?1:(assert(0),0))
515 # define NEVER(X)       ((X)?(assert(0),1):0)
516 #else
517 # define ALWAYS(X)      (X)
518 # define NEVER(X)       (X)
519 #endif
520
521 /*
522 ** Return true (non-zero) if the input is a integer that is too large
523 ** to fit in 32-bits.  This macro is used inside of various testcase()
524 ** macros to verify that we have tested SQLite for large-file support.
525 */
526 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
527
528 /*
529 ** The macro unlikely() is a hint that surrounds a boolean
530 ** expression that is usually false.  Macro likely() surrounds
531 ** a boolean expression that is usually true.  GCC is able to
532 ** use these hints to generate better code, sometimes.
533 */
534 #if defined(__GNUC__) && 0
535 # define likely(X)    __builtin_expect((X),1)
536 # define unlikely(X)  __builtin_expect((X),0)
537 #else
538 # define likely(X)    !!(X)
539 # define unlikely(X)  !!(X)
540 #endif
541
542 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
543 /************** Begin file sqlite3.h *****************************************/
544 /*
545 ** 2001 September 15
546 **
547 ** The author disclaims copyright to this source code.  In place of
548 ** a legal notice, here is a blessing:
549 **
550 **    May you do good and not evil.
551 **    May you find forgiveness for yourself and forgive others.
552 **    May you share freely, never taking more than you give.
553 **
554 *************************************************************************
555 ** This header file defines the interface that the SQLite library
556 ** presents to client programs.  If a C-function, structure, datatype,
557 ** or constant definition does not appear in this file, then it is
558 ** not a published API of SQLite, is subject to change without
559 ** notice, and should not be referenced by programs that use SQLite.
560 **
561 ** Some of the definitions that are in this file are marked as
562 ** "experimental".  Experimental interfaces are normally new
563 ** features recently added to SQLite.  We do not anticipate changes
564 ** to experimental interfaces but reserve the right to make minor changes
565 ** if experience from use "in the wild" suggest such changes are prudent.
566 **
567 ** The official C-language API documentation for SQLite is derived
568 ** from comments in this file.  This file is the authoritative source
569 ** on how SQLite interfaces are suppose to operate.
570 **
571 ** The name of this file under configuration management is "sqlite.h.in".
572 ** The makefile makes some minor changes to this file (such as inserting
573 ** the version number) and changes its name to "sqlite3.h" as
574 ** part of the build process.
575 */
576 #ifndef _SQLITE3_H_
577 #define _SQLITE3_H_
578 #include <stdarg.h>     /* Needed for the definition of va_list */
579
580 /*
581 ** Make sure we can call this stuff from C++.
582 */
583 #if 0
584 extern "C" {
585 #endif
586
587
588 /*
589 ** Add the ability to override 'extern'
590 */
591 #ifndef SQLITE_EXTERN
592 # define SQLITE_EXTERN extern
593 #endif
594
595 #ifndef SQLITE_API
596 # define SQLITE_API
597 #endif
598
599
600 /*
601 ** These no-op macros are used in front of interfaces to mark those
602 ** interfaces as either deprecated or experimental.  New applications
603 ** should not use deprecated interfaces - they are support for backwards
604 ** compatibility only.  Application writers should be aware that
605 ** experimental interfaces are subject to change in point releases.
606 **
607 ** These macros used to resolve to various kinds of compiler magic that
608 ** would generate warning messages when they were used.  But that
609 ** compiler magic ended up generating such a flurry of bug reports
610 ** that we have taken it all out and gone back to using simple
611 ** noop macros.
612 */
613 #define SQLITE_DEPRECATED
614 #define SQLITE_EXPERIMENTAL
615
616 /*
617 ** Ensure these symbols were not defined by some previous header file.
618 */
619 #ifdef SQLITE_VERSION
620 # undef SQLITE_VERSION
621 #endif
622 #ifdef SQLITE_VERSION_NUMBER
623 # undef SQLITE_VERSION_NUMBER
624 #endif
625
626 /*
627 ** CAPI3REF: Compile-Time Library Version Numbers
628 **
629 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
630 ** evaluates to a string literal that is the SQLite version in the
631 ** format "X.Y.Z" where X is the major version number (always 3 for
632 ** SQLite3) and Y is the minor version number and Z is the release number.)^
633 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
634 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
635 ** numbers used in [SQLITE_VERSION].)^
636 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
637 ** be larger than the release from which it is derived.  Either Y will
638 ** be held constant and Z will be incremented or else Y will be incremented
639 ** and Z will be reset to zero.
640 **
641 ** Since version 3.6.18, SQLite source code has been stored in the
642 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
643 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
644 ** a string which identifies a particular check-in of SQLite
645 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
646 ** string contains the date and time of the check-in (UTC) and an SHA1
647 ** hash of the entire source tree.
648 **
649 ** See also: [sqlite3_libversion()],
650 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
651 ** [sqlite_version()] and [sqlite_source_id()].
652 */
653 #define SQLITE_VERSION        "3.7.4"
654 #define SQLITE_VERSION_NUMBER 3007004
655 #define SQLITE_SOURCE_ID      "2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45"
656
657 /*
658 ** CAPI3REF: Run-Time Library Version Numbers
659 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
660 **
661 ** These interfaces provide the same information as the [SQLITE_VERSION],
662 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
663 ** but are associated with the library instead of the header file.  ^(Cautious
664 ** programmers might include assert() statements in their application to
665 ** verify that values returned by these interfaces match the macros in
666 ** the header, and thus insure that the application is
667 ** compiled with matching library and header files.
668 **
669 ** <blockquote><pre>
670 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
671 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
672 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
673 ** </pre></blockquote>)^
674 **
675 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
676 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
677 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
678 ** function is provided for use in DLLs since DLL users usually do not have
679 ** direct access to string constants within the DLL.  ^The
680 ** sqlite3_libversion_number() function returns an integer equal to
681 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
682 ** a pointer to a string constant whose value is the same as the 
683 ** [SQLITE_SOURCE_ID] C preprocessor macro.
684 **
685 ** See also: [sqlite_version()] and [sqlite_source_id()].
686 */
687 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
688 SQLITE_API const char *sqlite3_libversion(void);
689 SQLITE_API const char *sqlite3_sourceid(void);
690 SQLITE_API int sqlite3_libversion_number(void);
691
692 /*
693 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
694 **
695 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
696 ** indicating whether the specified option was defined at 
697 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
698 ** option name passed to sqlite3_compileoption_used().  
699 **
700 ** ^The sqlite3_compileoption_get() function allows iterating
701 ** over the list of options that were defined at compile time by
702 ** returning the N-th compile time option string.  ^If N is out of range,
703 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
704 ** prefix is omitted from any strings returned by 
705 ** sqlite3_compileoption_get().
706 **
707 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
708 ** and sqlite3_compileoption_get() may be omitted by specifying the 
709 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
710 **
711 ** See also: SQL functions [sqlite_compileoption_used()] and
712 ** [sqlite_compileoption_get()] and the [compile_options pragma].
713 */
714 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
715 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
716 SQLITE_API const char *sqlite3_compileoption_get(int N);
717 #endif
718
719 /*
720 ** CAPI3REF: Test To See If The Library Is Threadsafe
721 **
722 ** ^The sqlite3_threadsafe() function returns zero if and only if
723 ** SQLite was compiled mutexing code omitted due to the
724 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
725 **
726 ** SQLite can be compiled with or without mutexes.  When
727 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
728 ** are enabled and SQLite is threadsafe.  When the
729 ** [SQLITE_THREADSAFE] macro is 0, 
730 ** the mutexes are omitted.  Without the mutexes, it is not safe
731 ** to use SQLite concurrently from more than one thread.
732 **
733 ** Enabling mutexes incurs a measurable performance penalty.
734 ** So if speed is of utmost importance, it makes sense to disable
735 ** the mutexes.  But for maximum safety, mutexes should be enabled.
736 ** ^The default behavior is for mutexes to be enabled.
737 **
738 ** This interface can be used by an application to make sure that the
739 ** version of SQLite that it is linking against was compiled with
740 ** the desired setting of the [SQLITE_THREADSAFE] macro.
741 **
742 ** This interface only reports on the compile-time mutex setting
743 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
744 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
745 ** can be fully or partially disabled using a call to [sqlite3_config()]
746 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
747 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
748 ** sqlite3_threadsafe() function shows only the compile-time setting of
749 ** thread safety, not any run-time changes to that setting made by
750 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
751 ** is unchanged by calls to sqlite3_config().)^
752 **
753 ** See the [threading mode] documentation for additional information.
754 */
755 SQLITE_API int sqlite3_threadsafe(void);
756
757 /*
758 ** CAPI3REF: Database Connection Handle
759 ** KEYWORDS: {database connection} {database connections}
760 **
761 ** Each open SQLite database is represented by a pointer to an instance of
762 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
763 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
764 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
765 ** is its destructor.  There are many other interfaces (such as
766 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
767 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
768 ** sqlite3 object.
769 */
770 typedef struct sqlite3 sqlite3;
771
772 /*
773 ** CAPI3REF: 64-Bit Integer Types
774 ** KEYWORDS: sqlite_int64 sqlite_uint64
775 **
776 ** Because there is no cross-platform way to specify 64-bit integer types
777 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
778 **
779 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
780 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
781 ** compatibility only.
782 **
783 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
784 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
785 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
786 ** between 0 and +18446744073709551615 inclusive.
787 */
788 #ifdef SQLITE_INT64_TYPE
789   typedef SQLITE_INT64_TYPE sqlite_int64;
790   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
791 #elif defined(_MSC_VER) || defined(__BORLANDC__)
792   typedef __int64 sqlite_int64;
793   typedef unsigned __int64 sqlite_uint64;
794 #else
795   typedef long long int sqlite_int64;
796   typedef unsigned long long int sqlite_uint64;
797 #endif
798 typedef sqlite_int64 sqlite3_int64;
799 typedef sqlite_uint64 sqlite3_uint64;
800
801 /*
802 ** If compiling for a processor that lacks floating point support,
803 ** substitute integer for floating-point.
804 */
805 #ifdef SQLITE_OMIT_FLOATING_POINT
806 # define double sqlite3_int64
807 #endif
808
809 /*
810 ** CAPI3REF: Closing A Database Connection
811 **
812 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
813 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
814 ** successfully destroyed and all associated resources are deallocated.
815 **
816 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
817 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
818 ** the [sqlite3] object prior to attempting to close the object.  ^If
819 ** sqlite3_close() is called on a [database connection] that still has
820 ** outstanding [prepared statements] or [BLOB handles], then it returns
821 ** SQLITE_BUSY.
822 **
823 ** ^If [sqlite3_close()] is invoked while a transaction is open,
824 ** the transaction is automatically rolled back.
825 **
826 ** The C parameter to [sqlite3_close(C)] must be either a NULL
827 ** pointer or an [sqlite3] object pointer obtained
828 ** from [sqlite3_open()], [sqlite3_open16()], or
829 ** [sqlite3_open_v2()], and not previously closed.
830 ** ^Calling sqlite3_close() with a NULL pointer argument is a 
831 ** harmless no-op.
832 */
833 SQLITE_API int sqlite3_close(sqlite3 *);
834
835 /*
836 ** The type for a callback function.
837 ** This is legacy and deprecated.  It is included for historical
838 ** compatibility and is not documented.
839 */
840 typedef int (*sqlite3_callback)(void*,int,char**, char**);
841
842 /*
843 ** CAPI3REF: One-Step Query Execution Interface
844 **
845 ** The sqlite3_exec() interface is a convenience wrapper around
846 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
847 ** that allows an application to run multiple statements of SQL
848 ** without having to use a lot of C code. 
849 **
850 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
851 ** semicolon-separate SQL statements passed into its 2nd argument,
852 ** in the context of the [database connection] passed in as its 1st
853 ** argument.  ^If the callback function of the 3rd argument to
854 ** sqlite3_exec() is not NULL, then it is invoked for each result row
855 ** coming out of the evaluated SQL statements.  ^The 4th argument to
856 ** to sqlite3_exec() is relayed through to the 1st argument of each
857 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
858 ** is NULL, then no callback is ever invoked and result rows are
859 ** ignored.
860 **
861 ** ^If an error occurs while evaluating the SQL statements passed into
862 ** sqlite3_exec(), then execution of the current statement stops and
863 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
864 ** is not NULL then any error message is written into memory obtained
865 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
866 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
867 ** on error message strings returned through the 5th parameter of
868 ** of sqlite3_exec() after the error message string is no longer needed.
869 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
870 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
871 ** NULL before returning.
872 **
873 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
874 ** routine returns SQLITE_ABORT without invoking the callback again and
875 ** without running any subsequent SQL statements.
876 **
877 ** ^The 2nd argument to the sqlite3_exec() callback function is the
878 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
879 ** callback is an array of pointers to strings obtained as if from
880 ** [sqlite3_column_text()], one for each column.  ^If an element of a
881 ** result row is NULL then the corresponding string pointer for the
882 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
883 ** sqlite3_exec() callback is an array of pointers to strings where each
884 ** entry represents the name of corresponding result column as obtained
885 ** from [sqlite3_column_name()].
886 **
887 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
888 ** to an empty string, or a pointer that contains only whitespace and/or 
889 ** SQL comments, then no SQL statements are evaluated and the database
890 ** is not changed.
891 **
892 ** Restrictions:
893 **
894 ** <ul>
895 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
896 **      is a valid and open [database connection].
897 ** <li> The application must not close [database connection] specified by
898 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
899 ** <li> The application must not modify the SQL statement text passed into
900 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
901 ** </ul>
902 */
903 SQLITE_API int sqlite3_exec(
904   sqlite3*,                                  /* An open database */
905   const char *sql,                           /* SQL to be evaluated */
906   int (*callback)(void*,int,char**,char**),  /* Callback function */
907   void *,                                    /* 1st argument to callback */
908   char **errmsg                              /* Error msg written here */
909 );
910
911 /*
912 ** CAPI3REF: Result Codes
913 ** KEYWORDS: SQLITE_OK {error code} {error codes}
914 ** KEYWORDS: {result code} {result codes}
915 **
916 ** Many SQLite functions return an integer result code from the set shown
917 ** here in order to indicates success or failure.
918 **
919 ** New error codes may be added in future versions of SQLite.
920 **
921 ** See also: [SQLITE_IOERR_READ | extended result codes]
922 */
923 #define SQLITE_OK           0   /* Successful result */
924 /* beginning-of-error-codes */
925 #define SQLITE_ERROR        1   /* SQL error or missing database */
926 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
927 #define SQLITE_PERM         3   /* Access permission denied */
928 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
929 #define SQLITE_BUSY         5   /* The database file is locked */
930 #define SQLITE_LOCKED       6   /* A table in the database is locked */
931 #define SQLITE_NOMEM        7   /* A malloc() failed */
932 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
933 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
934 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
935 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
936 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
937 #define SQLITE_FULL        13   /* Insertion failed because database is full */
938 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
939 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
940 #define SQLITE_EMPTY       16   /* Database is empty */
941 #define SQLITE_SCHEMA      17   /* The database schema changed */
942 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
943 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
944 #define SQLITE_MISMATCH    20   /* Data type mismatch */
945 #define SQLITE_MISUSE      21   /* Library used incorrectly */
946 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
947 #define SQLITE_AUTH        23   /* Authorization denied */
948 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
949 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
950 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
951 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
952 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
953 /* end-of-error-codes */
954
955 /*
956 ** CAPI3REF: Extended Result Codes
957 ** KEYWORDS: {extended error code} {extended error codes}
958 ** KEYWORDS: {extended result code} {extended result codes}
959 **
960 ** In its default configuration, SQLite API routines return one of 26 integer
961 ** [SQLITE_OK | result codes].  However, experience has shown that many of
962 ** these result codes are too coarse-grained.  They do not provide as
963 ** much information about problems as programmers might like.  In an effort to
964 ** address this, newer versions of SQLite (version 3.3.8 and later) include
965 ** support for additional result codes that provide more detailed information
966 ** about errors. The extended result codes are enabled or disabled
967 ** on a per database connection basis using the
968 ** [sqlite3_extended_result_codes()] API.
969 **
970 ** Some of the available extended result codes are listed here.
971 ** One may expect the number of extended result codes will be expand
972 ** over time.  Software that uses extended result codes should expect
973 ** to see new result codes in future releases of SQLite.
974 **
975 ** The SQLITE_OK result code will never be extended.  It will always
976 ** be exactly zero.
977 */
978 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
979 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
980 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
981 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
982 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
983 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
984 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
985 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
986 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
987 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
988 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
989 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
990 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
991 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
992 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
993 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
994 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
995 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
996 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
997 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
998 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
999 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1000 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1001
1002 /*
1003 ** CAPI3REF: Flags For File Open Operations
1004 **
1005 ** These bit values are intended for use in the
1006 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1007 ** in the 4th parameter to the xOpen method of the
1008 ** [sqlite3_vfs] object.
1009 */
1010 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1011 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1012 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1013 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1014 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1015 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1016 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1017 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1018 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1019 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1020 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1021 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1022 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1023 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1024 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1025 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1026 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1027 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1028
1029 /*
1030 ** CAPI3REF: Device Characteristics
1031 **
1032 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1033 ** object returns an integer which is a vector of the these
1034 ** bit values expressing I/O characteristics of the mass storage
1035 ** device that holds the file that the [sqlite3_io_methods]
1036 ** refers to.
1037 **
1038 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1039 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1040 ** mean that writes of blocks that are nnn bytes in size and
1041 ** are aligned to an address which is an integer multiple of
1042 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1043 ** that when data is appended to a file, the data is appended
1044 ** first then the size of the file is extended, never the other
1045 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1046 ** information is written to disk in the same order as calls
1047 ** to xWrite().
1048 */
1049 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1050 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1051 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1052 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1053 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1054 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1055 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1056 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1057 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1058 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1059 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1060 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1061
1062 /*
1063 ** CAPI3REF: File Locking Levels
1064 **
1065 ** SQLite uses one of these integer values as the second
1066 ** argument to calls it makes to the xLock() and xUnlock() methods
1067 ** of an [sqlite3_io_methods] object.
1068 */
1069 #define SQLITE_LOCK_NONE          0
1070 #define SQLITE_LOCK_SHARED        1
1071 #define SQLITE_LOCK_RESERVED      2
1072 #define SQLITE_LOCK_PENDING       3
1073 #define SQLITE_LOCK_EXCLUSIVE     4
1074
1075 /*
1076 ** CAPI3REF: Synchronization Type Flags
1077 **
1078 ** When SQLite invokes the xSync() method of an
1079 ** [sqlite3_io_methods] object it uses a combination of
1080 ** these integer values as the second argument.
1081 **
1082 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1083 ** sync operation only needs to flush data to mass storage.  Inode
1084 ** information need not be flushed. If the lower four bits of the flag
1085 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1086 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1087 ** to use Mac OS X style fullsync instead of fsync().
1088 **
1089 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1090 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1091 ** settings.  The [synchronous pragma] determines when calls to the
1092 ** xSync VFS method occur and applies uniformly across all platforms.
1093 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1094 ** energetic or rigorous or forceful the sync operations are and
1095 ** only make a difference on Mac OSX for the default SQLite code.
1096 ** (Third-party VFS implementations might also make the distinction
1097 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1098 ** operating systems natively supported by SQLite, only Mac OSX
1099 ** cares about the difference.)
1100 */
1101 #define SQLITE_SYNC_NORMAL        0x00002
1102 #define SQLITE_SYNC_FULL          0x00003
1103 #define SQLITE_SYNC_DATAONLY      0x00010
1104
1105 /*
1106 ** CAPI3REF: OS Interface Open File Handle
1107 **
1108 ** An [sqlite3_file] object represents an open file in the 
1109 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1110 ** implementations will
1111 ** want to subclass this object by appending additional fields
1112 ** for their own use.  The pMethods entry is a pointer to an
1113 ** [sqlite3_io_methods] object that defines methods for performing
1114 ** I/O operations on the open file.
1115 */
1116 typedef struct sqlite3_file sqlite3_file;
1117 struct sqlite3_file {
1118   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1119 };
1120
1121 /*
1122 ** CAPI3REF: OS Interface File Virtual Methods Object
1123 **
1124 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1125 ** [sqlite3_file] object (or, more commonly, a subclass of the
1126 ** [sqlite3_file] object) with a pointer to an instance of this object.
1127 ** This object defines the methods used to perform various operations
1128 ** against the open file represented by the [sqlite3_file] object.
1129 **
1130 ** If the xOpen method sets the sqlite3_file.pMethods element 
1131 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1132 ** may be invoked even if the xOpen reported that it failed.  The
1133 ** only way to prevent a call to xClose following a failed xOpen
1134 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1135 **
1136 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1137 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1138 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1139 ** flag may be ORed in to indicate that only the data of the file
1140 ** and not its inode needs to be synced.
1141 **
1142 ** The integer values to xLock() and xUnlock() are one of
1143 ** <ul>
1144 ** <li> [SQLITE_LOCK_NONE],
1145 ** <li> [SQLITE_LOCK_SHARED],
1146 ** <li> [SQLITE_LOCK_RESERVED],
1147 ** <li> [SQLITE_LOCK_PENDING], or
1148 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1149 ** </ul>
1150 ** xLock() increases the lock. xUnlock() decreases the lock.
1151 ** The xCheckReservedLock() method checks whether any database connection,
1152 ** either in this process or in some other process, is holding a RESERVED,
1153 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1154 ** if such a lock exists and false otherwise.
1155 **
1156 ** The xFileControl() method is a generic interface that allows custom
1157 ** VFS implementations to directly control an open file using the
1158 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1159 ** integer opcode.  The third argument is a generic pointer intended to
1160 ** point to a structure that may contain arguments or space in which to
1161 ** write return values.  Potential uses for xFileControl() might be
1162 ** functions to enable blocking locks with timeouts, to change the
1163 ** locking strategy (for example to use dot-file locks), to inquire
1164 ** about the status of a lock, or to break stale locks.  The SQLite
1165 ** core reserves all opcodes less than 100 for its own use.
1166 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1167 ** Applications that define a custom xFileControl method should use opcodes
1168 ** greater than 100 to avoid conflicts.
1169 **
1170 ** The xSectorSize() method returns the sector size of the
1171 ** device that underlies the file.  The sector size is the
1172 ** minimum write that can be performed without disturbing
1173 ** other bytes in the file.  The xDeviceCharacteristics()
1174 ** method returns a bit vector describing behaviors of the
1175 ** underlying device:
1176 **
1177 ** <ul>
1178 ** <li> [SQLITE_IOCAP_ATOMIC]
1179 ** <li> [SQLITE_IOCAP_ATOMIC512]
1180 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1181 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1182 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1183 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1184 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1185 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1186 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1187 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1188 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1189 ** </ul>
1190 **
1191 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1192 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1193 ** mean that writes of blocks that are nnn bytes in size and
1194 ** are aligned to an address which is an integer multiple of
1195 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1196 ** that when data is appended to a file, the data is appended
1197 ** first then the size of the file is extended, never the other
1198 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1199 ** information is written to disk in the same order as calls
1200 ** to xWrite().
1201 **
1202 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1203 ** in the unread portions of the buffer with zeros.  A VFS that
1204 ** fails to zero-fill short reads might seem to work.  However,
1205 ** failure to zero-fill short reads will eventually lead to
1206 ** database corruption.
1207 */
1208 typedef struct sqlite3_io_methods sqlite3_io_methods;
1209 struct sqlite3_io_methods {
1210   int iVersion;
1211   int (*xClose)(sqlite3_file*);
1212   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1213   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1214   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1215   int (*xSync)(sqlite3_file*, int flags);
1216   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1217   int (*xLock)(sqlite3_file*, int);
1218   int (*xUnlock)(sqlite3_file*, int);
1219   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1220   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1221   int (*xSectorSize)(sqlite3_file*);
1222   int (*xDeviceCharacteristics)(sqlite3_file*);
1223   /* Methods above are valid for version 1 */
1224   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1225   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1226   void (*xShmBarrier)(sqlite3_file*);
1227   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1228   /* Methods above are valid for version 2 */
1229   /* Additional methods may be added in future releases */
1230 };
1231
1232 /*
1233 ** CAPI3REF: Standard File Control Opcodes
1234 **
1235 ** These integer constants are opcodes for the xFileControl method
1236 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1237 ** interface.
1238 **
1239 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1240 ** opcode causes the xFileControl method to write the current state of
1241 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1242 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1243 ** into an integer that the pArg argument points to. This capability
1244 ** is used during testing and only needs to be supported when SQLITE_TEST
1245 ** is defined.
1246 **
1247 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1248 ** layer a hint of how large the database file will grow to be during the
1249 ** current transaction.  This hint is not guaranteed to be accurate but it
1250 ** is often close.  The underlying VFS might choose to preallocate database
1251 ** file space based on this hint in order to help writes to the database
1252 ** file run faster.
1253 **
1254 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1255 ** extends and truncates the database file in chunks of a size specified
1256 ** by the user. The fourth argument to [sqlite3_file_control()] should 
1257 ** point to an integer (type int) containing the new chunk-size to use
1258 ** for the nominated database. Allocating database file space in large
1259 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1260 ** improve performance on some systems.
1261 */
1262 #define SQLITE_FCNTL_LOCKSTATE        1
1263 #define SQLITE_GET_LOCKPROXYFILE      2
1264 #define SQLITE_SET_LOCKPROXYFILE      3
1265 #define SQLITE_LAST_ERRNO             4
1266 #define SQLITE_FCNTL_SIZE_HINT        5
1267 #define SQLITE_FCNTL_CHUNK_SIZE       6
1268 #define SQLITE_FCNTL_FILE_POINTER     7
1269
1270
1271 /*
1272 ** CAPI3REF: Mutex Handle
1273 **
1274 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1275 ** abstract type for a mutex object.  The SQLite core never looks
1276 ** at the internal representation of an [sqlite3_mutex].  It only
1277 ** deals with pointers to the [sqlite3_mutex] object.
1278 **
1279 ** Mutexes are created using [sqlite3_mutex_alloc()].
1280 */
1281 typedef struct sqlite3_mutex sqlite3_mutex;
1282
1283 /*
1284 ** CAPI3REF: OS Interface Object
1285 **
1286 ** An instance of the sqlite3_vfs object defines the interface between
1287 ** the SQLite core and the underlying operating system.  The "vfs"
1288 ** in the name of the object stands for "virtual file system".
1289 **
1290 ** The value of the iVersion field is initially 1 but may be larger in
1291 ** future versions of SQLite.  Additional fields may be appended to this
1292 ** object when the iVersion value is increased.  Note that the structure
1293 ** of the sqlite3_vfs object changes in the transaction between
1294 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1295 ** modified.
1296 **
1297 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1298 ** structure used by this VFS.  mxPathname is the maximum length of
1299 ** a pathname in this VFS.
1300 **
1301 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1302 ** the pNext pointer.  The [sqlite3_vfs_register()]
1303 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1304 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1305 ** searches the list.  Neither the application code nor the VFS
1306 ** implementation should use the pNext pointer.
1307 **
1308 ** The pNext field is the only field in the sqlite3_vfs
1309 ** structure that SQLite will ever modify.  SQLite will only access
1310 ** or modify this field while holding a particular static mutex.
1311 ** The application should never modify anything within the sqlite3_vfs
1312 ** object once the object has been registered.
1313 **
1314 ** The zName field holds the name of the VFS module.  The name must
1315 ** be unique across all VFS modules.
1316 **
1317 ** ^SQLite guarantees that the zFilename parameter to xOpen
1318 ** is either a NULL pointer or string obtained
1319 ** from xFullPathname() with an optional suffix added.
1320 ** ^If a suffix is added to the zFilename parameter, it will
1321 ** consist of a single "-" character followed by no more than
1322 ** 10 alphanumeric and/or "-" characters.
1323 ** ^SQLite further guarantees that
1324 ** the string will be valid and unchanged until xClose() is
1325 ** called. Because of the previous sentence,
1326 ** the [sqlite3_file] can safely store a pointer to the
1327 ** filename if it needs to remember the filename for some reason.
1328 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1329 ** must invent its own temporary name for the file.  ^Whenever the 
1330 ** xFilename parameter is NULL it will also be the case that the
1331 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1332 **
1333 ** The flags argument to xOpen() includes all bits set in
1334 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1335 ** or [sqlite3_open16()] is used, then flags includes at least
1336 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1337 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1338 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1339 **
1340 ** ^(SQLite will also add one of the following flags to the xOpen()
1341 ** call, depending on the object being opened:
1342 **
1343 ** <ul>
1344 ** <li>  [SQLITE_OPEN_MAIN_DB]
1345 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1346 ** <li>  [SQLITE_OPEN_TEMP_DB]
1347 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1348 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1349 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1350 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1351 ** <li>  [SQLITE_OPEN_WAL]
1352 ** </ul>)^
1353 **
1354 ** The file I/O implementation can use the object type flags to
1355 ** change the way it deals with files.  For example, an application
1356 ** that does not care about crash recovery or rollback might make
1357 ** the open of a journal file a no-op.  Writes to this journal would
1358 ** also be no-ops, and any attempt to read the journal would return
1359 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1360 ** file will be doing page-aligned sector reads and writes in a random
1361 ** order and set up its I/O subsystem accordingly.
1362 **
1363 ** SQLite might also add one of the following flags to the xOpen method:
1364 **
1365 ** <ul>
1366 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1367 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1368 ** </ul>
1369 **
1370 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1371 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1372 ** will be set for TEMP databases and their journals, transient
1373 ** databases, and subjournals.
1374 **
1375 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1376 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1377 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1378 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1379 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1380 ** be created, and that it is an error if it already exists.
1381 ** It is <i>not</i> used to indicate the file should be opened 
1382 ** for exclusive access.
1383 **
1384 ** ^At least szOsFile bytes of memory are allocated by SQLite
1385 ** to hold the  [sqlite3_file] structure passed as the third
1386 ** argument to xOpen.  The xOpen method does not have to
1387 ** allocate the structure; it should just fill it in.  Note that
1388 ** the xOpen method must set the sqlite3_file.pMethods to either
1389 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1390 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1391 ** element will be valid after xOpen returns regardless of the success
1392 ** or failure of the xOpen call.
1393 **
1394 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1395 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1396 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1397 ** to test whether a file is at least readable.   The file can be a
1398 ** directory.
1399 **
1400 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1401 ** output buffer xFullPathname.  The exact size of the output buffer
1402 ** is also passed as a parameter to both  methods. If the output buffer
1403 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1404 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1405 ** to prevent this by setting mxPathname to a sufficiently large value.
1406 **
1407 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1408 ** interfaces are not strictly a part of the filesystem, but they are
1409 ** included in the VFS structure for completeness.
1410 ** The xRandomness() function attempts to return nBytes bytes
1411 ** of good-quality randomness into zOut.  The return value is
1412 ** the actual number of bytes of randomness obtained.
1413 ** The xSleep() method causes the calling thread to sleep for at
1414 ** least the number of microseconds given.  ^The xCurrentTime()
1415 ** method returns a Julian Day Number for the current date and time as
1416 ** a floating point value.
1417 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1418 ** Day Number multipled by 86400000 (the number of milliseconds in 
1419 ** a 24-hour day).  
1420 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1421 ** date and time if that method is available (if iVersion is 2 or 
1422 ** greater and the function pointer is not NULL) and will fall back
1423 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1424 */
1425 typedef struct sqlite3_vfs sqlite3_vfs;
1426 struct sqlite3_vfs {
1427   int iVersion;            /* Structure version number (currently 2) */
1428   int szOsFile;            /* Size of subclassed sqlite3_file */
1429   int mxPathname;          /* Maximum file pathname length */
1430   sqlite3_vfs *pNext;      /* Next registered VFS */
1431   const char *zName;       /* Name of this virtual file system */
1432   void *pAppData;          /* Pointer to application-specific data */
1433   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1434                int flags, int *pOutFlags);
1435   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1436   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1437   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1438   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1439   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1440   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1441   void (*xDlClose)(sqlite3_vfs*, void*);
1442   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1443   int (*xSleep)(sqlite3_vfs*, int microseconds);
1444   int (*xCurrentTime)(sqlite3_vfs*, double*);
1445   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1446   /*
1447   ** The methods above are in version 1 of the sqlite_vfs object
1448   ** definition.  Those that follow are added in version 2 or later
1449   */
1450   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1451   /*
1452   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1453   ** New fields may be appended in figure versions.  The iVersion
1454   ** value will increment whenever this happens. 
1455   */
1456 };
1457
1458 /*
1459 ** CAPI3REF: Flags for the xAccess VFS method
1460 **
1461 ** These integer constants can be used as the third parameter to
1462 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1463 ** what kind of permissions the xAccess method is looking for.
1464 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1465 ** simply checks whether the file exists.
1466 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1467 ** checks whether the named directory is both readable and writable
1468 ** (in other words, if files can be added, removed, and renamed within
1469 ** the directory).
1470 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1471 ** [temp_store_directory pragma], though this could change in a future
1472 ** release of SQLite.
1473 ** With SQLITE_ACCESS_READ, the xAccess method
1474 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1475 ** currently unused, though it might be used in a future release of
1476 ** SQLite.
1477 */
1478 #define SQLITE_ACCESS_EXISTS    0
1479 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1480 #define SQLITE_ACCESS_READ      2   /* Unused */
1481
1482 /*
1483 ** CAPI3REF: Flags for the xShmLock VFS method
1484 **
1485 ** These integer constants define the various locking operations
1486 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1487 ** following are the only legal combinations of flags to the
1488 ** xShmLock method:
1489 **
1490 ** <ul>
1491 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1492 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1493 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1494 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1495 ** </ul>
1496 **
1497 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1498 ** was given no the corresponding lock.  
1499 **
1500 ** The xShmLock method can transition between unlocked and SHARED or
1501 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1502 ** and EXCLUSIVE.
1503 */
1504 #define SQLITE_SHM_UNLOCK       1
1505 #define SQLITE_SHM_LOCK         2
1506 #define SQLITE_SHM_SHARED       4
1507 #define SQLITE_SHM_EXCLUSIVE    8
1508
1509 /*
1510 ** CAPI3REF: Maximum xShmLock index
1511 **
1512 ** The xShmLock method on [sqlite3_io_methods] may use values
1513 ** between 0 and this upper bound as its "offset" argument.
1514 ** The SQLite core will never attempt to acquire or release a
1515 ** lock outside of this range
1516 */
1517 #define SQLITE_SHM_NLOCK        8
1518
1519
1520 /*
1521 ** CAPI3REF: Initialize The SQLite Library
1522 **
1523 ** ^The sqlite3_initialize() routine initializes the
1524 ** SQLite library.  ^The sqlite3_shutdown() routine
1525 ** deallocates any resources that were allocated by sqlite3_initialize().
1526 ** These routines are designed to aid in process initialization and
1527 ** shutdown on embedded systems.  Workstation applications using
1528 ** SQLite normally do not need to invoke either of these routines.
1529 **
1530 ** A call to sqlite3_initialize() is an "effective" call if it is
1531 ** the first time sqlite3_initialize() is invoked during the lifetime of
1532 ** the process, or if it is the first time sqlite3_initialize() is invoked
1533 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1534 ** of sqlite3_initialize() does any initialization.  All other calls
1535 ** are harmless no-ops.)^
1536 **
1537 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1538 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1539 ** an effective call to sqlite3_shutdown() does any deinitialization.
1540 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1541 **
1542 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1543 ** is not.  The sqlite3_shutdown() interface must only be called from a
1544 ** single thread.  All open [database connections] must be closed and all
1545 ** other SQLite resources must be deallocated prior to invoking
1546 ** sqlite3_shutdown().
1547 **
1548 ** Among other things, ^sqlite3_initialize() will invoke
1549 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1550 ** will invoke sqlite3_os_end().
1551 **
1552 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1553 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1554 ** the library (perhaps it is unable to allocate a needed resource such
1555 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1556 **
1557 ** ^The sqlite3_initialize() routine is called internally by many other
1558 ** SQLite interfaces so that an application usually does not need to
1559 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1560 ** calls sqlite3_initialize() so the SQLite library will be automatically
1561 ** initialized when [sqlite3_open()] is called if it has not be initialized
1562 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1563 ** compile-time option, then the automatic calls to sqlite3_initialize()
1564 ** are omitted and the application must call sqlite3_initialize() directly
1565 ** prior to using any other SQLite interface.  For maximum portability,
1566 ** it is recommended that applications always invoke sqlite3_initialize()
1567 ** directly prior to using any other SQLite interface.  Future releases
1568 ** of SQLite may require this.  In other words, the behavior exhibited
1569 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1570 ** default behavior in some future release of SQLite.
1571 **
1572 ** The sqlite3_os_init() routine does operating-system specific
1573 ** initialization of the SQLite library.  The sqlite3_os_end()
1574 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1575 ** performed by these routines include allocation or deallocation
1576 ** of static resources, initialization of global variables,
1577 ** setting up a default [sqlite3_vfs] module, or setting up
1578 ** a default configuration using [sqlite3_config()].
1579 **
1580 ** The application should never invoke either sqlite3_os_init()
1581 ** or sqlite3_os_end() directly.  The application should only invoke
1582 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1583 ** interface is called automatically by sqlite3_initialize() and
1584 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1585 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1586 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1587 ** When [custom builds | built for other platforms]
1588 ** (using the [SQLITE_OS_OTHER=1] compile-time
1589 ** option) the application must supply a suitable implementation for
1590 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1591 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1592 ** must return [SQLITE_OK] on success and some other [error code] upon
1593 ** failure.
1594 */
1595 SQLITE_API int sqlite3_initialize(void);
1596 SQLITE_API int sqlite3_shutdown(void);
1597 SQLITE_API int sqlite3_os_init(void);
1598 SQLITE_API int sqlite3_os_end(void);
1599
1600 /*
1601 ** CAPI3REF: Configuring The SQLite Library
1602 **
1603 ** The sqlite3_config() interface is used to make global configuration
1604 ** changes to SQLite in order to tune SQLite to the specific needs of
1605 ** the application.  The default configuration is recommended for most
1606 ** applications and so this routine is usually not necessary.  It is
1607 ** provided to support rare applications with unusual needs.
1608 **
1609 ** The sqlite3_config() interface is not threadsafe.  The application
1610 ** must insure that no other SQLite interfaces are invoked by other
1611 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1612 ** may only be invoked prior to library initialization using
1613 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1614 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1615 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1616 ** Note, however, that ^sqlite3_config() can be called as part of the
1617 ** implementation of an application-defined [sqlite3_os_init()].
1618 **
1619 ** The first argument to sqlite3_config() is an integer
1620 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1621 ** what property of SQLite is to be configured.  Subsequent arguments
1622 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1623 ** in the first argument.
1624 **
1625 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1626 ** ^If the option is unknown or SQLite is unable to set the option
1627 ** then this routine returns a non-zero [error code].
1628 */
1629 SQLITE_API int sqlite3_config(int, ...);
1630
1631 /*
1632 ** CAPI3REF: Configure database connections
1633 **
1634 ** The sqlite3_db_config() interface is used to make configuration
1635 ** changes to a [database connection].  The interface is similar to
1636 ** [sqlite3_config()] except that the changes apply to a single
1637 ** [database connection] (specified in the first argument).  The
1638 ** sqlite3_db_config() interface should only be used immediately after
1639 ** the database connection is created using [sqlite3_open()],
1640 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1641 **
1642 ** The second argument to sqlite3_db_config(D,V,...)  is the
1643 ** configuration verb - an integer code that indicates what
1644 ** aspect of the [database connection] is being configured.
1645 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1646 ** New verbs are likely to be added in future releases of SQLite.
1647 ** Additional arguments depend on the verb.
1648 **
1649 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1650 ** the call is considered successful.
1651 */
1652 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1653
1654 /*
1655 ** CAPI3REF: Memory Allocation Routines
1656 **
1657 ** An instance of this object defines the interface between SQLite
1658 ** and low-level memory allocation routines.
1659 **
1660 ** This object is used in only one place in the SQLite interface.
1661 ** A pointer to an instance of this object is the argument to
1662 ** [sqlite3_config()] when the configuration option is
1663 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1664 ** By creating an instance of this object
1665 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1666 ** during configuration, an application can specify an alternative
1667 ** memory allocation subsystem for SQLite to use for all of its
1668 ** dynamic memory needs.
1669 **
1670 ** Note that SQLite comes with several [built-in memory allocators]
1671 ** that are perfectly adequate for the overwhelming majority of applications
1672 ** and that this object is only useful to a tiny minority of applications
1673 ** with specialized memory allocation requirements.  This object is
1674 ** also used during testing of SQLite in order to specify an alternative
1675 ** memory allocator that simulates memory out-of-memory conditions in
1676 ** order to verify that SQLite recovers gracefully from such
1677 ** conditions.
1678 **
1679 ** The xMalloc and xFree methods must work like the
1680 ** malloc() and free() functions from the standard C library.
1681 ** The xRealloc method must work like realloc() from the standard C library
1682 ** with the exception that if the second argument to xRealloc is zero,
1683 ** xRealloc must be a no-op - it must not perform any allocation or
1684 ** deallocation.  ^SQLite guarantees that the second argument to
1685 ** xRealloc is always a value returned by a prior call to xRoundup.
1686 ** And so in cases where xRoundup always returns a positive number,
1687 ** xRealloc can perform exactly as the standard library realloc() and
1688 ** still be in compliance with this specification.
1689 **
1690 ** xSize should return the allocated size of a memory allocation
1691 ** previously obtained from xMalloc or xRealloc.  The allocated size
1692 ** is always at least as big as the requested size but may be larger.
1693 **
1694 ** The xRoundup method returns what would be the allocated size of
1695 ** a memory allocation given a particular requested size.  Most memory
1696 ** allocators round up memory allocations at least to the next multiple
1697 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1698 ** Every memory allocation request coming in through [sqlite3_malloc()]
1699 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1700 ** that causes the corresponding memory allocation to fail.
1701 **
1702 ** The xInit method initializes the memory allocator.  (For example,
1703 ** it might allocate any require mutexes or initialize internal data
1704 ** structures.  The xShutdown method is invoked (indirectly) by
1705 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1706 ** by xInit.  The pAppData pointer is used as the only parameter to
1707 ** xInit and xShutdown.
1708 **
1709 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1710 ** the xInit method, so the xInit method need not be threadsafe.  The
1711 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1712 ** not need to be threadsafe either.  For all other methods, SQLite
1713 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1714 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1715 ** it is by default) and so the methods are automatically serialized.
1716 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1717 ** methods must be threadsafe or else make their own arrangements for
1718 ** serialization.
1719 **
1720 ** SQLite will never invoke xInit() more than once without an intervening
1721 ** call to xShutdown().
1722 */
1723 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1724 struct sqlite3_mem_methods {
1725   void *(*xMalloc)(int);         /* Memory allocation function */
1726   void (*xFree)(void*);          /* Free a prior allocation */
1727   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1728   int (*xSize)(void*);           /* Return the size of an allocation */
1729   int (*xRoundup)(int);          /* Round up request size to allocation size */
1730   int (*xInit)(void*);           /* Initialize the memory allocator */
1731   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1732   void *pAppData;                /* Argument to xInit() and xShutdown() */
1733 };
1734
1735 /*
1736 ** CAPI3REF: Configuration Options
1737 **
1738 ** These constants are the available integer configuration options that
1739 ** can be passed as the first argument to the [sqlite3_config()] interface.
1740 **
1741 ** New configuration options may be added in future releases of SQLite.
1742 ** Existing configuration options might be discontinued.  Applications
1743 ** should check the return code from [sqlite3_config()] to make sure that
1744 ** the call worked.  The [sqlite3_config()] interface will return a
1745 ** non-zero [error code] if a discontinued or unsupported configuration option
1746 ** is invoked.
1747 **
1748 ** <dl>
1749 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1750 ** <dd>There are no arguments to this option.  ^This option sets the
1751 ** [threading mode] to Single-thread.  In other words, it disables
1752 ** all mutexing and puts SQLite into a mode where it can only be used
1753 ** by a single thread.   ^If SQLite is compiled with
1754 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1755 ** it is not possible to change the [threading mode] from its default
1756 ** value of Single-thread and so [sqlite3_config()] will return 
1757 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1758 ** configuration option.</dd>
1759 **
1760 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1761 ** <dd>There are no arguments to this option.  ^This option sets the
1762 ** [threading mode] to Multi-thread.  In other words, it disables
1763 ** mutexing on [database connection] and [prepared statement] objects.
1764 ** The application is responsible for serializing access to
1765 ** [database connections] and [prepared statements].  But other mutexes
1766 ** are enabled so that SQLite will be safe to use in a multi-threaded
1767 ** environment as long as no two threads attempt to use the same
1768 ** [database connection] at the same time.  ^If SQLite is compiled with
1769 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1770 ** it is not possible to set the Multi-thread [threading mode] and
1771 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1772 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1773 **
1774 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1775 ** <dd>There are no arguments to this option.  ^This option sets the
1776 ** [threading mode] to Serialized. In other words, this option enables
1777 ** all mutexes including the recursive
1778 ** mutexes on [database connection] and [prepared statement] objects.
1779 ** In this mode (which is the default when SQLite is compiled with
1780 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1781 ** to [database connections] and [prepared statements] so that the
1782 ** application is free to use the same [database connection] or the
1783 ** same [prepared statement] in different threads at the same time.
1784 ** ^If SQLite is compiled with
1785 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1786 ** it is not possible to set the Serialized [threading mode] and
1787 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1788 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1789 **
1790 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1791 ** <dd> ^(This option takes a single argument which is a pointer to an
1792 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1793 ** alternative low-level memory allocation routines to be used in place of
1794 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1795 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1796 ** before the [sqlite3_config()] call returns.</dd>
1797 **
1798 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1799 ** <dd> ^(This option takes a single argument which is a pointer to an
1800 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1801 ** structure is filled with the currently defined memory allocation routines.)^
1802 ** This option can be used to overload the default memory allocation
1803 ** routines with a wrapper that simulations memory allocation failure or
1804 ** tracks memory usage, for example. </dd>
1805 **
1806 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1807 ** <dd> ^This option takes single argument of type int, interpreted as a 
1808 ** boolean, which enables or disables the collection of memory allocation 
1809 ** statistics. ^(When memory allocation statistics are disabled, the 
1810 ** following SQLite interfaces become non-operational:
1811 **   <ul>
1812 **   <li> [sqlite3_memory_used()]
1813 **   <li> [sqlite3_memory_highwater()]
1814 **   <li> [sqlite3_soft_heap_limit64()]
1815 **   <li> [sqlite3_status()]
1816 **   </ul>)^
1817 ** ^Memory allocation statistics are enabled by default unless SQLite is
1818 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1819 ** allocation statistics are disabled by default.
1820 ** </dd>
1821 **
1822 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1823 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1824 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1825 ** aligned memory buffer from which the scrach allocations will be
1826 ** drawn, the size of each scratch allocation (sz),
1827 ** and the maximum number of scratch allocations (N).  The sz
1828 ** argument must be a multiple of 16.
1829 ** The first argument must be a pointer to an 8-byte aligned buffer
1830 ** of at least sz*N bytes of memory.
1831 ** ^SQLite will use no more than two scratch buffers per thread.  So
1832 ** N should be set to twice the expected maximum number of threads.
1833 ** ^SQLite will never require a scratch buffer that is more than 6
1834 ** times the database page size. ^If SQLite needs needs additional
1835 ** scratch memory beyond what is provided by this configuration option, then 
1836 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1837 **
1838 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1839 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1840 ** the database page cache with the default page cache implemenation.  
1841 ** This configuration should not be used if an application-define page
1842 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1843 ** There are three arguments to this option: A pointer to 8-byte aligned
1844 ** memory, the size of each page buffer (sz), and the number of pages (N).
1845 ** The sz argument should be the size of the largest database page
1846 ** (a power of two between 512 and 32768) plus a little extra for each
1847 ** page header.  ^The page header size is 20 to 40 bytes depending on
1848 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1849 ** to make sz a little too large.  The first
1850 ** argument should point to an allocation of at least sz*N bytes of memory.
1851 ** ^SQLite will use the memory provided by the first argument to satisfy its
1852 ** memory needs for the first N pages that it adds to cache.  ^If additional
1853 ** page cache memory is needed beyond what is provided by this option, then
1854 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1855 ** The pointer in the first argument must
1856 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1857 ** will be undefined.</dd>
1858 **
1859 ** <dt>SQLITE_CONFIG_HEAP</dt>
1860 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1861 ** for all of its dynamic memory allocation needs beyond those provided
1862 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1863 ** There are three arguments: An 8-byte aligned pointer to the memory,
1864 ** the number of bytes in the memory buffer, and the minimum allocation size.
1865 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1866 ** to using its default memory allocator (the system malloc() implementation),
1867 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1868 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1869 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1870 ** allocator is engaged to handle all of SQLites memory allocation needs.
1871 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1872 ** boundary or subsequent behavior of SQLite will be undefined.</dd>
1873 **
1874 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1875 ** <dd> ^(This option takes a single argument which is a pointer to an
1876 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1877 ** alternative low-level mutex routines to be used in place
1878 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1879 ** content of the [sqlite3_mutex_methods] structure before the call to
1880 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1881 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1882 ** the entire mutexing subsystem is omitted from the build and hence calls to
1883 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1884 ** return [SQLITE_ERROR].</dd>
1885 **
1886 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1887 ** <dd> ^(This option takes a single argument which is a pointer to an
1888 ** instance of the [sqlite3_mutex_methods] structure.  The
1889 ** [sqlite3_mutex_methods]
1890 ** structure is filled with the currently defined mutex routines.)^
1891 ** This option can be used to overload the default mutex allocation
1892 ** routines with a wrapper used to track mutex usage for performance
1893 ** profiling or testing, for example.   ^If SQLite is compiled with
1894 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1895 ** the entire mutexing subsystem is omitted from the build and hence calls to
1896 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1897 ** return [SQLITE_ERROR].</dd>
1898 **
1899 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1900 ** <dd> ^(This option takes two arguments that determine the default
1901 ** memory allocation for the lookaside memory allocator on each
1902 ** [database connection].  The first argument is the
1903 ** size of each lookaside buffer slot and the second is the number of
1904 ** slots allocated to each database connection.)^  ^(This option sets the
1905 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1906 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1907 ** configuration on individual connections.)^ </dd>
1908 **
1909 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1910 ** <dd> ^(This option takes a single argument which is a pointer to
1911 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1912 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1913 ** object and uses it for page cache memory allocations.</dd>
1914 **
1915 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1916 ** <dd> ^(This option takes a single argument which is a pointer to an
1917 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1918 ** page cache implementation into that object.)^ </dd>
1919 **
1920 ** <dt>SQLITE_CONFIG_LOG</dt>
1921 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1922 ** function with a call signature of void(*)(void*,int,const char*), 
1923 ** and a pointer to void. ^If the function pointer is not NULL, it is
1924 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1925 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1926 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1927 ** passed through as the first parameter to the application-defined logger
1928 ** function whenever that function is invoked.  ^The second parameter to
1929 ** the logger function is a copy of the first parameter to the corresponding
1930 ** [sqlite3_log()] call and is intended to be a [result code] or an
1931 ** [extended result code].  ^The third parameter passed to the logger is
1932 ** log message after formatting via [sqlite3_snprintf()].
1933 ** The SQLite logging interface is not reentrant; the logger function
1934 ** supplied by the application must not invoke any SQLite interface.
1935 ** In a multi-threaded application, the application-defined logger
1936 ** function must be threadsafe. </dd>
1937 **
1938 ** </dl>
1939 */
1940 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1941 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1942 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1943 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1944 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1945 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1946 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1947 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1948 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1949 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1950 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1951 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1952 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1953 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1954 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1955 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1956
1957 /*
1958 ** CAPI3REF: Database Connection Configuration Options
1959 **
1960 ** These constants are the available integer configuration options that
1961 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1962 **
1963 ** New configuration options may be added in future releases of SQLite.
1964 ** Existing configuration options might be discontinued.  Applications
1965 ** should check the return code from [sqlite3_db_config()] to make sure that
1966 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
1967 ** non-zero [error code] if a discontinued or unsupported configuration option
1968 ** is invoked.
1969 **
1970 ** <dl>
1971 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1972 ** <dd> ^This option takes three additional arguments that determine the 
1973 ** [lookaside memory allocator] configuration for the [database connection].
1974 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1975 ** pointer to an memory buffer to use for lookaside memory.
1976 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1977 ** may be NULL in which case SQLite will allocate the
1978 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1979 ** size of each lookaside buffer slot.  ^The third argument is the number of
1980 ** slots.  The size of the buffer in the first argument must be greater than
1981 ** or equal to the product of the second and third arguments.  The buffer
1982 ** must be aligned to an 8-byte boundary.  ^If the second argument to
1983 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1984 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
1985 ** configuration for a database connection can only be changed when that
1986 ** connection is not currently using lookaside memory, or in other words
1987 ** when the "current value" returned by
1988 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
1989 ** Any attempt to change the lookaside memory configuration when lookaside
1990 ** memory is in use leaves the configuration unchanged and returns 
1991 ** [SQLITE_BUSY].)^</dd>
1992 **
1993 ** </dl>
1994 */
1995 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1996
1997
1998 /*
1999 ** CAPI3REF: Enable Or Disable Extended Result Codes
2000 **
2001 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2002 ** [extended result codes] feature of SQLite. ^The extended result
2003 ** codes are disabled by default for historical compatibility.
2004 */
2005 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2006
2007 /*
2008 ** CAPI3REF: Last Insert Rowid
2009 **
2010 ** ^Each entry in an SQLite table has a unique 64-bit signed
2011 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2012 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2013 ** names are not also used by explicitly declared columns. ^If
2014 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2015 ** is another alias for the rowid.
2016 **
2017 ** ^This routine returns the [rowid] of the most recent
2018 ** successful [INSERT] into the database from the [database connection]
2019 ** in the first argument.  ^If no successful [INSERT]s
2020 ** have ever occurred on that database connection, zero is returned.
2021 **
2022 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
2023 ** row is returned by this routine as long as the trigger is running.
2024 ** But once the trigger terminates, the value returned by this routine
2025 ** reverts to the last value inserted before the trigger fired.)^
2026 **
2027 ** ^An [INSERT] that fails due to a constraint violation is not a
2028 ** successful [INSERT] and does not change the value returned by this
2029 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2030 ** and INSERT OR ABORT make no changes to the return value of this
2031 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2032 ** encounters a constraint violation, it does not fail.  The
2033 ** INSERT continues to completion after deleting rows that caused
2034 ** the constraint problem so INSERT OR REPLACE will always change
2035 ** the return value of this interface.)^
2036 **
2037 ** ^For the purposes of this routine, an [INSERT] is considered to
2038 ** be successful even if it is subsequently rolled back.
2039 **
2040 ** This function is accessible to SQL statements via the
2041 ** [last_insert_rowid() SQL function].
2042 **
2043 ** If a separate thread performs a new [INSERT] on the same
2044 ** database connection while the [sqlite3_last_insert_rowid()]
2045 ** function is running and thus changes the last insert [rowid],
2046 ** then the value returned by [sqlite3_last_insert_rowid()] is
2047 ** unpredictable and might not equal either the old or the new
2048 ** last insert [rowid].
2049 */
2050 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2051
2052 /*
2053 ** CAPI3REF: Count The Number Of Rows Modified
2054 **
2055 ** ^This function returns the number of database rows that were changed
2056 ** or inserted or deleted by the most recently completed SQL statement
2057 ** on the [database connection] specified by the first parameter.
2058 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2059 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2060 ** triggers or [foreign key actions] are not counted.)^ Use the
2061 ** [sqlite3_total_changes()] function to find the total number of changes
2062 ** including changes caused by triggers and foreign key actions.
2063 **
2064 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2065 ** are not counted.  Only real table changes are counted.
2066 **
2067 ** ^(A "row change" is a change to a single row of a single table
2068 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2069 ** are changed as side effects of [REPLACE] constraint resolution,
2070 ** rollback, ABORT processing, [DROP TABLE], or by any other
2071 ** mechanisms do not count as direct row changes.)^
2072 **
2073 ** A "trigger context" is a scope of execution that begins and
2074 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2075 ** Most SQL statements are
2076 ** evaluated outside of any trigger.  This is the "top level"
2077 ** trigger context.  If a trigger fires from the top level, a
2078 ** new trigger context is entered for the duration of that one
2079 ** trigger.  Subtriggers create subcontexts for their duration.
2080 **
2081 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2082 ** not create a new trigger context.
2083 **
2084 ** ^This function returns the number of direct row changes in the
2085 ** most recent INSERT, UPDATE, or DELETE statement within the same
2086 ** trigger context.
2087 **
2088 ** ^Thus, when called from the top level, this function returns the
2089 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2090 ** that also occurred at the top level.  ^(Within the body of a trigger,
2091 ** the sqlite3_changes() interface can be called to find the number of
2092 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2093 ** statement within the body of the same trigger.
2094 ** However, the number returned does not include changes
2095 ** caused by subtriggers since those have their own context.)^
2096 **
2097 ** See also the [sqlite3_total_changes()] interface, the
2098 ** [count_changes pragma], and the [changes() SQL function].
2099 **
2100 ** If a separate thread makes changes on the same database connection
2101 ** while [sqlite3_changes()] is running then the value returned
2102 ** is unpredictable and not meaningful.
2103 */
2104 SQLITE_API int sqlite3_changes(sqlite3*);
2105
2106 /*
2107 ** CAPI3REF: Total Number Of Rows Modified
2108 **
2109 ** ^This function returns the number of row changes caused by [INSERT],
2110 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2111 ** ^(The count returned by sqlite3_total_changes() includes all changes
2112 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2113 ** [foreign key actions]. However,
2114 ** the count does not include changes used to implement [REPLACE] constraints,
2115 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2116 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2117 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2118 ** are counted.)^
2119 ** ^The sqlite3_total_changes() function counts the changes as soon as
2120 ** the statement that makes them is completed (when the statement handle
2121 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2122 **
2123 ** See also the [sqlite3_changes()] interface, the
2124 ** [count_changes pragma], and the [total_changes() SQL function].
2125 **
2126 ** If a separate thread makes changes on the same database connection
2127 ** while [sqlite3_total_changes()] is running then the value
2128 ** returned is unpredictable and not meaningful.
2129 */
2130 SQLITE_API int sqlite3_total_changes(sqlite3*);
2131
2132 /*
2133 ** CAPI3REF: Interrupt A Long-Running Query
2134 **
2135 ** ^This function causes any pending database operation to abort and
2136 ** return at its earliest opportunity. This routine is typically
2137 ** called in response to a user action such as pressing "Cancel"
2138 ** or Ctrl-C where the user wants a long query operation to halt
2139 ** immediately.
2140 **
2141 ** ^It is safe to call this routine from a thread different from the
2142 ** thread that is currently running the database operation.  But it
2143 ** is not safe to call this routine with a [database connection] that
2144 ** is closed or might close before sqlite3_interrupt() returns.
2145 **
2146 ** ^If an SQL operation is very nearly finished at the time when
2147 ** sqlite3_interrupt() is called, then it might not have an opportunity
2148 ** to be interrupted and might continue to completion.
2149 **
2150 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2151 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2152 ** that is inside an explicit transaction, then the entire transaction
2153 ** will be rolled back automatically.
2154 **
2155 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2156 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2157 ** that are started after the sqlite3_interrupt() call and before the 
2158 ** running statements reaches zero are interrupted as if they had been
2159 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2160 ** that are started after the running statement count reaches zero are
2161 ** not effected by the sqlite3_interrupt().
2162 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2163 ** SQL statements is a no-op and has no effect on SQL statements
2164 ** that are started after the sqlite3_interrupt() call returns.
2165 **
2166 ** If the database connection closes while [sqlite3_interrupt()]
2167 ** is running then bad things will likely happen.
2168 */
2169 SQLITE_API void sqlite3_interrupt(sqlite3*);
2170
2171 /*
2172 ** CAPI3REF: Determine If An SQL Statement Is Complete
2173 **
2174 ** These routines are useful during command-line input to determine if the
2175 ** currently entered text seems to form a complete SQL statement or
2176 ** if additional input is needed before sending the text into
2177 ** SQLite for parsing.  ^These routines return 1 if the input string
2178 ** appears to be a complete SQL statement.  ^A statement is judged to be
2179 ** complete if it ends with a semicolon token and is not a prefix of a
2180 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2181 ** string literals or quoted identifier names or comments are not
2182 ** independent tokens (they are part of the token in which they are
2183 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2184 ** and comments that follow the final semicolon are ignored.
2185 **
2186 ** ^These routines return 0 if the statement is incomplete.  ^If a
2187 ** memory allocation fails, then SQLITE_NOMEM is returned.
2188 **
2189 ** ^These routines do not parse the SQL statements thus
2190 ** will not detect syntactically incorrect SQL.
2191 **
2192 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2193 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2194 ** automatically by sqlite3_complete16().  If that initialization fails,
2195 ** then the return value from sqlite3_complete16() will be non-zero
2196 ** regardless of whether or not the input SQL is complete.)^
2197 **
2198 ** The input to [sqlite3_complete()] must be a zero-terminated
2199 ** UTF-8 string.
2200 **
2201 ** The input to [sqlite3_complete16()] must be a zero-terminated
2202 ** UTF-16 string in native byte order.
2203 */
2204 SQLITE_API int sqlite3_complete(const char *sql);
2205 SQLITE_API int sqlite3_complete16(const void *sql);
2206
2207 /*
2208 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2209 **
2210 ** ^This routine sets a callback function that might be invoked whenever
2211 ** an attempt is made to open a database table that another thread
2212 ** or process has locked.
2213 **
2214 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2215 ** is returned immediately upon encountering the lock.  ^If the busy callback
2216 ** is not NULL, then the callback might be invoked with two arguments.
2217 **
2218 ** ^The first argument to the busy handler is a copy of the void* pointer which
2219 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2220 ** the busy handler callback is the number of times that the busy handler has
2221 ** been invoked for this locking event.  ^If the
2222 ** busy callback returns 0, then no additional attempts are made to
2223 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2224 ** ^If the callback returns non-zero, then another attempt
2225 ** is made to open the database for reading and the cycle repeats.
2226 **
2227 ** The presence of a busy handler does not guarantee that it will be invoked
2228 ** when there is lock contention. ^If SQLite determines that invoking the busy
2229 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2230 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2231 ** Consider a scenario where one process is holding a read lock that
2232 ** it is trying to promote to a reserved lock and
2233 ** a second process is holding a reserved lock that it is trying
2234 ** to promote to an exclusive lock.  The first process cannot proceed
2235 ** because it is blocked by the second and the second process cannot
2236 ** proceed because it is blocked by the first.  If both processes
2237 ** invoke the busy handlers, neither will make any progress.  Therefore,
2238 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2239 ** will induce the first process to release its read lock and allow
2240 ** the second process to proceed.
2241 **
2242 ** ^The default busy callback is NULL.
2243 **
2244 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2245 ** when SQLite is in the middle of a large transaction where all the
2246 ** changes will not fit into the in-memory cache.  SQLite will
2247 ** already hold a RESERVED lock on the database file, but it needs
2248 ** to promote this lock to EXCLUSIVE so that it can spill cache
2249 ** pages into the database file without harm to concurrent
2250 ** readers.  ^If it is unable to promote the lock, then the in-memory
2251 ** cache will be left in an inconsistent state and so the error
2252 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2253 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2254 ** forces an automatic rollback of the changes.  See the
2255 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2256 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2257 ** this is important.
2258 **
2259 ** ^(There can only be a single busy handler defined for each
2260 ** [database connection].  Setting a new busy handler clears any
2261 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2262 ** will also set or clear the busy handler.
2263 **
2264 ** The busy callback should not take any actions which modify the
2265 ** database connection that invoked the busy handler.  Any such actions
2266 ** result in undefined behavior.
2267 ** 
2268 ** A busy handler must not close the database connection
2269 ** or [prepared statement] that invoked the busy handler.
2270 */
2271 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2272
2273 /*
2274 ** CAPI3REF: Set A Busy Timeout
2275 **
2276 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2277 ** for a specified amount of time when a table is locked.  ^The handler
2278 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2279 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2280 ** the handler returns 0 which causes [sqlite3_step()] to return
2281 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2282 **
2283 ** ^Calling this routine with an argument less than or equal to zero
2284 ** turns off all busy handlers.
2285 **
2286 ** ^(There can only be a single busy handler for a particular
2287 ** [database connection] any any given moment.  If another busy handler
2288 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2289 ** this routine, that other busy handler is cleared.)^
2290 */
2291 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2292
2293 /*
2294 ** CAPI3REF: Convenience Routines For Running Queries
2295 **
2296 ** This is a legacy interface that is preserved for backwards compatibility.
2297 ** Use of this interface is not recommended.
2298 **
2299 ** Definition: A <b>result table</b> is memory data structure created by the
2300 ** [sqlite3_get_table()] interface.  A result table records the
2301 ** complete query results from one or more queries.
2302 **
2303 ** The table conceptually has a number of rows and columns.  But
2304 ** these numbers are not part of the result table itself.  These
2305 ** numbers are obtained separately.  Let N be the number of rows
2306 ** and M be the number of columns.
2307 **
2308 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2309 ** There are (N+1)*M elements in the array.  The first M pointers point
2310 ** to zero-terminated strings that  contain the names of the columns.
2311 ** The remaining entries all point to query results.  NULL values result
2312 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2313 ** string representation as returned by [sqlite3_column_text()].
2314 **
2315 ** A result table might consist of one or more memory allocations.
2316 ** It is not safe to pass a result table directly to [sqlite3_free()].
2317 ** A result table should be deallocated using [sqlite3_free_table()].
2318 **
2319 ** ^(As an example of the result table format, suppose a query result
2320 ** is as follows:
2321 **
2322 ** <blockquote><pre>
2323 **        Name        | Age
2324 **        -----------------------
2325 **        Alice       | 43
2326 **        Bob         | 28
2327 **        Cindy       | 21
2328 ** </pre></blockquote>
2329 **
2330 ** There are two column (M==2) and three rows (N==3).  Thus the
2331 ** result table has 8 entries.  Suppose the result table is stored
2332 ** in an array names azResult.  Then azResult holds this content:
2333 **
2334 ** <blockquote><pre>
2335 **        azResult&#91;0] = "Name";
2336 **        azResult&#91;1] = "Age";
2337 **        azResult&#91;2] = "Alice";
2338 **        azResult&#91;3] = "43";
2339 **        azResult&#91;4] = "Bob";
2340 **        azResult&#91;5] = "28";
2341 **        azResult&#91;6] = "Cindy";
2342 **        azResult&#91;7] = "21";
2343 ** </pre></blockquote>)^
2344 **
2345 ** ^The sqlite3_get_table() function evaluates one or more
2346 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2347 ** string of its 2nd parameter and returns a result table to the
2348 ** pointer given in its 3rd parameter.
2349 **
2350 ** After the application has finished with the result from sqlite3_get_table(),
2351 ** it must pass the result table pointer to sqlite3_free_table() in order to
2352 ** release the memory that was malloced.  Because of the way the
2353 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2354 ** function must not try to call [sqlite3_free()] directly.  Only
2355 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2356 **
2357 ** The sqlite3_get_table() interface is implemented as a wrapper around
2358 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2359 ** to any internal data structures of SQLite.  It uses only the public
2360 ** interface defined here.  As a consequence, errors that occur in the
2361 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2362 ** reflected in subsequent calls to [sqlite3_errcode()] or
2363 ** [sqlite3_errmsg()].
2364 */
2365 SQLITE_API int sqlite3_get_table(
2366   sqlite3 *db,          /* An open database */
2367   const char *zSql,     /* SQL to be evaluated */
2368   char ***pazResult,    /* Results of the query */
2369   int *pnRow,           /* Number of result rows written here */
2370   int *pnColumn,        /* Number of result columns written here */
2371   char **pzErrmsg       /* Error msg written here */
2372 );
2373 SQLITE_API void sqlite3_free_table(char **result);
2374
2375 /*
2376 ** CAPI3REF: Formatted String Printing Functions
2377 **
2378 ** These routines are work-alikes of the "printf()" family of functions
2379 ** from the standard C library.
2380 **
2381 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2382 ** results into memory obtained from [sqlite3_malloc()].
2383 ** The strings returned by these two routines should be
2384 ** released by [sqlite3_free()].  ^Both routines return a
2385 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2386 ** memory to hold the resulting string.
2387 **
2388 ** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2389 ** the standard C library.  The result is written into the
2390 ** buffer supplied as the second parameter whose size is given by
2391 ** the first parameter. Note that the order of the
2392 ** first two parameters is reversed from snprintf().)^  This is an
2393 ** historical accident that cannot be fixed without breaking
2394 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2395 ** returns a pointer to its buffer instead of the number of
2396 ** characters actually written into the buffer.)^  We admit that
2397 ** the number of characters written would be a more useful return
2398 ** value but we cannot change the implementation of sqlite3_snprintf()
2399 ** now without breaking compatibility.
2400 **
2401 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2402 ** guarantees that the buffer is always zero-terminated.  ^The first
2403 ** parameter "n" is the total size of the buffer, including space for
2404 ** the zero terminator.  So the longest string that can be completely
2405 ** written will be n-1 characters.
2406 **
2407 ** These routines all implement some additional formatting
2408 ** options that are useful for constructing SQL statements.
2409 ** All of the usual printf() formatting options apply.  In addition, there
2410 ** is are "%q", "%Q", and "%z" options.
2411 **
2412 ** ^(The %q option works like %s in that it substitutes a null-terminated
2413 ** string from the argument list.  But %q also doubles every '\'' character.
2414 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2415 ** character it escapes that character and allows it to be inserted into
2416 ** the string.
2417 **
2418 ** For example, assume the string variable zText contains text as follows:
2419 **
2420 ** <blockquote><pre>
2421 **  char *zText = "It's a happy day!";
2422 ** </pre></blockquote>
2423 **
2424 ** One can use this text in an SQL statement as follows:
2425 **
2426 ** <blockquote><pre>
2427 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2428 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2429 **  sqlite3_free(zSQL);
2430 ** </pre></blockquote>
2431 **
2432 ** Because the %q format string is used, the '\'' character in zText
2433 ** is escaped and the SQL generated is as follows:
2434 **
2435 ** <blockquote><pre>
2436 **  INSERT INTO table1 VALUES('It''s a happy day!')
2437 ** </pre></blockquote>
2438 **
2439 ** This is correct.  Had we used %s instead of %q, the generated SQL
2440 ** would have looked like this:
2441 **
2442 ** <blockquote><pre>
2443 **  INSERT INTO table1 VALUES('It's a happy day!');
2444 ** </pre></blockquote>
2445 **
2446 ** This second example is an SQL syntax error.  As a general rule you should
2447 ** always use %q instead of %s when inserting text into a string literal.
2448 **
2449 ** ^(The %Q option works like %q except it also adds single quotes around
2450 ** the outside of the total string.  Additionally, if the parameter in the
2451 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2452 ** single quotes).)^  So, for example, one could say:
2453 **
2454 ** <blockquote><pre>
2455 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2456 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2457 **  sqlite3_free(zSQL);
2458 ** </pre></blockquote>
2459 **
2460 ** The code above will render a correct SQL statement in the zSQL
2461 ** variable even if the zText variable is a NULL pointer.
2462 **
2463 ** ^(The "%z" formatting option works like "%s" but with the
2464 ** addition that after the string has been read and copied into
2465 ** the result, [sqlite3_free()] is called on the input string.)^
2466 */
2467 SQLITE_API char *sqlite3_mprintf(const char*,...);
2468 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2469 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2470
2471 /*
2472 ** CAPI3REF: Memory Allocation Subsystem
2473 **
2474 ** The SQLite core uses these three routines for all of its own
2475 ** internal memory allocation needs. "Core" in the previous sentence
2476 ** does not include operating-system specific VFS implementation.  The
2477 ** Windows VFS uses native malloc() and free() for some operations.
2478 **
2479 ** ^The sqlite3_malloc() routine returns a pointer to a block
2480 ** of memory at least N bytes in length, where N is the parameter.
2481 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2482 ** memory, it returns a NULL pointer.  ^If the parameter N to
2483 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2484 ** a NULL pointer.
2485 **
2486 ** ^Calling sqlite3_free() with a pointer previously returned
2487 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2488 ** that it might be reused.  ^The sqlite3_free() routine is
2489 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2490 ** to sqlite3_free() is harmless.  After being freed, memory
2491 ** should neither be read nor written.  Even reading previously freed
2492 ** memory might result in a segmentation fault or other severe error.
2493 ** Memory corruption, a segmentation fault, or other severe error
2494 ** might result if sqlite3_free() is called with a non-NULL pointer that
2495 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2496 **
2497 ** ^(The sqlite3_realloc() interface attempts to resize a
2498 ** prior memory allocation to be at least N bytes, where N is the
2499 ** second parameter.  The memory allocation to be resized is the first
2500 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2501 ** is a NULL pointer then its behavior is identical to calling
2502 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2503 ** ^If the second parameter to sqlite3_realloc() is zero or
2504 ** negative then the behavior is exactly the same as calling
2505 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2506 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2507 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2508 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2509 ** of the prior allocation are copied into the beginning of buffer returned
2510 ** by sqlite3_realloc() and the prior allocation is freed.
2511 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2512 ** is not freed.
2513 **
2514 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2515 ** is always aligned to at least an 8 byte boundary, or to a
2516 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2517 ** option is used.
2518 **
2519 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2520 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2521 ** implementation of these routines to be omitted.  That capability
2522 ** is no longer provided.  Only built-in memory allocators can be used.
2523 **
2524 ** The Windows OS interface layer calls
2525 ** the system malloc() and free() directly when converting
2526 ** filenames between the UTF-8 encoding used by SQLite
2527 ** and whatever filename encoding is used by the particular Windows
2528 ** installation.  Memory allocation errors are detected, but
2529 ** they are reported back as [SQLITE_CANTOPEN] or
2530 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2531 **
2532 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2533 ** must be either NULL or else pointers obtained from a prior
2534 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2535 ** not yet been released.
2536 **
2537 ** The application must not read or write any part of
2538 ** a block of memory after it has been released using
2539 ** [sqlite3_free()] or [sqlite3_realloc()].
2540 */
2541 SQLITE_API void *sqlite3_malloc(int);
2542 SQLITE_API void *sqlite3_realloc(void*, int);
2543 SQLITE_API void sqlite3_free(void*);
2544
2545 /*
2546 ** CAPI3REF: Memory Allocator Statistics
2547 **
2548 ** SQLite provides these two interfaces for reporting on the status
2549 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2550 ** routines, which form the built-in memory allocation subsystem.
2551 **
2552 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2553 ** of memory currently outstanding (malloced but not freed).
2554 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2555 ** value of [sqlite3_memory_used()] since the high-water mark
2556 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2557 ** [sqlite3_memory_highwater()] include any overhead
2558 ** added by SQLite in its implementation of [sqlite3_malloc()],
2559 ** but not overhead added by the any underlying system library
2560 ** routines that [sqlite3_malloc()] may call.
2561 **
2562 ** ^The memory high-water mark is reset to the current value of
2563 ** [sqlite3_memory_used()] if and only if the parameter to
2564 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2565 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2566 ** prior to the reset.
2567 */
2568 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2569 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2570
2571 /*
2572 ** CAPI3REF: Pseudo-Random Number Generator
2573 **
2574 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2575 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2576 ** already uses the largest possible [ROWID].  The PRNG is also used for
2577 ** the build-in random() and randomblob() SQL functions.  This interface allows
2578 ** applications to access the same PRNG for other purposes.
2579 **
2580 ** ^A call to this routine stores N bytes of randomness into buffer P.
2581 **
2582 ** ^The first time this routine is invoked (either internally or by
2583 ** the application) the PRNG is seeded using randomness obtained
2584 ** from the xRandomness method of the default [sqlite3_vfs] object.
2585 ** ^On all subsequent invocations, the pseudo-randomness is generated
2586 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2587 ** method.
2588 */
2589 SQLITE_API void sqlite3_randomness(int N, void *P);
2590
2591 /*
2592 ** CAPI3REF: Compile-Time Authorization Callbacks
2593 **
2594 ** ^This routine registers a authorizer callback with a particular
2595 ** [database connection], supplied in the first argument.
2596 ** ^The authorizer callback is invoked as SQL statements are being compiled
2597 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2598 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2599 ** points during the compilation process, as logic is being created
2600 ** to perform various actions, the authorizer callback is invoked to
2601 ** see if those actions are allowed.  ^The authorizer callback should
2602 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2603 ** specific action but allow the SQL statement to continue to be
2604 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2605 ** rejected with an error.  ^If the authorizer callback returns
2606 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2607 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2608 ** the authorizer will fail with an error message.
2609 **
2610 ** When the callback returns [SQLITE_OK], that means the operation
2611 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2612 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2613 ** authorizer will fail with an error message explaining that
2614 ** access is denied. 
2615 **
2616 ** ^The first parameter to the authorizer callback is a copy of the third
2617 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2618 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2619 ** the particular action to be authorized. ^The third through sixth parameters
2620 ** to the callback are zero-terminated strings that contain additional
2621 ** details about the action to be authorized.
2622 **
2623 ** ^If the action code is [SQLITE_READ]
2624 ** and the callback returns [SQLITE_IGNORE] then the
2625 ** [prepared statement] statement is constructed to substitute
2626 ** a NULL value in place of the table column that would have
2627 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2628 ** return can be used to deny an untrusted user access to individual
2629 ** columns of a table.
2630 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2631 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2632 ** [truncate optimization] is disabled and all rows are deleted individually.
2633 **
2634 ** An authorizer is used when [sqlite3_prepare | preparing]
2635 ** SQL statements from an untrusted source, to ensure that the SQL statements
2636 ** do not try to access data they are not allowed to see, or that they do not
2637 ** try to execute malicious statements that damage the database.  For
2638 ** example, an application may allow a user to enter arbitrary
2639 ** SQL queries for evaluation by a database.  But the application does
2640 ** not want the user to be able to make arbitrary changes to the
2641 ** database.  An authorizer could then be put in place while the
2642 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2643 ** disallows everything except [SELECT] statements.
2644 **
2645 ** Applications that need to process SQL from untrusted sources
2646 ** might also consider lowering resource limits using [sqlite3_limit()]
2647 ** and limiting database size using the [max_page_count] [PRAGMA]
2648 ** in addition to using an authorizer.
2649 **
2650 ** ^(Only a single authorizer can be in place on a database connection
2651 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2652 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2653 ** The authorizer is disabled by default.
2654 **
2655 ** The authorizer callback must not do anything that will modify
2656 ** the database connection that invoked the authorizer callback.
2657 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2658 ** database connections for the meaning of "modify" in this paragraph.
2659 **
2660 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2661 ** statement might be re-prepared during [sqlite3_step()] due to a 
2662 ** schema change.  Hence, the application should ensure that the
2663 ** correct authorizer callback remains in place during the [sqlite3_step()].
2664 **
2665 ** ^Note that the authorizer callback is invoked only during
2666 ** [sqlite3_prepare()] or its variants.  Authorization is not
2667 ** performed during statement evaluation in [sqlite3_step()], unless
2668 ** as stated in the previous paragraph, sqlite3_step() invokes
2669 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2670 */
2671 SQLITE_API int sqlite3_set_authorizer(
2672   sqlite3*,
2673   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2674   void *pUserData
2675 );
2676
2677 /*
2678 ** CAPI3REF: Authorizer Return Codes
2679 **
2680 ** The [sqlite3_set_authorizer | authorizer callback function] must
2681 ** return either [SQLITE_OK] or one of these two constants in order
2682 ** to signal SQLite whether or not the action is permitted.  See the
2683 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2684 ** information.
2685 */
2686 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2687 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2688
2689 /*
2690 ** CAPI3REF: Authorizer Action Codes
2691 **
2692 ** The [sqlite3_set_authorizer()] interface registers a callback function
2693 ** that is invoked to authorize certain SQL statement actions.  The
2694 ** second parameter to the callback is an integer code that specifies
2695 ** what action is being authorized.  These are the integer action codes that
2696 ** the authorizer callback may be passed.
2697 **
2698 ** These action code values signify what kind of operation is to be
2699 ** authorized.  The 3rd and 4th parameters to the authorization
2700 ** callback function will be parameters or NULL depending on which of these
2701 ** codes is used as the second parameter.  ^(The 5th parameter to the
2702 ** authorizer callback is the name of the database ("main", "temp",
2703 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2704 ** is the name of the inner-most trigger or view that is responsible for
2705 ** the access attempt or NULL if this access attempt is directly from
2706 ** top-level SQL code.
2707 */
2708 /******************************************* 3rd ************ 4th ***********/
2709 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2710 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2711 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2712 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2713 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2714 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2715 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2716 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2717 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2718 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2719 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2720 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2721 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2722 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2723 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2724 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2725 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2726 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2727 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2728 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2729 #define SQLITE_SELECT               21   /* NULL            NULL            */
2730 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2731 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2732 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2733 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2734 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2735 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2736 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2737 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2738 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2739 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2740 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2741 #define SQLITE_COPY                  0   /* No longer used */
2742
2743 /*
2744 ** CAPI3REF: Tracing And Profiling Functions
2745 **
2746 ** These routines register callback functions that can be used for
2747 ** tracing and profiling the execution of SQL statements.
2748 **
2749 ** ^The callback function registered by sqlite3_trace() is invoked at
2750 ** various times when an SQL statement is being run by [sqlite3_step()].
2751 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2752 ** SQL statement text as the statement first begins executing.
2753 ** ^(Additional sqlite3_trace() callbacks might occur
2754 ** as each triggered subprogram is entered.  The callbacks for triggers
2755 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2756 **
2757 ** ^The callback function registered by sqlite3_profile() is invoked
2758 ** as each SQL statement finishes.  ^The profile callback contains
2759 ** the original statement text and an estimate of wall-clock time
2760 ** of how long that statement took to run.  ^The profile callback
2761 ** time is in units of nanoseconds, however the current implementation
2762 ** is only capable of millisecond resolution so the six least significant
2763 ** digits in the time are meaningless.  Future versions of SQLite
2764 ** might provide greater resolution on the profiler callback.  The
2765 ** sqlite3_profile() function is considered experimental and is
2766 ** subject to change in future versions of SQLite.
2767 */
2768 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2769 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2770    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2771
2772 /*
2773 ** CAPI3REF: Query Progress Callbacks
2774 **
2775 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2776 ** function X to be invoked periodically during long running calls to
2777 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2778 ** database connection D.  An example use for this
2779 ** interface is to keep a GUI updated during a large query.
2780 **
2781 ** ^The parameter P is passed through as the only parameter to the 
2782 ** callback function X.  ^The parameter N is the number of 
2783 ** [virtual machine instructions] that are evaluated between successive
2784 ** invocations of the callback X.
2785 **
2786 ** ^Only a single progress handler may be defined at one time per
2787 ** [database connection]; setting a new progress handler cancels the
2788 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2789 ** ^The progress handler is also disabled by setting N to a value less
2790 ** than 1.
2791 **
2792 ** ^If the progress callback returns non-zero, the operation is
2793 ** interrupted.  This feature can be used to implement a
2794 ** "Cancel" button on a GUI progress dialog box.
2795 **
2796 ** The progress handler callback must not do anything that will modify
2797 ** the database connection that invoked the progress handler.
2798 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2799 ** database connections for the meaning of "modify" in this paragraph.
2800 **
2801 */
2802 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2803
2804 /*
2805 ** CAPI3REF: Opening A New Database Connection
2806 **
2807 ** ^These routines open an SQLite database file whose name is given by the
2808 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2809 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2810 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2811 ** returned in *ppDb, even if an error occurs.  The only exception is that
2812 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2813 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2814 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2815 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2816 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2817 ** an English language description of the error following a failure of any
2818 ** of the sqlite3_open() routines.
2819 **
2820 ** ^The default encoding for the database will be UTF-8 if
2821 ** sqlite3_open() or sqlite3_open_v2() is called and
2822 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2823 **
2824 ** Whether or not an error occurs when it is opened, resources
2825 ** associated with the [database connection] handle should be released by
2826 ** passing it to [sqlite3_close()] when it is no longer required.
2827 **
2828 ** The sqlite3_open_v2() interface works like sqlite3_open()
2829 ** except that it accepts two additional parameters for additional control
2830 ** over the new database connection.  ^(The flags parameter to
2831 ** sqlite3_open_v2() can take one of
2832 ** the following three values, optionally combined with the 
2833 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2834 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2835 **
2836 ** <dl>
2837 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2838 ** <dd>The database is opened in read-only mode.  If the database does not
2839 ** already exist, an error is returned.</dd>)^
2840 **
2841 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2842 ** <dd>The database is opened for reading and writing if possible, or reading
2843 ** only if the file is write protected by the operating system.  In either
2844 ** case the database must already exist, otherwise an error is returned.</dd>)^
2845 **
2846 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2847 ** <dd>The database is opened for reading and writing, and is creates it if
2848 ** it does not already exist. This is the behavior that is always used for
2849 ** sqlite3_open() and sqlite3_open16().</dd>)^
2850 ** </dl>
2851 **
2852 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2853 ** combinations shown above or one of the combinations shown above combined
2854 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2855 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_PRIVATECACHE] flags,
2856 ** then the behavior is undefined.
2857 **
2858 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2859 ** opens in the multi-thread [threading mode] as long as the single-thread
2860 ** mode has not been set at compile-time or start-time.  ^If the
2861 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2862 ** in the serialized [threading mode] unless single-thread was
2863 ** previously selected at compile-time or start-time.
2864 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2865 ** eligible to use [shared cache mode], regardless of whether or not shared
2866 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2867 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2868 ** participate in [shared cache mode] even if it is enabled.
2869 **
2870 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2871 ** is created for the connection.  ^This in-memory database will vanish when
2872 ** the database connection is closed.  Future versions of SQLite might
2873 ** make use of additional special filenames that begin with the ":" character.
2874 ** It is recommended that when a database filename actually does begin with
2875 ** a ":" character you should prefix the filename with a pathname such as
2876 ** "./" to avoid ambiguity.
2877 **
2878 ** ^If the filename is an empty string, then a private, temporary
2879 ** on-disk database will be created.  ^This private database will be
2880 ** automatically deleted as soon as the database connection is closed.
2881 **
2882 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2883 ** [sqlite3_vfs] object that defines the operating system interface that
2884 ** the new database connection should use.  ^If the fourth parameter is
2885 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2886 **
2887 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2888 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2889 ** codepage is currently defined.  Filenames containing international
2890 ** characters must be converted to UTF-8 prior to passing them into
2891 ** sqlite3_open() or sqlite3_open_v2().
2892 */
2893 SQLITE_API int sqlite3_open(
2894   const char *filename,   /* Database filename (UTF-8) */
2895   sqlite3 **ppDb          /* OUT: SQLite db handle */
2896 );
2897 SQLITE_API int sqlite3_open16(
2898   const void *filename,   /* Database filename (UTF-16) */
2899   sqlite3 **ppDb          /* OUT: SQLite db handle */
2900 );
2901 SQLITE_API int sqlite3_open_v2(
2902   const char *filename,   /* Database filename (UTF-8) */
2903   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2904   int flags,              /* Flags */
2905   const char *zVfs        /* Name of VFS module to use */
2906 );
2907
2908 /*
2909 ** CAPI3REF: Error Codes And Messages
2910 **
2911 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2912 ** [extended result code] for the most recent failed sqlite3_* API call
2913 ** associated with a [database connection]. If a prior API call failed
2914 ** but the most recent API call succeeded, the return value from
2915 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2916 ** interface is the same except that it always returns the 
2917 ** [extended result code] even when extended result codes are
2918 ** disabled.
2919 **
2920 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2921 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2922 ** ^(Memory to hold the error message string is managed internally.
2923 ** The application does not need to worry about freeing the result.
2924 ** However, the error string might be overwritten or deallocated by
2925 ** subsequent calls to other SQLite interface functions.)^
2926 **
2927 ** When the serialized [threading mode] is in use, it might be the
2928 ** case that a second error occurs on a separate thread in between
2929 ** the time of the first error and the call to these interfaces.
2930 ** When that happens, the second error will be reported since these
2931 ** interfaces always report the most recent result.  To avoid
2932 ** this, each thread can obtain exclusive use of the [database connection] D
2933 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2934 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2935 ** all calls to the interfaces listed here are completed.
2936 **
2937 ** If an interface fails with SQLITE_MISUSE, that means the interface
2938 ** was invoked incorrectly by the application.  In that case, the
2939 ** error code and message may or may not be set.
2940 */
2941 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2942 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2943 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2944 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2945
2946 /*
2947 ** CAPI3REF: SQL Statement Object
2948 ** KEYWORDS: {prepared statement} {prepared statements}
2949 **
2950 ** An instance of this object represents a single SQL statement.
2951 ** This object is variously known as a "prepared statement" or a
2952 ** "compiled SQL statement" or simply as a "statement".
2953 **
2954 ** The life of a statement object goes something like this:
2955 **
2956 ** <ol>
2957 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
2958 **      function.
2959 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2960 **      interfaces.
2961 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2962 ** <li> Reset the statement using [sqlite3_reset()] then go back
2963 **      to step 2.  Do this zero or more times.
2964 ** <li> Destroy the object using [sqlite3_finalize()].
2965 ** </ol>
2966 **
2967 ** Refer to documentation on individual methods above for additional
2968 ** information.
2969 */
2970 typedef struct sqlite3_stmt sqlite3_stmt;
2971
2972 /*
2973 ** CAPI3REF: Run-time Limits
2974 **
2975 ** ^(This interface allows the size of various constructs to be limited
2976 ** on a connection by connection basis.  The first parameter is the
2977 ** [database connection] whose limit is to be set or queried.  The
2978 ** second parameter is one of the [limit categories] that define a
2979 ** class of constructs to be size limited.  The third parameter is the
2980 ** new limit for that construct.)^
2981 **
2982 ** ^If the new limit is a negative number, the limit is unchanged.
2983 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
2984 ** [limits | hard upper bound]
2985 ** set at compile-time by a C preprocessor macro called
2986 ** [limits | SQLITE_MAX_<i>NAME</i>].
2987 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2988 ** ^Attempts to increase a limit above its hard upper bound are
2989 ** silently truncated to the hard upper bound.
2990 **
2991 ** ^Regardless of whether or not the limit was changed, the 
2992 ** [sqlite3_limit()] interface returns the prior value of the limit.
2993 ** ^Hence, to find the current value of a limit without changing it,
2994 ** simply invoke this interface with the third parameter set to -1.
2995 **
2996 ** Run-time limits are intended for use in applications that manage
2997 ** both their own internal database and also databases that are controlled
2998 ** by untrusted external sources.  An example application might be a
2999 ** web browser that has its own databases for storing history and
3000 ** separate databases controlled by JavaScript applications downloaded
3001 ** off the Internet.  The internal databases can be given the
3002 ** large, default limits.  Databases managed by external sources can
3003 ** be given much smaller limits designed to prevent a denial of service
3004 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3005 ** interface to further control untrusted SQL.  The size of the database
3006 ** created by an untrusted script can be contained using the
3007 ** [max_page_count] [PRAGMA].
3008 **
3009 ** New run-time limit categories may be added in future releases.
3010 */
3011 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3012
3013 /*
3014 ** CAPI3REF: Run-Time Limit Categories
3015 ** KEYWORDS: {limit category} {*limit categories}
3016 **
3017 ** These constants define various performance limits
3018 ** that can be lowered at run-time using [sqlite3_limit()].
3019 ** The synopsis of the meanings of the various limits is shown below.
3020 ** Additional information is available at [limits | Limits in SQLite].
3021 **
3022 ** <dl>
3023 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3024 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3025 **
3026 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3027 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3028 **
3029 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3030 ** <dd>The maximum number of columns in a table definition or in the
3031 ** result set of a [SELECT] or the maximum number of columns in an index
3032 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3033 **
3034 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3035 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3036 **
3037 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3038 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3039 **
3040 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3041 ** <dd>The maximum number of instructions in a virtual machine program
3042 ** used to implement an SQL statement.  This limit is not currently
3043 ** enforced, though that might be added in some future release of
3044 ** SQLite.</dd>)^
3045 **
3046 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3047 ** <dd>The maximum number of arguments on a function.</dd>)^
3048 **
3049 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3050 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3051 **
3052 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3053 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3054 ** [GLOB] operators.</dd>)^
3055 **
3056 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3057 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3058 **
3059 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3060 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3061 ** </dl>
3062 */
3063 #define SQLITE_LIMIT_LENGTH                    0
3064 #define SQLITE_LIMIT_SQL_LENGTH                1
3065 #define SQLITE_LIMIT_COLUMN                    2
3066 #define SQLITE_LIMIT_EXPR_DEPTH                3
3067 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3068 #define SQLITE_LIMIT_VDBE_OP                   5
3069 #define SQLITE_LIMIT_FUNCTION_ARG              6
3070 #define SQLITE_LIMIT_ATTACHED                  7
3071 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3072 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3073 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3074
3075 /*
3076 ** CAPI3REF: Compiling An SQL Statement
3077 ** KEYWORDS: {SQL statement compiler}
3078 **
3079 ** To execute an SQL query, it must first be compiled into a byte-code
3080 ** program using one of these routines.
3081 **
3082 ** The first argument, "db", is a [database connection] obtained from a
3083 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3084 ** [sqlite3_open16()].  The database connection must not have been closed.
3085 **
3086 ** The second argument, "zSql", is the statement to be compiled, encoded
3087 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3088 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3089 ** use UTF-16.
3090 **
3091 ** ^If the nByte argument is less than zero, then zSql is read up to the
3092 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3093 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3094 ** zSql string ends at either the first '\000' or '\u0000' character or
3095 ** the nByte-th byte, whichever comes first. If the caller knows
3096 ** that the supplied string is nul-terminated, then there is a small
3097 ** performance advantage to be gained by passing an nByte parameter that
3098 ** is equal to the number of bytes in the input string <i>including</i>
3099 ** the nul-terminator bytes.
3100 **
3101 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3102 ** past the end of the first SQL statement in zSql.  These routines only
3103 ** compile the first statement in zSql, so *pzTail is left pointing to
3104 ** what remains uncompiled.
3105 **
3106 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3107 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3108 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3109 ** string or a comment) then *ppStmt is set to NULL.
3110 ** The calling procedure is responsible for deleting the compiled
3111 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3112 ** ppStmt may not be NULL.
3113 **
3114 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3115 ** otherwise an [error code] is returned.
3116 **
3117 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3118 ** recommended for all new programs. The two older interfaces are retained
3119 ** for backwards compatibility, but their use is discouraged.
3120 ** ^In the "v2" interfaces, the prepared statement
3121 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3122 ** original SQL text. This causes the [sqlite3_step()] interface to
3123 ** behave differently in three ways:
3124 **
3125 ** <ol>
3126 ** <li>
3127 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3128 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3129 ** statement and try to run it again.
3130 ** </li>
3131 **
3132 ** <li>
3133 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3134 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3135 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3136 ** and the application would have to make a second call to [sqlite3_reset()]
3137 ** in order to find the underlying cause of the problem. With the "v2" prepare
3138 ** interfaces, the underlying reason for the error is returned immediately.
3139 ** </li>
3140 **
3141 ** <li>
3142 ** ^If the specific value bound to [parameter | host parameter] in the 
3143 ** WHERE clause might influence the choice of query plan for a statement,
3144 ** then the statement will be automatically recompiled, as if there had been 
3145 ** a schema change, on the first  [sqlite3_step()] call following any change
3146 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3147 ** ^The specific value of WHERE-clause [parameter] might influence the 
3148 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3149 ** or [GLOB] operator or if the parameter is compared to an indexed column
3150 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3151 ** the 
3152 ** </li>
3153 ** </ol>
3154 */
3155 SQLITE_API int sqlite3_prepare(
3156   sqlite3 *db,            /* Database handle */
3157   const char *zSql,       /* SQL statement, UTF-8 encoded */
3158   int nByte,              /* Maximum length of zSql in bytes. */
3159   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3160   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3161 );
3162 SQLITE_API int sqlite3_prepare_v2(
3163   sqlite3 *db,            /* Database handle */
3164   const char *zSql,       /* SQL statement, UTF-8 encoded */
3165   int nByte,              /* Maximum length of zSql in bytes. */
3166   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3167   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3168 );
3169 SQLITE_API int sqlite3_prepare16(
3170   sqlite3 *db,            /* Database handle */
3171   const void *zSql,       /* SQL statement, UTF-16 encoded */
3172   int nByte,              /* Maximum length of zSql in bytes. */
3173   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3174   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3175 );
3176 SQLITE_API int sqlite3_prepare16_v2(
3177   sqlite3 *db,            /* Database handle */
3178   const void *zSql,       /* SQL statement, UTF-16 encoded */
3179   int nByte,              /* Maximum length of zSql in bytes. */
3180   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3181   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3182 );
3183
3184 /*
3185 ** CAPI3REF: Retrieving Statement SQL
3186 **
3187 ** ^This interface can be used to retrieve a saved copy of the original
3188 ** SQL text used to create a [prepared statement] if that statement was
3189 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3190 */
3191 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3192
3193 /*
3194 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3195 **
3196 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3197 ** the [prepared statement] X is [SELECT] statement and false (zero) if
3198 ** X is an [INSERT], [UPDATE], [DELETE], CREATE, DROP, [ANALYZE],
3199 ** [ALTER], or [REINDEX] statement.
3200 ** If X is a NULL pointer or any other kind of statement, including but
3201 ** not limited to [ATTACH], [DETACH], [COMMIT], [ROLLBACK], [RELEASE],
3202 ** [SAVEPOINT], [PRAGMA], or [VACUUM] the result of sqlite3_stmt_readonly(X) is
3203 ** undefined.
3204 */
3205 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3206
3207 /*
3208 ** CAPI3REF: Dynamically Typed Value Object
3209 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3210 **
3211 ** SQLite uses the sqlite3_value object to represent all values
3212 ** that can be stored in a database table. SQLite uses dynamic typing
3213 ** for the values it stores.  ^Values stored in sqlite3_value objects
3214 ** can be integers, floating point values, strings, BLOBs, or NULL.
3215 **
3216 ** An sqlite3_value object may be either "protected" or "unprotected".
3217 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3218 ** will accept either a protected or an unprotected sqlite3_value.
3219 ** Every interface that accepts sqlite3_value arguments specifies
3220 ** whether or not it requires a protected sqlite3_value.
3221 **
3222 ** The terms "protected" and "unprotected" refer to whether or not
3223 ** a mutex is held.  A internal mutex is held for a protected
3224 ** sqlite3_value object but no mutex is held for an unprotected
3225 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3226 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3227 ** or if SQLite is run in one of reduced mutex modes 
3228 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3229 ** then there is no distinction between protected and unprotected
3230 ** sqlite3_value objects and they can be used interchangeably.  However,
3231 ** for maximum code portability it is recommended that applications
3232 ** still make the distinction between protected and unprotected
3233 ** sqlite3_value objects even when not strictly required.
3234 **
3235 ** ^The sqlite3_value objects that are passed as parameters into the
3236 ** implementation of [application-defined SQL functions] are protected.
3237 ** ^The sqlite3_value object returned by
3238 ** [sqlite3_column_value()] is unprotected.
3239 ** Unprotected sqlite3_value objects may only be used with
3240 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3241 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3242 ** interfaces require protected sqlite3_value objects.
3243 */
3244 typedef struct Mem sqlite3_value;
3245
3246 /*
3247 ** CAPI3REF: SQL Function Context Object
3248 **
3249 ** The context in which an SQL function executes is stored in an
3250 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3251 ** is always first parameter to [application-defined SQL functions].
3252 ** The application-defined SQL function implementation will pass this
3253 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3254 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3255 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3256 ** and/or [sqlite3_set_auxdata()].
3257 */
3258 typedef struct sqlite3_context sqlite3_context;
3259
3260 /*
3261 ** CAPI3REF: Binding Values To Prepared Statements
3262 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3263 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3264 **
3265 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3266 ** literals may be replaced by a [parameter] that matches one of following
3267 ** templates:
3268 **
3269 ** <ul>
3270 ** <li>  ?
3271 ** <li>  ?NNN
3272 ** <li>  :VVV
3273 ** <li>  @VVV
3274 ** <li>  $VVV
3275 ** </ul>
3276 **
3277 ** In the templates above, NNN represents an integer literal,
3278 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3279 ** parameters (also called "host parameter names" or "SQL parameters")
3280 ** can be set using the sqlite3_bind_*() routines defined here.
3281 **
3282 ** ^The first argument to the sqlite3_bind_*() routines is always
3283 ** a pointer to the [sqlite3_stmt] object returned from
3284 ** [sqlite3_prepare_v2()] or its variants.
3285 **
3286 ** ^The second argument is the index of the SQL parameter to be set.
3287 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3288 ** SQL parameter is used more than once, second and subsequent
3289 ** occurrences have the same index as the first occurrence.
3290 ** ^The index for named parameters can be looked up using the
3291 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3292 ** for "?NNN" parameters is the value of NNN.
3293 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3294 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3295 **
3296 ** ^The third argument is the value to bind to the parameter.
3297 **
3298 ** ^(In those routines that have a fourth argument, its value is the
3299 ** number of bytes in the parameter.  To be clear: the value is the
3300 ** number of <u>bytes</u> in the value, not the number of characters.)^
3301 ** ^If the fourth parameter is negative, the length of the string is
3302 ** the number of bytes up to the first zero terminator.
3303 **
3304 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3305 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3306 ** string after SQLite has finished with it.  ^The destructor is called
3307 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3308 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
3309 ** ^If the fifth argument is
3310 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3311 ** information is in static, unmanaged space and does not need to be freed.
3312 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3313 ** SQLite makes its own private copy of the data immediately, before
3314 ** the sqlite3_bind_*() routine returns.
3315 **
3316 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3317 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3318 ** (just an integer to hold its size) while it is being processed.
3319 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3320 ** content is later written using
3321 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3322 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3323 **
3324 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3325 ** for the [prepared statement] or with a prepared statement for which
3326 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3327 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3328 ** routine is passed a [prepared statement] that has been finalized, the
3329 ** result is undefined and probably harmful.
3330 **
3331 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3332 ** ^Unbound parameters are interpreted as NULL.
3333 **
3334 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3335 ** [error code] if anything goes wrong.
3336 ** ^[SQLITE_RANGE] is returned if the parameter
3337 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3338 **
3339 ** See also: [sqlite3_bind_parameter_count()],
3340 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3341 */
3342 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3343 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3344 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3345 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3346 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3347 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3348 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3349 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3350 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3351
3352 /*
3353 ** CAPI3REF: Number Of SQL Parameters
3354 **
3355 ** ^This routine can be used to find the number of [SQL parameters]
3356 ** in a [prepared statement].  SQL parameters are tokens of the
3357 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3358 ** placeholders for values that are [sqlite3_bind_blob | bound]
3359 ** to the parameters at a later time.
3360 **
3361 ** ^(This routine actually returns the index of the largest (rightmost)
3362 ** parameter. For all forms except ?NNN, this will correspond to the
3363 ** number of unique parameters.  If parameters of the ?NNN form are used,
3364 ** there may be gaps in the list.)^
3365 **
3366 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3367 ** [sqlite3_bind_parameter_name()], and
3368 ** [sqlite3_bind_parameter_index()].
3369 */
3370 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3371
3372 /*
3373 ** CAPI3REF: Name Of A Host Parameter
3374 **
3375 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3376 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3377 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3378 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3379 ** respectively.
3380 ** In other words, the initial ":" or "$" or "@" or "?"
3381 ** is included as part of the name.)^
3382 ** ^Parameters of the form "?" without a following integer have no name
3383 ** and are referred to as "nameless" or "anonymous parameters".
3384 **
3385 ** ^The first host parameter has an index of 1, not 0.
3386 **
3387 ** ^If the value N is out of range or if the N-th parameter is
3388 ** nameless, then NULL is returned.  ^The returned string is
3389 ** always in UTF-8 encoding even if the named parameter was
3390 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3391 ** [sqlite3_prepare16_v2()].
3392 **
3393 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3394 ** [sqlite3_bind_parameter_count()], and
3395 ** [sqlite3_bind_parameter_index()].
3396 */
3397 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3398
3399 /*
3400 ** CAPI3REF: Index Of A Parameter With A Given Name
3401 **
3402 ** ^Return the index of an SQL parameter given its name.  ^The
3403 ** index value returned is suitable for use as the second
3404 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3405 ** is returned if no matching parameter is found.  ^The parameter
3406 ** name must be given in UTF-8 even if the original statement
3407 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3408 **
3409 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3410 ** [sqlite3_bind_parameter_count()], and
3411 ** [sqlite3_bind_parameter_index()].
3412 */
3413 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3414
3415 /*
3416 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3417 **
3418 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3419 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3420 ** ^Use this routine to reset all host parameters to NULL.
3421 */
3422 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3423
3424 /*
3425 ** CAPI3REF: Number Of Columns In A Result Set
3426 **
3427 ** ^Return the number of columns in the result set returned by the
3428 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3429 ** statement that does not return data (for example an [UPDATE]).
3430 **
3431 ** See also: [sqlite3_data_count()]
3432 */
3433 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3434
3435 /*
3436 ** CAPI3REF: Column Names In A Result Set
3437 **
3438 ** ^These routines return the name assigned to a particular column
3439 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3440 ** interface returns a pointer to a zero-terminated UTF-8 string
3441 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3442 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3443 ** that implements the [SELECT] statement. ^The second parameter is the
3444 ** column number.  ^The leftmost column is number 0.
3445 **
3446 ** ^The returned string pointer is valid until either the [prepared statement]
3447 ** is destroyed by [sqlite3_finalize()] or until the next call to
3448 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3449 **
3450 ** ^If sqlite3_malloc() fails during the processing of either routine
3451 ** (for example during a conversion from UTF-8 to UTF-16) then a
3452 ** NULL pointer is returned.
3453 **
3454 ** ^The name of a result column is the value of the "AS" clause for
3455 ** that column, if there is an AS clause.  If there is no AS clause
3456 ** then the name of the column is unspecified and may change from
3457 ** one release of SQLite to the next.
3458 */
3459 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3460 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3461
3462 /*
3463 ** CAPI3REF: Source Of Data In A Query Result
3464 **
3465 ** ^These routines provide a means to determine the database, table, and
3466 ** table column that is the origin of a particular result column in
3467 ** [SELECT] statement.
3468 ** ^The name of the database or table or column can be returned as
3469 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3470 ** the database name, the _table_ routines return the table name, and
3471 ** the origin_ routines return the column name.
3472 ** ^The returned string is valid until the [prepared statement] is destroyed
3473 ** using [sqlite3_finalize()] or until the same information is requested
3474 ** again in a different encoding.
3475 **
3476 ** ^The names returned are the original un-aliased names of the
3477 ** database, table, and column.
3478 **
3479 ** ^The first argument to these interfaces is a [prepared statement].
3480 ** ^These functions return information about the Nth result column returned by
3481 ** the statement, where N is the second function argument.
3482 ** ^The left-most column is column 0 for these routines.
3483 **
3484 ** ^If the Nth column returned by the statement is an expression or
3485 ** subquery and is not a column value, then all of these functions return
3486 ** NULL.  ^These routine might also return NULL if a memory allocation error
3487 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3488 ** or column that query result column was extracted from.
3489 **
3490 ** ^As with all other SQLite APIs, those whose names end with "16" return
3491 ** UTF-16 encoded strings and the other functions return UTF-8.
3492 **
3493 ** ^These APIs are only available if the library was compiled with the
3494 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3495 **
3496 ** If two or more threads call one or more of these routines against the same
3497 ** prepared statement and column at the same time then the results are
3498 ** undefined.
3499 **
3500 ** If two or more threads call one or more
3501 ** [sqlite3_column_database_name | column metadata interfaces]
3502 ** for the same [prepared statement] and result column
3503 ** at the same time then the results are undefined.
3504 */
3505 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3506 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3507 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3508 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3509 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3510 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3511
3512 /*
3513 ** CAPI3REF: Declared Datatype Of A Query Result
3514 **
3515 ** ^(The first parameter is a [prepared statement].
3516 ** If this statement is a [SELECT] statement and the Nth column of the
3517 ** returned result set of that [SELECT] is a table column (not an
3518 ** expression or subquery) then the declared type of the table
3519 ** column is returned.)^  ^If the Nth column of the result set is an
3520 ** expression or subquery, then a NULL pointer is returned.
3521 ** ^The returned string is always UTF-8 encoded.
3522 **
3523 ** ^(For example, given the database schema:
3524 **
3525 ** CREATE TABLE t1(c1 VARIANT);
3526 **
3527 ** and the following statement to be compiled:
3528 **
3529 ** SELECT c1 + 1, c1 FROM t1;
3530 **
3531 ** this routine would return the string "VARIANT" for the second result
3532 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3533 **
3534 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3535 ** is declared to contain a particular type does not mean that the
3536 ** data stored in that column is of the declared type.  SQLite is
3537 ** strongly typed, but the typing is dynamic not static.  ^Type
3538 ** is associated with individual values, not with the containers
3539 ** used to hold those values.
3540 */
3541 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3542 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3543
3544 /*
3545 ** CAPI3REF: Evaluate An SQL Statement
3546 **
3547 ** After a [prepared statement] has been prepared using either
3548 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3549 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3550 ** must be called one or more times to evaluate the statement.
3551 **
3552 ** The details of the behavior of the sqlite3_step() interface depend
3553 ** on whether the statement was prepared using the newer "v2" interface
3554 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3555 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3556 ** new "v2" interface is recommended for new applications but the legacy
3557 ** interface will continue to be supported.
3558 **
3559 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3560 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3561 ** ^With the "v2" interface, any of the other [result codes] or
3562 ** [extended result codes] might be returned as well.
3563 **
3564 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3565 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3566 ** or occurs outside of an explicit transaction, then you can retry the
3567 ** statement.  If the statement is not a [COMMIT] and occurs within a
3568 ** explicit transaction then you should rollback the transaction before
3569 ** continuing.
3570 **
3571 ** ^[SQLITE_DONE] means that the statement has finished executing
3572 ** successfully.  sqlite3_step() should not be called again on this virtual
3573 ** machine without first calling [sqlite3_reset()] to reset the virtual
3574 ** machine back to its initial state.
3575 **
3576 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3577 ** is returned each time a new row of data is ready for processing by the
3578 ** caller. The values may be accessed using the [column access functions].
3579 ** sqlite3_step() is called again to retrieve the next row of data.
3580 **
3581 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3582 ** violation) has occurred.  sqlite3_step() should not be called again on
3583 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3584 ** ^With the legacy interface, a more specific error code (for example,
3585 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3586 ** can be obtained by calling [sqlite3_reset()] on the
3587 ** [prepared statement].  ^In the "v2" interface,
3588 ** the more specific error code is returned directly by sqlite3_step().
3589 **
3590 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3591 ** Perhaps it was called on a [prepared statement] that has
3592 ** already been [sqlite3_finalize | finalized] or on one that had
3593 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3594 ** be the case that the same database connection is being used by two or
3595 ** more threads at the same moment in time.
3596 **
3597 ** For all versions of SQLite up to and including 3.6.23.1, it was required
3598 ** after sqlite3_step() returned anything other than [SQLITE_ROW] that
3599 ** [sqlite3_reset()] be called before any subsequent invocation of
3600 ** sqlite3_step().  Failure to invoke [sqlite3_reset()] in this way would
3601 ** result in an [SQLITE_MISUSE] return from sqlite3_step().  But after
3602 ** version 3.6.23.1, sqlite3_step() began calling [sqlite3_reset()] 
3603 ** automatically in this circumstance rather than returning [SQLITE_MISUSE].  
3604 **
3605 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3606 ** API always returns a generic error code, [SQLITE_ERROR], following any
3607 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3608 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3609 ** specific [error codes] that better describes the error.
3610 ** We admit that this is a goofy design.  The problem has been fixed
3611 ** with the "v2" interface.  If you prepare all of your SQL statements
3612 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3613 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3614 ** then the more specific [error codes] are returned directly
3615 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3616 */
3617 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3618
3619 /*
3620 ** CAPI3REF: Number of columns in a result set
3621 **
3622 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3623 ** current row of the result set of [prepared statement] P.
3624 ** ^If prepared statement P does not have results ready to return
3625 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3626 ** interfaces) then sqlite3_data_count(P) returns 0.
3627 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3628 **
3629 ** See also: [sqlite3_column_count()]
3630 */
3631 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3632
3633 /*
3634 ** CAPI3REF: Fundamental Datatypes
3635 ** KEYWORDS: SQLITE_TEXT
3636 **
3637 ** ^(Every value in SQLite has one of five fundamental datatypes:
3638 **
3639 ** <ul>
3640 ** <li> 64-bit signed integer
3641 ** <li> 64-bit IEEE floating point number
3642 ** <li> string
3643 ** <li> BLOB
3644 ** <li> NULL
3645 ** </ul>)^
3646 **
3647 ** These constants are codes for each of those types.
3648 **
3649 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3650 ** for a completely different meaning.  Software that links against both
3651 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3652 ** SQLITE_TEXT.
3653 */
3654 #define SQLITE_INTEGER  1
3655 #define SQLITE_FLOAT    2
3656 #define SQLITE_BLOB     4
3657 #define SQLITE_NULL     5
3658 #ifdef SQLITE_TEXT
3659 # undef SQLITE_TEXT
3660 #else
3661 # define SQLITE_TEXT     3
3662 #endif
3663 #define SQLITE3_TEXT     3
3664
3665 /*
3666 ** CAPI3REF: Result Values From A Query
3667 ** KEYWORDS: {column access functions}
3668 **
3669 ** These routines form the "result set" interface.
3670 **
3671 ** ^These routines return information about a single column of the current
3672 ** result row of a query.  ^In every case the first argument is a pointer
3673 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3674 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3675 ** and the second argument is the index of the column for which information
3676 ** should be returned. ^The leftmost column of the result set has the index 0.
3677 ** ^The number of columns in the result can be determined using
3678 ** [sqlite3_column_count()].
3679 **
3680 ** If the SQL statement does not currently point to a valid row, or if the
3681 ** column index is out of range, the result is undefined.
3682 ** These routines may only be called when the most recent call to
3683 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3684 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3685 ** If any of these routines are called after [sqlite3_reset()] or
3686 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3687 ** something other than [SQLITE_ROW], the results are undefined.
3688 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3689 ** are called from a different thread while any of these routines
3690 ** are pending, then the results are undefined.
3691 **
3692 ** ^The sqlite3_column_type() routine returns the
3693 ** [SQLITE_INTEGER | datatype code] for the initial data type
3694 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3695 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3696 ** returned by sqlite3_column_type() is only meaningful if no type
3697 ** conversions have occurred as described below.  After a type conversion,
3698 ** the value returned by sqlite3_column_type() is undefined.  Future
3699 ** versions of SQLite may change the behavior of sqlite3_column_type()
3700 ** following a type conversion.
3701 **
3702 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3703 ** routine returns the number of bytes in that BLOB or string.
3704 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3705 ** the string to UTF-8 and then returns the number of bytes.
3706 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3707 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3708 ** the number of bytes in that string.
3709 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3710 **
3711 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3712 ** routine returns the number of bytes in that BLOB or string.
3713 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3714 ** the string to UTF-16 and then returns the number of bytes.
3715 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3716 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3717 ** the number of bytes in that string.
3718 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3719 **
3720 ** ^The values returned by [sqlite3_column_bytes()] and 
3721 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3722 ** of the string.  ^For clarity: the values returned by
3723 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3724 ** bytes in the string, not the number of characters.
3725 **
3726 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3727 ** even empty strings, are always zero terminated.  ^The return
3728 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3729 **
3730 ** ^The object returned by [sqlite3_column_value()] is an
3731 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3732 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3733 ** If the [unprotected sqlite3_value] object returned by
3734 ** [sqlite3_column_value()] is used in any other way, including calls
3735 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3736 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3737 **
3738 ** These routines attempt to convert the value where appropriate.  ^For
3739 ** example, if the internal representation is FLOAT and a text result
3740 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3741 ** conversion automatically.  ^(The following table details the conversions
3742 ** that are applied:
3743 **
3744 ** <blockquote>
3745 ** <table border="1">
3746 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3747 **
3748 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3749 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3750 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3751 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3752 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3753 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3754 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3755 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3756 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3757 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3758 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3759 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3760 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3761 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3762 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3763 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3764 ** </table>
3765 ** </blockquote>)^
3766 **
3767 ** The table above makes reference to standard C library functions atoi()
3768 ** and atof().  SQLite does not really use these functions.  It has its
3769 ** own equivalent internal routines.  The atoi() and atof() names are
3770 ** used in the table for brevity and because they are familiar to most
3771 ** C programmers.
3772 **
3773 ** Note that when type conversions occur, pointers returned by prior
3774 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3775 ** sqlite3_column_text16() may be invalidated.
3776 ** Type conversions and pointer invalidations might occur
3777 ** in the following cases:
3778 **
3779 ** <ul>
3780 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3781 **      sqlite3_column_text16() is called.  A zero-terminator might
3782 **      need to be added to the string.</li>
3783 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3784 **      sqlite3_column_text16() is called.  The content must be converted
3785 **      to UTF-16.</li>
3786 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3787 **      sqlite3_column_text() is called.  The content must be converted
3788 **      to UTF-8.</li>
3789 ** </ul>
3790 **
3791 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3792 ** not invalidate a prior pointer, though of course the content of the buffer
3793 ** that the prior pointer references will have been modified.  Other kinds
3794 ** of conversion are done in place when it is possible, but sometimes they
3795 ** are not possible and in those cases prior pointers are invalidated.
3796 **
3797 ** The safest and easiest to remember policy is to invoke these routines
3798 ** in one of the following ways:
3799 **
3800 ** <ul>
3801 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3802 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3803 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3804 ** </ul>
3805 **
3806 ** In other words, you should call sqlite3_column_text(),
3807 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3808 ** into the desired format, then invoke sqlite3_column_bytes() or
3809 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3810 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3811 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3812 ** with calls to sqlite3_column_bytes().
3813 **
3814 ** ^The pointers returned are valid until a type conversion occurs as
3815 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3816 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3817 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3818 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3819 ** [sqlite3_free()].
3820 **
3821 ** ^(If a memory allocation error occurs during the evaluation of any
3822 ** of these routines, a default value is returned.  The default value
3823 ** is either the integer 0, the floating point number 0.0, or a NULL
3824 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3825 ** [SQLITE_NOMEM].)^
3826 */
3827 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3828 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3829 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3830 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3831 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3832 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3833 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3834 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3835 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3836 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3837
3838 /*
3839 ** CAPI3REF: Destroy A Prepared Statement Object
3840 **
3841 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3842 ** ^If the most recent evaluation of the statement encountered no errors or
3843 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
3844 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
3845 ** sqlite3_finalize(S) returns the appropriate [error code] or
3846 ** [extended error code].
3847 **
3848 ** ^The sqlite3_finalize(S) routine can be called at any point during
3849 ** the life cycle of [prepared statement] S:
3850 ** before statement S is ever evaluated, after
3851 ** one or more calls to [sqlite3_reset()], or after any call
3852 ** to [sqlite3_step()] regardless of whether or not the statement has
3853 ** completed execution.
3854 **
3855 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3856 **
3857 ** The application must finalize every [prepared statement] in order to avoid
3858 ** resource leaks.  It is a grievous error for the application to try to use
3859 ** a prepared statement after it has been finalized.  Any use of a prepared
3860 ** statement after it has been finalized can result in undefined and
3861 ** undesirable behavior such as segfaults and heap corruption.
3862 */
3863 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3864
3865 /*
3866 ** CAPI3REF: Reset A Prepared Statement Object
3867 **
3868 ** The sqlite3_reset() function is called to reset a [prepared statement]
3869 ** object back to its initial state, ready to be re-executed.
3870 ** ^Any SQL statement variables that had values bound to them using
3871 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3872 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3873 **
3874 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3875 ** back to the beginning of its program.
3876 **
3877 ** ^If the most recent call to [sqlite3_step(S)] for the
3878 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3879 ** or if [sqlite3_step(S)] has never before been called on S,
3880 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3881 **
3882 ** ^If the most recent call to [sqlite3_step(S)] for the
3883 ** [prepared statement] S indicated an error, then
3884 ** [sqlite3_reset(S)] returns an appropriate [error code].
3885 **
3886 ** ^The [sqlite3_reset(S)] interface does not change the values
3887 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3888 */
3889 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3890
3891 /*
3892 ** CAPI3REF: Create Or Redefine SQL Functions
3893 ** KEYWORDS: {function creation routines}
3894 ** KEYWORDS: {application-defined SQL function}
3895 ** KEYWORDS: {application-defined SQL functions}
3896 **
3897 ** ^These functions (collectively known as "function creation routines")
3898 ** are used to add SQL functions or aggregates or to redefine the behavior
3899 ** of existing SQL functions or aggregates.  The only differences between
3900 ** these routines are the text encoding expected for
3901 ** the the second parameter (the name of the function being created)
3902 ** and the presence or absence of a destructor callback for
3903 ** the application data pointer.
3904 **
3905 ** ^The first parameter is the [database connection] to which the SQL
3906 ** function is to be added.  ^If an application uses more than one database
3907 ** connection then application-defined SQL functions must be added
3908 ** to each database connection separately.
3909 **
3910 ** ^The second parameter is the name of the SQL function to be created or
3911 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
3912 ** representation, exclusive of the zero-terminator.  ^Note that the name
3913 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
3914 ** ^Any attempt to create a function with a longer name
3915 ** will result in [SQLITE_MISUSE] being returned.
3916 **
3917 ** ^The third parameter (nArg)
3918 ** is the number of arguments that the SQL function or
3919 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3920 ** aggregate may take any number of arguments between 0 and the limit
3921 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3922 ** parameter is less than -1 or greater than 127 then the behavior is
3923 ** undefined.
3924 **
3925 ** ^The fourth parameter, eTextRep, specifies what
3926 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3927 ** its parameters.  Every SQL function implementation must be able to work
3928 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3929 ** more efficient with one encoding than another.  ^An application may
3930 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3931 ** times with the same function but with different values of eTextRep.
3932 ** ^When multiple implementations of the same function are available, SQLite
3933 ** will pick the one that involves the least amount of data conversion.
3934 ** If there is only a single implementation which does not care what text
3935 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3936 **
3937 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3938 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3939 **
3940 ** ^The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3941 ** pointers to C-language functions that implement the SQL function or
3942 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3943 ** callback only; NULL pointers must be passed as the xStep and xFinal
3944 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3945 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
3946 ** SQL function or aggregate, pass NULL poiners for all three function
3947 ** callbacks.
3948 **
3949 ** ^(If the tenth parameter to sqlite3_create_function_v2() is not NULL,
3950 ** then it is destructor for the application data pointer. 
3951 ** The destructor is invoked when the function is deleted, either by being
3952 ** overloaded or when the database connection closes.)^
3953 ** ^The destructor is also invoked if the call to
3954 ** sqlite3_create_function_v2() fails.
3955 ** ^When the destructor callback of the tenth parameter is invoked, it
3956 ** is passed a single argument which is a copy of the application data 
3957 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
3958 **
3959 ** ^It is permitted to register multiple implementations of the same
3960 ** functions with the same name but with either differing numbers of
3961 ** arguments or differing preferred text encodings.  ^SQLite will use
3962 ** the implementation that most closely matches the way in which the
3963 ** SQL function is used.  ^A function implementation with a non-negative
3964 ** nArg parameter is a better match than a function implementation with
3965 ** a negative nArg.  ^A function where the preferred text encoding
3966 ** matches the database encoding is a better
3967 ** match than a function where the encoding is different.  
3968 ** ^A function where the encoding difference is between UTF16le and UTF16be
3969 ** is a closer match than a function where the encoding difference is
3970 ** between UTF8 and UTF16.
3971 **
3972 ** ^Built-in functions may be overloaded by new application-defined functions.
3973 **
3974 ** ^An application-defined function is permitted to call other
3975 ** SQLite interfaces.  However, such calls must not
3976 ** close the database connection nor finalize or reset the prepared
3977 ** statement in which the function is running.
3978 */
3979 SQLITE_API int sqlite3_create_function(
3980   sqlite3 *db,
3981   const char *zFunctionName,
3982   int nArg,
3983   int eTextRep,
3984   void *pApp,
3985   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3986   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3987   void (*xFinal)(sqlite3_context*)
3988 );
3989 SQLITE_API int sqlite3_create_function16(
3990   sqlite3 *db,
3991   const void *zFunctionName,
3992   int nArg,
3993   int eTextRep,
3994   void *pApp,
3995   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3996   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3997   void (*xFinal)(sqlite3_context*)
3998 );
3999 SQLITE_API int sqlite3_create_function_v2(
4000   sqlite3 *db,
4001   const char *zFunctionName,
4002   int nArg,
4003   int eTextRep,
4004   void *pApp,
4005   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4006   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4007   void (*xFinal)(sqlite3_context*),
4008   void(*xDestroy)(void*)
4009 );
4010
4011 /*
4012 ** CAPI3REF: Text Encodings
4013 **
4014 ** These constant define integer codes that represent the various
4015 ** text encodings supported by SQLite.
4016 */
4017 #define SQLITE_UTF8           1
4018 #define SQLITE_UTF16LE        2
4019 #define SQLITE_UTF16BE        3
4020 #define SQLITE_UTF16          4    /* Use native byte order */
4021 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4022 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4023
4024 /*
4025 ** CAPI3REF: Deprecated Functions
4026 ** DEPRECATED
4027 **
4028 ** These functions are [deprecated].  In order to maintain
4029 ** backwards compatibility with older code, these functions continue 
4030 ** to be supported.  However, new applications should avoid
4031 ** the use of these functions.  To help encourage people to avoid
4032 ** using these functions, we are not going to tell you what they do.
4033 */
4034 #ifndef SQLITE_OMIT_DEPRECATED
4035 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4036 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4037 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4038 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4039 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4040 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4041 #endif
4042
4043 /*
4044 ** CAPI3REF: Obtaining SQL Function Parameter Values
4045 **
4046 ** The C-language implementation of SQL functions and aggregates uses
4047 ** this set of interface routines to access the parameter values on
4048 ** the function or aggregate.
4049 **
4050 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4051 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4052 ** define callbacks that implement the SQL functions and aggregates.
4053 ** The 4th parameter to these callbacks is an array of pointers to
4054 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4055 ** each parameter to the SQL function.  These routines are used to
4056 ** extract values from the [sqlite3_value] objects.
4057 **
4058 ** These routines work only with [protected sqlite3_value] objects.
4059 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4060 ** object results in undefined behavior.
4061 **
4062 ** ^These routines work just like the corresponding [column access functions]
4063 ** except that  these routines take a single [protected sqlite3_value] object
4064 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4065 **
4066 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4067 ** in the native byte-order of the host machine.  ^The
4068 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4069 ** extract UTF-16 strings as big-endian and little-endian respectively.
4070 **
4071 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4072 ** numeric affinity to the value.  This means that an attempt is
4073 ** made to convert the value to an integer or floating point.  If
4074 ** such a conversion is possible without loss of information (in other
4075 ** words, if the value is a string that looks like a number)
4076 ** then the conversion is performed.  Otherwise no conversion occurs.
4077 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4078 **
4079 ** Please pay particular attention to the fact that the pointer returned
4080 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4081 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4082 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4083 ** or [sqlite3_value_text16()].
4084 **
4085 ** These routines must be called from the same thread as
4086 ** the SQL function that supplied the [sqlite3_value*] parameters.
4087 */
4088 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4089 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4090 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4091 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4092 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4093 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4094 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4095 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4096 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4097 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4098 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4099 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4100
4101 /*
4102 ** CAPI3REF: Obtain Aggregate Function Context
4103 **
4104 ** Implementations of aggregate SQL functions use this
4105 ** routine to allocate memory for storing their state.
4106 **
4107 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4108 ** for a particular aggregate function, SQLite
4109 ** allocates N of memory, zeroes out that memory, and returns a pointer
4110 ** to the new memory. ^On second and subsequent calls to
4111 ** sqlite3_aggregate_context() for the same aggregate function instance,
4112 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4113 ** called once for each invocation of the xStep callback and then one
4114 ** last time when the xFinal callback is invoked.  ^(When no rows match
4115 ** an aggregate query, the xStep() callback of the aggregate function
4116 ** implementation is never called and xFinal() is called exactly once.
4117 ** In those cases, sqlite3_aggregate_context() might be called for the
4118 ** first time from within xFinal().)^
4119 **
4120 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4121 ** less than or equal to zero or if a memory allocate error occurs.
4122 **
4123 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4124 ** determined by the N parameter on first successful call.  Changing the
4125 ** value of N in subsequent call to sqlite3_aggregate_context() within
4126 ** the same aggregate function instance will not resize the memory
4127 ** allocation.)^
4128 **
4129 ** ^SQLite automatically frees the memory allocated by 
4130 ** sqlite3_aggregate_context() when the aggregate query concludes.
4131 **
4132 ** The first parameter must be a copy of the
4133 ** [sqlite3_context | SQL function context] that is the first parameter
4134 ** to the xStep or xFinal callback routine that implements the aggregate
4135 ** function.
4136 **
4137 ** This routine must be called from the same thread in which
4138 ** the aggregate SQL function is running.
4139 */
4140 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4141
4142 /*
4143 ** CAPI3REF: User Data For Functions
4144 **
4145 ** ^The sqlite3_user_data() interface returns a copy of
4146 ** the pointer that was the pUserData parameter (the 5th parameter)
4147 ** of the [sqlite3_create_function()]
4148 ** and [sqlite3_create_function16()] routines that originally
4149 ** registered the application defined function.
4150 **
4151 ** This routine must be called from the same thread in which
4152 ** the application-defined function is running.
4153 */
4154 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4155
4156 /*
4157 ** CAPI3REF: Database Connection For Functions
4158 **
4159 ** ^The sqlite3_context_db_handle() interface returns a copy of
4160 ** the pointer to the [database connection] (the 1st parameter)
4161 ** of the [sqlite3_create_function()]
4162 ** and [sqlite3_create_function16()] routines that originally
4163 ** registered the application defined function.
4164 */
4165 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4166
4167 /*
4168 ** CAPI3REF: Function Auxiliary Data
4169 **
4170 ** The following two functions may be used by scalar SQL functions to
4171 ** associate metadata with argument values. If the same value is passed to
4172 ** multiple invocations of the same SQL function during query execution, under
4173 ** some circumstances the associated metadata may be preserved. This may
4174 ** be used, for example, to add a regular-expression matching scalar
4175 ** function. The compiled version of the regular expression is stored as
4176 ** metadata associated with the SQL value passed as the regular expression
4177 ** pattern.  The compiled regular expression can be reused on multiple
4178 ** invocations of the same function so that the original pattern string
4179 ** does not need to be recompiled on each invocation.
4180 **
4181 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4182 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4183 ** value to the application-defined function. ^If no metadata has been ever
4184 ** been set for the Nth argument of the function, or if the corresponding
4185 ** function parameter has changed since the meta-data was set,
4186 ** then sqlite3_get_auxdata() returns a NULL pointer.
4187 **
4188 ** ^The sqlite3_set_auxdata() interface saves the metadata
4189 ** pointed to by its 3rd parameter as the metadata for the N-th
4190 ** argument of the application-defined function.  Subsequent
4191 ** calls to sqlite3_get_auxdata() might return this data, if it has
4192 ** not been destroyed.
4193 ** ^If it is not NULL, SQLite will invoke the destructor
4194 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4195 ** the metadata when the corresponding function parameter changes
4196 ** or when the SQL statement completes, whichever comes first.
4197 **
4198 ** SQLite is free to call the destructor and drop metadata on any
4199 ** parameter of any function at any time.  ^The only guarantee is that
4200 ** the destructor will be called before the metadata is dropped.
4201 **
4202 ** ^(In practice, metadata is preserved between function calls for
4203 ** expressions that are constant at compile time. This includes literal
4204 ** values and [parameters].)^
4205 **
4206 ** These routines must be called from the same thread in which
4207 ** the SQL function is running.
4208 */
4209 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4210 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4211
4212
4213 /*
4214 ** CAPI3REF: Constants Defining Special Destructor Behavior
4215 **
4216 ** These are special values for the destructor that is passed in as the
4217 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4218 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4219 ** and will never change.  It does not need to be destroyed.  ^The
4220 ** SQLITE_TRANSIENT value means that the content will likely change in
4221 ** the near future and that SQLite should make its own private copy of
4222 ** the content before returning.
4223 **
4224 ** The typedef is necessary to work around problems in certain
4225 ** C++ compilers.  See ticket #2191.
4226 */
4227 typedef void (*sqlite3_destructor_type)(void*);
4228 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4229 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4230
4231 /*
4232 ** CAPI3REF: Setting The Result Of An SQL Function
4233 **
4234 ** These routines are used by the xFunc or xFinal callbacks that
4235 ** implement SQL functions and aggregates.  See
4236 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4237 ** for additional information.
4238 **
4239 ** These functions work very much like the [parameter binding] family of
4240 ** functions used to bind values to host parameters in prepared statements.
4241 ** Refer to the [SQL parameter] documentation for additional information.
4242 **
4243 ** ^The sqlite3_result_blob() interface sets the result from
4244 ** an application-defined function to be the BLOB whose content is pointed
4245 ** to by the second parameter and which is N bytes long where N is the
4246 ** third parameter.
4247 **
4248 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4249 ** the application-defined function to be a BLOB containing all zero
4250 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4251 **
4252 ** ^The sqlite3_result_double() interface sets the result from
4253 ** an application-defined function to be a floating point value specified
4254 ** by its 2nd argument.
4255 **
4256 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4257 ** cause the implemented SQL function to throw an exception.
4258 ** ^SQLite uses the string pointed to by the
4259 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4260 ** as the text of an error message.  ^SQLite interprets the error
4261 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4262 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4263 ** byte order.  ^If the third parameter to sqlite3_result_error()
4264 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4265 ** message all text up through the first zero character.
4266 ** ^If the third parameter to sqlite3_result_error() or
4267 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4268 ** bytes (not characters) from the 2nd parameter as the error message.
4269 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4270 ** routines make a private copy of the error message text before
4271 ** they return.  Hence, the calling function can deallocate or
4272 ** modify the text after they return without harm.
4273 ** ^The sqlite3_result_error_code() function changes the error code
4274 ** returned by SQLite as a result of an error in a function.  ^By default,
4275 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4276 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4277 **
4278 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4279 ** indicating that a string or BLOB is too long to represent.
4280 **
4281 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4282 ** indicating that a memory allocation failed.
4283 **
4284 ** ^The sqlite3_result_int() interface sets the return value
4285 ** of the application-defined function to be the 32-bit signed integer
4286 ** value given in the 2nd argument.
4287 ** ^The sqlite3_result_int64() interface sets the return value
4288 ** of the application-defined function to be the 64-bit signed integer
4289 ** value given in the 2nd argument.
4290 **
4291 ** ^The sqlite3_result_null() interface sets the return value
4292 ** of the application-defined function to be NULL.
4293 **
4294 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4295 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4296 ** set the return value of the application-defined function to be
4297 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4298 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4299 ** ^SQLite takes the text result from the application from
4300 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4301 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4302 ** is negative, then SQLite takes result text from the 2nd parameter
4303 ** through the first zero character.
4304 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4305 ** is non-negative, then as many bytes (not characters) of the text
4306 ** pointed to by the 2nd parameter are taken as the application-defined
4307 ** function result.
4308 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4309 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4310 ** function as the destructor on the text or BLOB result when it has
4311 ** finished using that result.
4312 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4313 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4314 ** assumes that the text or BLOB result is in constant space and does not
4315 ** copy the content of the parameter nor call a destructor on the content
4316 ** when it has finished using that result.
4317 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4318 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4319 ** then SQLite makes a copy of the result into space obtained from
4320 ** from [sqlite3_malloc()] before it returns.
4321 **
4322 ** ^The sqlite3_result_value() interface sets the result of
4323 ** the application-defined function to be a copy the
4324 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4325 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4326 ** so that the [sqlite3_value] specified in the parameter may change or
4327 ** be deallocated after sqlite3_result_value() returns without harm.
4328 ** ^A [protected sqlite3_value] object may always be used where an
4329 ** [unprotected sqlite3_value] object is required, so either
4330 ** kind of [sqlite3_value] object can be used with this interface.
4331 **
4332 ** If these routines are called from within the different thread
4333 ** than the one containing the application-defined function that received
4334 ** the [sqlite3_context] pointer, the results are undefined.
4335 */
4336 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4337 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4338 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4339 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4340 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4341 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4342 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4343 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4344 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4345 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4346 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4347 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4348 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4349 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4350 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4351 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4352
4353 /*
4354 ** CAPI3REF: Define New Collating Sequences
4355 **
4356 ** ^These functions add, remove, or modify a [collation] associated
4357 ** with the [database connection] specified as the first argument.
4358 **
4359 ** ^The name of the collation is a UTF-8 string
4360 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4361 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4362 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4363 ** considered to be the same name.
4364 **
4365 ** ^(The third argument (eTextRep) must be one of the constants:
4366 ** <ul>
4367 ** <li> [SQLITE_UTF8],
4368 ** <li> [SQLITE_UTF16LE],
4369 ** <li> [SQLITE_UTF16BE],
4370 ** <li> [SQLITE_UTF16], or
4371 ** <li> [SQLITE_UTF16_ALIGNED].
4372 ** </ul>)^
4373 ** ^The eTextRep argument determines the encoding of strings passed
4374 ** to the collating function callback, xCallback.
4375 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4376 ** force strings to be UTF16 with native byte order.
4377 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4378 ** on an even byte address.
4379 **
4380 ** ^The fourth argument, pArg, is a application data pointer that is passed
4381 ** through as the first argument to the collating function callback.
4382 **
4383 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4384 ** ^Multiple collating functions can be registered using the same name but
4385 ** with different eTextRep parameters and SQLite will use whichever
4386 ** function requires the least amount of data transformation.
4387 ** ^If the xCallback argument is NULL then the collating function is
4388 ** deleted.  ^When all collating functions having the same name are deleted,
4389 ** that collation is no longer usable.
4390 **
4391 ** ^The collating function callback is invoked with a copy of the pArg 
4392 ** application data pointer and with two strings in the encoding specified
4393 ** by the eTextRep argument.  The collating function must return an
4394 ** integer that is negative, zero, or positive
4395 ** if the first string is less than, equal to, or greater than the second,
4396 ** respectively.  A collating function must alway return the same answer
4397 ** given the same inputs.  If two or more collating functions are registered
4398 ** to the same collation name (using different eTextRep values) then all
4399 ** must give an equivalent answer when invoked with equivalent strings.
4400 ** The collating function must obey the following properties for all
4401 ** strings A, B, and C:
4402 **
4403 ** <ol>
4404 ** <li> If A==B then B==A.
4405 ** <li> If A==B and B==C then A==C.
4406 ** <li> If A&lt;B THEN B&gt;A.
4407 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4408 ** </ol>
4409 **
4410 ** If a collating function fails any of the above constraints and that
4411 ** collating function is  registered and used, then the behavior of SQLite
4412 ** is undefined.
4413 **
4414 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4415 ** with the addition that the xDestroy callback is invoked on pArg when
4416 ** the collating function is deleted.
4417 ** ^Collating functions are deleted when they are overridden by later
4418 ** calls to the collation creation functions or when the
4419 ** [database connection] is closed using [sqlite3_close()].
4420 **
4421 ** ^The xDestroy callback is <u>not</u> called if the 
4422 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4423 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
4424 ** check the return code and dispose of the application data pointer
4425 ** themselves rather than expecting SQLite to deal with it for them.
4426 ** This is different from every other SQLite interface.  The inconsistency 
4427 ** is unfortunate but cannot be changed without breaking backwards 
4428 ** compatibility.
4429 **
4430 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4431 */
4432 SQLITE_API int sqlite3_create_collation(
4433   sqlite3*, 
4434   const char *zName, 
4435   int eTextRep, 
4436   void *pArg,
4437   int(*xCompare)(void*,int,const void*,int,const void*)
4438 );
4439 SQLITE_API int sqlite3_create_collation_v2(
4440   sqlite3*, 
4441   const char *zName, 
4442   int eTextRep, 
4443   void *pArg,
4444   int(*xCompare)(void*,int,const void*,int,const void*),
4445   void(*xDestroy)(void*)
4446 );
4447 SQLITE_API int sqlite3_create_collation16(
4448   sqlite3*, 
4449   const void *zName,
4450   int eTextRep, 
4451   void *pArg,
4452   int(*xCompare)(void*,int,const void*,int,const void*)
4453 );
4454
4455 /*
4456 ** CAPI3REF: Collation Needed Callbacks
4457 **
4458 ** ^To avoid having to register all collation sequences before a database
4459 ** can be used, a single callback function may be registered with the
4460 ** [database connection] to be invoked whenever an undefined collation
4461 ** sequence is required.
4462 **
4463 ** ^If the function is registered using the sqlite3_collation_needed() API,
4464 ** then it is passed the names of undefined collation sequences as strings
4465 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4466 ** the names are passed as UTF-16 in machine native byte order.
4467 ** ^A call to either function replaces the existing collation-needed callback.
4468 **
4469 ** ^(When the callback is invoked, the first argument passed is a copy
4470 ** of the second argument to sqlite3_collation_needed() or
4471 ** sqlite3_collation_needed16().  The second argument is the database
4472 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4473 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4474 ** sequence function required.  The fourth parameter is the name of the
4475 ** required collation sequence.)^
4476 **
4477 ** The callback function should register the desired collation using
4478 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4479 ** [sqlite3_create_collation_v2()].
4480 */
4481 SQLITE_API int sqlite3_collation_needed(
4482   sqlite3*, 
4483   void*, 
4484   void(*)(void*,sqlite3*,int eTextRep,const char*)
4485 );
4486 SQLITE_API int sqlite3_collation_needed16(
4487   sqlite3*, 
4488   void*,
4489   void(*)(void*,sqlite3*,int eTextRep,const void*)
4490 );
4491
4492 #ifdef SQLITE_HAS_CODEC
4493 /*
4494 ** Specify the key for an encrypted database.  This routine should be
4495 ** called right after sqlite3_open().
4496 **
4497 ** The code to implement this API is not available in the public release
4498 ** of SQLite.
4499 */
4500 SQLITE_API int sqlite3_key(
4501   sqlite3 *db,                   /* Database to be rekeyed */
4502   const void *pKey, int nKey     /* The key */
4503 );
4504
4505 /*
4506 ** Change the key on an open database.  If the current database is not
4507 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4508 ** database is decrypted.
4509 **
4510 ** The code to implement this API is not available in the public release
4511 ** of SQLite.
4512 */
4513 SQLITE_API int sqlite3_rekey(
4514   sqlite3 *db,                   /* Database to be rekeyed */
4515   const void *pKey, int nKey     /* The new key */
4516 );
4517
4518 /*
4519 ** Specify the activation key for a SEE database.  Unless 
4520 ** activated, none of the SEE routines will work.
4521 */
4522 SQLITE_API void sqlite3_activate_see(
4523   const char *zPassPhrase        /* Activation phrase */
4524 );
4525 #endif
4526
4527 #ifdef SQLITE_ENABLE_CEROD
4528 /*
4529 ** Specify the activation key for a CEROD database.  Unless 
4530 ** activated, none of the CEROD routines will work.
4531 */
4532 SQLITE_API void sqlite3_activate_cerod(
4533   const char *zPassPhrase        /* Activation phrase */
4534 );
4535 #endif
4536
4537 /*
4538 ** CAPI3REF: Suspend Execution For A Short Time
4539 **
4540 ** The sqlite3_sleep() function causes the current thread to suspend execution
4541 ** for at least a number of milliseconds specified in its parameter.
4542 **
4543 ** If the operating system does not support sleep requests with
4544 ** millisecond time resolution, then the time will be rounded up to
4545 ** the nearest second. The number of milliseconds of sleep actually
4546 ** requested from the operating system is returned.
4547 **
4548 ** ^SQLite implements this interface by calling the xSleep()
4549 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
4550 ** of the default VFS is not implemented correctly, or not implemented at
4551 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4552 ** in the previous paragraphs.
4553 */
4554 SQLITE_API int sqlite3_sleep(int);
4555
4556 /*
4557 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4558 **
4559 ** ^(If this global variable is made to point to a string which is
4560 ** the name of a folder (a.k.a. directory), then all temporary files
4561 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4562 ** will be placed in that directory.)^  ^If this variable
4563 ** is a NULL pointer, then SQLite performs a search for an appropriate
4564 ** temporary file directory.
4565 **
4566 ** It is not safe to read or modify this variable in more than one
4567 ** thread at a time.  It is not safe to read or modify this variable
4568 ** if a [database connection] is being used at the same time in a separate
4569 ** thread.
4570 ** It is intended that this variable be set once
4571 ** as part of process initialization and before any SQLite interface
4572 ** routines have been called and that this variable remain unchanged
4573 ** thereafter.
4574 **
4575 ** ^The [temp_store_directory pragma] may modify this variable and cause
4576 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4577 ** the [temp_store_directory pragma] always assumes that any string
4578 ** that this variable points to is held in memory obtained from 
4579 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4580 ** using [sqlite3_free].
4581 ** Hence, if this variable is modified directly, either it should be
4582 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4583 ** or else the use of the [temp_store_directory pragma] should be avoided.
4584 */
4585 SQLITE_API char *sqlite3_temp_directory;
4586
4587 /*
4588 ** CAPI3REF: Test For Auto-Commit Mode
4589 ** KEYWORDS: {autocommit mode}
4590 **
4591 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4592 ** zero if the given database connection is or is not in autocommit mode,
4593 ** respectively.  ^Autocommit mode is on by default.
4594 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4595 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4596 **
4597 ** If certain kinds of errors occur on a statement within a multi-statement
4598 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4599 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4600 ** transaction might be rolled back automatically.  The only way to
4601 ** find out whether SQLite automatically rolled back the transaction after
4602 ** an error is to use this function.
4603 **
4604 ** If another thread changes the autocommit status of the database
4605 ** connection while this routine is running, then the return value
4606 ** is undefined.
4607 */
4608 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4609
4610 /*
4611 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4612 **
4613 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4614 ** to which a [prepared statement] belongs.  ^The [database connection]
4615 ** returned by sqlite3_db_handle is the same [database connection]
4616 ** that was the first argument
4617 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4618 ** create the statement in the first place.
4619 */
4620 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4621
4622 /*
4623 ** CAPI3REF: Find the next prepared statement
4624 **
4625 ** ^This interface returns a pointer to the next [prepared statement] after
4626 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4627 ** then this interface returns a pointer to the first prepared statement
4628 ** associated with the database connection pDb.  ^If no prepared statement
4629 ** satisfies the conditions of this routine, it returns NULL.
4630 **
4631 ** The [database connection] pointer D in a call to
4632 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4633 ** connection and in particular must not be a NULL pointer.
4634 */
4635 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4636
4637 /*
4638 ** CAPI3REF: Commit And Rollback Notification Callbacks
4639 **
4640 ** ^The sqlite3_commit_hook() interface registers a callback
4641 ** function to be invoked whenever a transaction is [COMMIT | committed].
4642 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4643 ** for the same database connection is overridden.
4644 ** ^The sqlite3_rollback_hook() interface registers a callback
4645 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4646 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4647 ** for the same database connection is overridden.
4648 ** ^The pArg argument is passed through to the callback.
4649 ** ^If the callback on a commit hook function returns non-zero,
4650 ** then the commit is converted into a rollback.
4651 **
4652 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4653 ** return the P argument from the previous call of the same function
4654 ** on the same [database connection] D, or NULL for
4655 ** the first call for each function on D.
4656 **
4657 ** The callback implementation must not do anything that will modify
4658 ** the database connection that invoked the callback.  Any actions
4659 ** to modify the database connection must be deferred until after the
4660 ** completion of the [sqlite3_step()] call that triggered the commit
4661 ** or rollback hook in the first place.
4662 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4663 ** database connections for the meaning of "modify" in this paragraph.
4664 **
4665 ** ^Registering a NULL function disables the callback.
4666 **
4667 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4668 ** operation is allowed to continue normally.  ^If the commit hook
4669 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4670 ** ^The rollback hook is invoked on a rollback that results from a commit
4671 ** hook returning non-zero, just as it would be with any other rollback.
4672 **
4673 ** ^For the purposes of this API, a transaction is said to have been
4674 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4675 ** an error or constraint causes an implicit rollback to occur.
4676 ** ^The rollback callback is not invoked if a transaction is
4677 ** automatically rolled back because the database connection is closed.
4678 **
4679 ** See also the [sqlite3_update_hook()] interface.
4680 */
4681 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4682 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4683
4684 /*
4685 ** CAPI3REF: Data Change Notification Callbacks
4686 **
4687 ** ^The sqlite3_update_hook() interface registers a callback function
4688 ** with the [database connection] identified by the first argument
4689 ** to be invoked whenever a row is updated, inserted or deleted.
4690 ** ^Any callback set by a previous call to this function
4691 ** for the same database connection is overridden.
4692 **
4693 ** ^The second argument is a pointer to the function to invoke when a
4694 ** row is updated, inserted or deleted.
4695 ** ^The first argument to the callback is a copy of the third argument
4696 ** to sqlite3_update_hook().
4697 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4698 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4699 ** to be invoked.
4700 ** ^The third and fourth arguments to the callback contain pointers to the
4701 ** database and table name containing the affected row.
4702 ** ^The final callback parameter is the [rowid] of the row.
4703 ** ^In the case of an update, this is the [rowid] after the update takes place.
4704 **
4705 ** ^(The update hook is not invoked when internal system tables are
4706 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4707 **
4708 ** ^In the current implementation, the update hook
4709 ** is not invoked when duplication rows are deleted because of an
4710 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4711 ** invoked when rows are deleted using the [truncate optimization].
4712 ** The exceptions defined in this paragraph might change in a future
4713 ** release of SQLite.
4714 **
4715 ** The update hook implementation must not do anything that will modify
4716 ** the database connection that invoked the update hook.  Any actions
4717 ** to modify the database connection must be deferred until after the
4718 ** completion of the [sqlite3_step()] call that triggered the update hook.
4719 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4720 ** database connections for the meaning of "modify" in this paragraph.
4721 **
4722 ** ^The sqlite3_update_hook(D,C,P) function
4723 ** returns the P argument from the previous call
4724 ** on the same [database connection] D, or NULL for
4725 ** the first call on D.
4726 **
4727 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4728 ** interfaces.
4729 */
4730 SQLITE_API void *sqlite3_update_hook(
4731   sqlite3*, 
4732   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4733   void*
4734 );
4735
4736 /*
4737 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4738 ** KEYWORDS: {shared cache}
4739 **
4740 ** ^(This routine enables or disables the sharing of the database cache
4741 ** and schema data structures between [database connection | connections]
4742 ** to the same database. Sharing is enabled if the argument is true
4743 ** and disabled if the argument is false.)^
4744 **
4745 ** ^Cache sharing is enabled and disabled for an entire process.
4746 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4747 ** sharing was enabled or disabled for each thread separately.
4748 **
4749 ** ^(The cache sharing mode set by this interface effects all subsequent
4750 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4751 ** Existing database connections continue use the sharing mode
4752 ** that was in effect at the time they were opened.)^
4753 **
4754 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4755 ** successfully.  An [error code] is returned otherwise.)^
4756 **
4757 ** ^Shared cache is disabled by default. But this might change in
4758 ** future releases of SQLite.  Applications that care about shared
4759 ** cache setting should set it explicitly.
4760 **
4761 ** See Also:  [SQLite Shared-Cache Mode]
4762 */
4763 SQLITE_API int sqlite3_enable_shared_cache(int);
4764
4765 /*
4766 ** CAPI3REF: Attempt To Free Heap Memory
4767 **
4768 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4769 ** of heap memory by deallocating non-essential memory allocations
4770 ** held by the database library.   Memory used to cache database
4771 ** pages to improve performance is an example of non-essential memory.
4772 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4773 ** which might be more or less than the amount requested.
4774 ** ^The sqlite3_release_memory() routine is a no-op returning zero
4775 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4776 */
4777 SQLITE_API int sqlite3_release_memory(int);
4778
4779 /*
4780 ** CAPI3REF: Impose A Limit On Heap Size
4781 **
4782 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
4783 ** soft limit on the amount of heap memory that may be allocated by SQLite.
4784 ** ^SQLite strives to keep heap memory utilization below the soft heap
4785 ** limit by reducing the number of pages held in the page cache
4786 ** as heap memory usages approaches the limit.
4787 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
4788 ** below the limit, it will exceed the limit rather than generate
4789 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
4790 ** is advisory only.
4791 **
4792 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
4793 ** the soft heap limit prior to the call.  ^If the argument N is negative
4794 ** then no change is made to the soft heap limit.  Hence, the current
4795 ** size of the soft heap limit can be determined by invoking
4796 ** sqlite3_soft_heap_limit64() with a negative argument.
4797 **
4798 ** ^If the argument N is zero then the soft heap limit is disabled.
4799 **
4800 ** ^(The soft heap limit is not enforced in the current implementation
4801 ** if one or more of following conditions are true:
4802 **
4803 ** <ul>
4804 ** <li> The soft heap limit is set to zero.
4805 ** <li> Memory accounting is disabled using a combination of the
4806 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
4807 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
4808 ** <li> An alternative page cache implementation is specifed using
4809 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
4810 ** <li> The page cache allocates from its own memory pool supplied
4811 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
4812 **      from the heap.
4813 ** </ul>)^
4814 **
4815 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
4816 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
4817 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
4818 ** the soft heap limit is enforced on every memory allocation.  Without
4819 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
4820 ** when memory is allocated by the page cache.  Testing suggests that because
4821 ** the page cache is the predominate memory user in SQLite, most
4822 ** applications will achieve adequate soft heap limit enforcement without
4823 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4824 **
4825 ** The circumstances under which SQLite will enforce the soft heap limit may
4826 ** changes in future releases of SQLite.
4827 */
4828 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
4829
4830 /*
4831 ** CAPI3REF: Deprecated Soft Heap Limit Interface
4832 ** DEPRECATED
4833 **
4834 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
4835 ** interface.  This routine is provided for historical compatibility
4836 ** only.  All new applications should use the
4837 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
4838 */
4839 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
4840
4841
4842 /*
4843 ** CAPI3REF: Extract Metadata About A Column Of A Table
4844 **
4845 ** ^This routine returns metadata about a specific column of a specific
4846 ** database table accessible using the [database connection] handle
4847 ** passed as the first function argument.
4848 **
4849 ** ^The column is identified by the second, third and fourth parameters to
4850 ** this function. ^The second parameter is either the name of the database
4851 ** (i.e. "main", "temp", or an attached database) containing the specified
4852 ** table or NULL. ^If it is NULL, then all attached databases are searched
4853 ** for the table using the same algorithm used by the database engine to
4854 ** resolve unqualified table references.
4855 **
4856 ** ^The third and fourth parameters to this function are the table and column
4857 ** name of the desired column, respectively. Neither of these parameters
4858 ** may be NULL.
4859 **
4860 ** ^Metadata is returned by writing to the memory locations passed as the 5th
4861 ** and subsequent parameters to this function. ^Any of these arguments may be
4862 ** NULL, in which case the corresponding element of metadata is omitted.
4863 **
4864 ** ^(<blockquote>
4865 ** <table border="1">
4866 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
4867 **
4868 ** <tr><td> 5th <td> const char* <td> Data type
4869 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4870 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4871 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4872 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4873 ** </table>
4874 ** </blockquote>)^
4875 **
4876 ** ^The memory pointed to by the character pointers returned for the
4877 ** declaration type and collation sequence is valid only until the next
4878 ** call to any SQLite API function.
4879 **
4880 ** ^If the specified table is actually a view, an [error code] is returned.
4881 **
4882 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4883 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4884 ** parameters are set for the explicitly declared column. ^(If there is no
4885 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4886 ** parameters are set as follows:
4887 **
4888 ** <pre>
4889 **     data type: "INTEGER"
4890 **     collation sequence: "BINARY"
4891 **     not null: 0
4892 **     primary key: 1
4893 **     auto increment: 0
4894 ** </pre>)^
4895 **
4896 ** ^(This function may load one or more schemas from database files. If an
4897 ** error occurs during this process, or if the requested table or column
4898 ** cannot be found, an [error code] is returned and an error message left
4899 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4900 **
4901 ** ^This API is only available if the library was compiled with the
4902 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4903 */
4904 SQLITE_API int sqlite3_table_column_metadata(
4905   sqlite3 *db,                /* Connection handle */
4906   const char *zDbName,        /* Database name or NULL */
4907   const char *zTableName,     /* Table name */
4908   const char *zColumnName,    /* Column name */
4909   char const **pzDataType,    /* OUTPUT: Declared data type */
4910   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4911   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4912   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4913   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4914 );
4915
4916 /*
4917 ** CAPI3REF: Load An Extension
4918 **
4919 ** ^This interface loads an SQLite extension library from the named file.
4920 **
4921 ** ^The sqlite3_load_extension() interface attempts to load an
4922 ** SQLite extension library contained in the file zFile.
4923 **
4924 ** ^The entry point is zProc.
4925 ** ^zProc may be 0, in which case the name of the entry point
4926 ** defaults to "sqlite3_extension_init".
4927 ** ^The sqlite3_load_extension() interface returns
4928 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4929 ** ^If an error occurs and pzErrMsg is not 0, then the
4930 ** [sqlite3_load_extension()] interface shall attempt to
4931 ** fill *pzErrMsg with error message text stored in memory
4932 ** obtained from [sqlite3_malloc()]. The calling function
4933 ** should free this memory by calling [sqlite3_free()].
4934 **
4935 ** ^Extension loading must be enabled using
4936 ** [sqlite3_enable_load_extension()] prior to calling this API,
4937 ** otherwise an error will be returned.
4938 **
4939 ** See also the [load_extension() SQL function].
4940 */
4941 SQLITE_API int sqlite3_load_extension(
4942   sqlite3 *db,          /* Load the extension into this database connection */
4943   const char *zFile,    /* Name of the shared library containing extension */
4944   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4945   char **pzErrMsg       /* Put error message here if not 0 */
4946 );
4947
4948 /*
4949 ** CAPI3REF: Enable Or Disable Extension Loading
4950 **
4951 ** ^So as not to open security holes in older applications that are
4952 ** unprepared to deal with extension loading, and as a means of disabling
4953 ** extension loading while evaluating user-entered SQL, the following API
4954 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4955 **
4956 ** ^Extension loading is off by default. See ticket #1863.
4957 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4958 ** to turn extension loading on and call it with onoff==0 to turn
4959 ** it back off again.
4960 */
4961 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4962
4963 /*
4964 ** CAPI3REF: Automatically Load Statically Linked Extensions
4965 **
4966 ** ^This interface causes the xEntryPoint() function to be invoked for
4967 ** each new [database connection] that is created.  The idea here is that
4968 ** xEntryPoint() is the entry point for a statically linked SQLite extension
4969 ** that is to be automatically loaded into all new database connections.
4970 **
4971 ** ^(Even though the function prototype shows that xEntryPoint() takes
4972 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
4973 ** arguments and expects and integer result as if the signature of the
4974 ** entry point where as follows:
4975 **
4976 ** <blockquote><pre>
4977 ** &nbsp;  int xEntryPoint(
4978 ** &nbsp;    sqlite3 *db,
4979 ** &nbsp;    const char **pzErrMsg,
4980 ** &nbsp;    const struct sqlite3_api_routines *pThunk
4981 ** &nbsp;  );
4982 ** </pre></blockquote>)^
4983 **
4984 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
4985 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
4986 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
4987 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
4988 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
4989 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
4990 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
4991 **
4992 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
4993 ** on the list of automatic extensions is a harmless no-op. ^No entry point
4994 ** will be called more than once for each database connection that is opened.
4995 **
4996 ** See also: [sqlite3_reset_auto_extension()].
4997 */
4998 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4999
5000 /*
5001 ** CAPI3REF: Reset Automatic Extension Loading
5002 **
5003 ** ^This interface disables all automatic extensions previously
5004 ** registered using [sqlite3_auto_extension()].
5005 */
5006 SQLITE_API void sqlite3_reset_auto_extension(void);
5007
5008 /*
5009 ** The interface to the virtual-table mechanism is currently considered
5010 ** to be experimental.  The interface might change in incompatible ways.
5011 ** If this is a problem for you, do not use the interface at this time.
5012 **
5013 ** When the virtual-table mechanism stabilizes, we will declare the
5014 ** interface fixed, support it indefinitely, and remove this comment.
5015 */
5016
5017 /*
5018 ** Structures used by the virtual table interface
5019 */
5020 typedef struct sqlite3_vtab sqlite3_vtab;
5021 typedef struct sqlite3_index_info sqlite3_index_info;
5022 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5023 typedef struct sqlite3_module sqlite3_module;
5024
5025 /*
5026 ** CAPI3REF: Virtual Table Object
5027 ** KEYWORDS: sqlite3_module {virtual table module}
5028 **
5029 ** This structure, sometimes called a a "virtual table module", 
5030 ** defines the implementation of a [virtual tables].  
5031 ** This structure consists mostly of methods for the module.
5032 **
5033 ** ^A virtual table module is created by filling in a persistent
5034 ** instance of this structure and passing a pointer to that instance
5035 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5036 ** ^The registration remains valid until it is replaced by a different
5037 ** module or until the [database connection] closes.  The content
5038 ** of this structure must not change while it is registered with
5039 ** any database connection.
5040 */
5041 struct sqlite3_module {
5042   int iVersion;
5043   int (*xCreate)(sqlite3*, void *pAux,
5044                int argc, const char *const*argv,
5045                sqlite3_vtab **ppVTab, char**);
5046   int (*xConnect)(sqlite3*, void *pAux,
5047                int argc, const char *const*argv,
5048                sqlite3_vtab **ppVTab, char**);
5049   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5050   int (*xDisconnect)(sqlite3_vtab *pVTab);
5051   int (*xDestroy)(sqlite3_vtab *pVTab);
5052   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5053   int (*xClose)(sqlite3_vtab_cursor*);
5054   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5055                 int argc, sqlite3_value **argv);
5056   int (*xNext)(sqlite3_vtab_cursor*);
5057   int (*xEof)(sqlite3_vtab_cursor*);
5058   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5059   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5060   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5061   int (*xBegin)(sqlite3_vtab *pVTab);
5062   int (*xSync)(sqlite3_vtab *pVTab);
5063   int (*xCommit)(sqlite3_vtab *pVTab);
5064   int (*xRollback)(sqlite3_vtab *pVTab);
5065   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5066                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5067                        void **ppArg);
5068   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5069 };
5070
5071 /*
5072 ** CAPI3REF: Virtual Table Indexing Information
5073 ** KEYWORDS: sqlite3_index_info
5074 **
5075 ** The sqlite3_index_info structure and its substructures is used as part
5076 ** of the [virtual table] interface to
5077 ** pass information into and receive the reply from the [xBestIndex]
5078 ** method of a [virtual table module].  The fields under **Inputs** are the
5079 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5080 ** results into the **Outputs** fields.
5081 **
5082 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5083 **
5084 ** <blockquote>column OP expr</blockquote>
5085 **
5086 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5087 ** stored in aConstraint[].op using one of the
5088 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5089 ** ^(The index of the column is stored in
5090 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5091 ** expr on the right-hand side can be evaluated (and thus the constraint
5092 ** is usable) and false if it cannot.)^
5093 **
5094 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5095 ** and makes other simplifications to the WHERE clause in an attempt to
5096 ** get as many WHERE clause terms into the form shown above as possible.
5097 ** ^The aConstraint[] array only reports WHERE clause terms that are
5098 ** relevant to the particular virtual table being queried.
5099 **
5100 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5101 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5102 **
5103 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5104 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5105 ** the right-hand side of the corresponding aConstraint[] is evaluated
5106 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5107 ** is true, then the constraint is assumed to be fully handled by the
5108 ** virtual table and is not checked again by SQLite.)^
5109 **
5110 ** ^The idxNum and idxPtr values are recorded and passed into the
5111 ** [xFilter] method.
5112 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5113 ** needToFreeIdxPtr is true.
5114 **
5115 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5116 ** the correct order to satisfy the ORDER BY clause so that no separate
5117 ** sorting step is required.
5118 **
5119 ** ^The estimatedCost value is an estimate of the cost of doing the
5120 ** particular lookup.  A full scan of a table with N entries should have
5121 ** a cost of N.  A binary search of a table of N entries should have a
5122 ** cost of approximately log(N).
5123 */
5124 struct sqlite3_index_info {
5125   /* Inputs */
5126   int nConstraint;           /* Number of entries in aConstraint */
5127   struct sqlite3_index_constraint {
5128      int iColumn;              /* Column on left-hand side of constraint */
5129      unsigned char op;         /* Constraint operator */
5130      unsigned char usable;     /* True if this constraint is usable */
5131      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5132   } *aConstraint;            /* Table of WHERE clause constraints */
5133   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5134   struct sqlite3_index_orderby {
5135      int iColumn;              /* Column number */
5136      unsigned char desc;       /* True for DESC.  False for ASC. */
5137   } *aOrderBy;               /* The ORDER BY clause */
5138   /* Outputs */
5139   struct sqlite3_index_constraint_usage {
5140     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5141     unsigned char omit;      /* Do not code a test for this constraint */
5142   } *aConstraintUsage;
5143   int idxNum;                /* Number used to identify the index */
5144   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5145   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5146   int orderByConsumed;       /* True if output is already ordered */
5147   double estimatedCost;      /* Estimated cost of using this index */
5148 };
5149
5150 /*
5151 ** CAPI3REF: Virtual Table Constraint Operator Codes
5152 **
5153 ** These macros defined the allowed values for the
5154 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5155 ** an operator that is part of a constraint term in the wHERE clause of
5156 ** a query that uses a [virtual table].
5157 */
5158 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5159 #define SQLITE_INDEX_CONSTRAINT_GT    4
5160 #define SQLITE_INDEX_CONSTRAINT_LE    8
5161 #define SQLITE_INDEX_CONSTRAINT_LT    16
5162 #define SQLITE_INDEX_CONSTRAINT_GE    32
5163 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5164
5165 /*
5166 ** CAPI3REF: Register A Virtual Table Implementation
5167 **
5168 ** ^These routines are used to register a new [virtual table module] name.
5169 ** ^Module names must be registered before
5170 ** creating a new [virtual table] using the module and before using a
5171 ** preexisting [virtual table] for the module.
5172 **
5173 ** ^The module name is registered on the [database connection] specified
5174 ** by the first parameter.  ^The name of the module is given by the 
5175 ** second parameter.  ^The third parameter is a pointer to
5176 ** the implementation of the [virtual table module].   ^The fourth
5177 ** parameter is an arbitrary client data pointer that is passed through
5178 ** into the [xCreate] and [xConnect] methods of the virtual table module
5179 ** when a new virtual table is be being created or reinitialized.
5180 **
5181 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5182 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5183 ** invoke the destructor function (if it is not NULL) when SQLite
5184 ** no longer needs the pClientData pointer.  ^The destructor will also
5185 ** be invoked if the call to sqlite3_create_module_v2() fails.
5186 ** ^The sqlite3_create_module()
5187 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5188 ** destructor.
5189 */
5190 SQLITE_API int sqlite3_create_module(
5191   sqlite3 *db,               /* SQLite connection to register module with */
5192   const char *zName,         /* Name of the module */
5193   const sqlite3_module *p,   /* Methods for the module */
5194   void *pClientData          /* Client data for xCreate/xConnect */
5195 );
5196 SQLITE_API int sqlite3_create_module_v2(
5197   sqlite3 *db,               /* SQLite connection to register module with */
5198   const char *zName,         /* Name of the module */
5199   const sqlite3_module *p,   /* Methods for the module */
5200   void *pClientData,         /* Client data for xCreate/xConnect */
5201   void(*xDestroy)(void*)     /* Module destructor function */
5202 );
5203
5204 /*
5205 ** CAPI3REF: Virtual Table Instance Object
5206 ** KEYWORDS: sqlite3_vtab
5207 **
5208 ** Every [virtual table module] implementation uses a subclass
5209 ** of this object to describe a particular instance
5210 ** of the [virtual table].  Each subclass will
5211 ** be tailored to the specific needs of the module implementation.
5212 ** The purpose of this superclass is to define certain fields that are
5213 ** common to all module implementations.
5214 **
5215 ** ^Virtual tables methods can set an error message by assigning a
5216 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5217 ** take care that any prior string is freed by a call to [sqlite3_free()]
5218 ** prior to assigning a new string to zErrMsg.  ^After the error message
5219 ** is delivered up to the client application, the string will be automatically
5220 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5221 */
5222 struct sqlite3_vtab {
5223   const sqlite3_module *pModule;  /* The module for this virtual table */
5224   int nRef;                       /* NO LONGER USED */
5225   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5226   /* Virtual table implementations will typically add additional fields */
5227 };
5228
5229 /*
5230 ** CAPI3REF: Virtual Table Cursor Object
5231 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5232 **
5233 ** Every [virtual table module] implementation uses a subclass of the
5234 ** following structure to describe cursors that point into the
5235 ** [virtual table] and are used
5236 ** to loop through the virtual table.  Cursors are created using the
5237 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5238 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5239 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5240 ** of the module.  Each module implementation will define
5241 ** the content of a cursor structure to suit its own needs.
5242 **
5243 ** This superclass exists in order to define fields of the cursor that
5244 ** are common to all implementations.
5245 */
5246 struct sqlite3_vtab_cursor {
5247   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5248   /* Virtual table implementations will typically add additional fields */
5249 };
5250
5251 /*
5252 ** CAPI3REF: Declare The Schema Of A Virtual Table
5253 **
5254 ** ^The [xCreate] and [xConnect] methods of a
5255 ** [virtual table module] call this interface
5256 ** to declare the format (the names and datatypes of the columns) of
5257 ** the virtual tables they implement.
5258 */
5259 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5260
5261 /*
5262 ** CAPI3REF: Overload A Function For A Virtual Table
5263 **
5264 ** ^(Virtual tables can provide alternative implementations of functions
5265 ** using the [xFindFunction] method of the [virtual table module].  
5266 ** But global versions of those functions
5267 ** must exist in order to be overloaded.)^
5268 **
5269 ** ^(This API makes sure a global version of a function with a particular
5270 ** name and number of parameters exists.  If no such function exists
5271 ** before this API is called, a new function is created.)^  ^The implementation
5272 ** of the new function always causes an exception to be thrown.  So
5273 ** the new function is not good for anything by itself.  Its only
5274 ** purpose is to be a placeholder function that can be overloaded
5275 ** by a [virtual table].
5276 */
5277 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5278
5279 /*
5280 ** The interface to the virtual-table mechanism defined above (back up
5281 ** to a comment remarkably similar to this one) is currently considered
5282 ** to be experimental.  The interface might change in incompatible ways.
5283 ** If this is a problem for you, do not use the interface at this time.
5284 **
5285 ** When the virtual-table mechanism stabilizes, we will declare the
5286 ** interface fixed, support it indefinitely, and remove this comment.
5287 */
5288
5289 /*
5290 ** CAPI3REF: A Handle To An Open BLOB
5291 ** KEYWORDS: {BLOB handle} {BLOB handles}
5292 **
5293 ** An instance of this object represents an open BLOB on which
5294 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5295 ** ^Objects of this type are created by [sqlite3_blob_open()]
5296 ** and destroyed by [sqlite3_blob_close()].
5297 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5298 ** can be used to read or write small subsections of the BLOB.
5299 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5300 */
5301 typedef struct sqlite3_blob sqlite3_blob;
5302
5303 /*
5304 ** CAPI3REF: Open A BLOB For Incremental I/O
5305 **
5306 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5307 ** in row iRow, column zColumn, table zTable in database zDb;
5308 ** in other words, the same BLOB that would be selected by:
5309 **
5310 ** <pre>
5311 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5312 ** </pre>)^
5313 **
5314 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5315 ** and write access. ^If it is zero, the BLOB is opened for read access.
5316 ** ^It is not possible to open a column that is part of an index or primary 
5317 ** key for writing. ^If [foreign key constraints] are enabled, it is 
5318 ** not possible to open a column that is part of a [child key] for writing.
5319 **
5320 ** ^Note that the database name is not the filename that contains
5321 ** the database but rather the symbolic name of the database that
5322 ** appears after the AS keyword when the database is connected using [ATTACH].
5323 ** ^For the main database file, the database name is "main".
5324 ** ^For TEMP tables, the database name is "temp".
5325 **
5326 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5327 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5328 ** to be a null pointer.)^
5329 ** ^This function sets the [database connection] error code and message
5330 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5331 ** functions. ^Note that the *ppBlob variable is always initialized in a
5332 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5333 ** regardless of the success or failure of this routine.
5334 **
5335 ** ^(If the row that a BLOB handle points to is modified by an
5336 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5337 ** then the BLOB handle is marked as "expired".
5338 ** This is true if any column of the row is changed, even a column
5339 ** other than the one the BLOB handle is open on.)^
5340 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5341 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
5342 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5343 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5344 ** commit if the transaction continues to completion.)^
5345 **
5346 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5347 ** the opened blob.  ^The size of a blob may not be changed by this
5348 ** interface.  Use the [UPDATE] SQL command to change the size of a
5349 ** blob.
5350 **
5351 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5352 ** and the built-in [zeroblob] SQL function can be used, if desired,
5353 ** to create an empty, zero-filled blob in which to read or write using
5354 ** this interface.
5355 **
5356 ** To avoid a resource leak, every open [BLOB handle] should eventually
5357 ** be released by a call to [sqlite3_blob_close()].
5358 */
5359 SQLITE_API int sqlite3_blob_open(
5360   sqlite3*,
5361   const char *zDb,
5362   const char *zTable,
5363   const char *zColumn,
5364   sqlite3_int64 iRow,
5365   int flags,
5366   sqlite3_blob **ppBlob
5367 );
5368
5369 /*
5370 ** CAPI3REF: Move a BLOB Handle to a New Row
5371 **
5372 ** ^This function is used to move an existing blob handle so that it points
5373 ** to a different row of the same database table. ^The new row is identified
5374 ** by the rowid value passed as the second argument. Only the row can be
5375 ** changed. ^The database, table and column on which the blob handle is open
5376 ** remain the same. Moving an existing blob handle to a new row can be
5377 ** faster than closing the existing handle and opening a new one.
5378 **
5379 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5380 ** it must exist and there must be either a blob or text value stored in
5381 ** the nominated column.)^ ^If the new row is not present in the table, or if
5382 ** it does not contain a blob or text value, or if another error occurs, an
5383 ** SQLite error code is returned and the blob handle is considered aborted.
5384 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5385 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5386 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5387 ** always returns zero.
5388 **
5389 ** ^This function sets the database handle error code and message.
5390 */
5391 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5392
5393 /*
5394 ** CAPI3REF: Close A BLOB Handle
5395 **
5396 ** ^Closes an open [BLOB handle].
5397 **
5398 ** ^Closing a BLOB shall cause the current transaction to commit
5399 ** if there are no other BLOBs, no pending prepared statements, and the
5400 ** database connection is in [autocommit mode].
5401 ** ^If any writes were made to the BLOB, they might be held in cache
5402 ** until the close operation if they will fit.
5403 **
5404 ** ^(Closing the BLOB often forces the changes
5405 ** out to disk and so if any I/O errors occur, they will likely occur
5406 ** at the time when the BLOB is closed.  Any errors that occur during
5407 ** closing are reported as a non-zero return value.)^
5408 **
5409 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5410 ** an error code, the BLOB is still closed.)^
5411 **
5412 ** ^Calling this routine with a null pointer (such as would be returned
5413 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5414 */
5415 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5416
5417 /*
5418 ** CAPI3REF: Return The Size Of An Open BLOB
5419 **
5420 ** ^Returns the size in bytes of the BLOB accessible via the 
5421 ** successfully opened [BLOB handle] in its only argument.  ^The
5422 ** incremental blob I/O routines can only read or overwriting existing
5423 ** blob content; they cannot change the size of a blob.
5424 **
5425 ** This routine only works on a [BLOB handle] which has been created
5426 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5427 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5428 ** to this routine results in undefined and probably undesirable behavior.
5429 */
5430 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5431
5432 /*
5433 ** CAPI3REF: Read Data From A BLOB Incrementally
5434 **
5435 ** ^(This function is used to read data from an open [BLOB handle] into a
5436 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5437 ** from the open BLOB, starting at offset iOffset.)^
5438 **
5439 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5440 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5441 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5442 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5443 ** can be determined using the [sqlite3_blob_bytes()] interface.
5444 **
5445 ** ^An attempt to read from an expired [BLOB handle] fails with an
5446 ** error code of [SQLITE_ABORT].
5447 **
5448 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5449 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5450 **
5451 ** This routine only works on a [BLOB handle] which has been created
5452 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5453 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5454 ** to this routine results in undefined and probably undesirable behavior.
5455 **
5456 ** See also: [sqlite3_blob_write()].
5457 */
5458 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5459
5460 /*
5461 ** CAPI3REF: Write Data Into A BLOB Incrementally
5462 **
5463 ** ^This function is used to write data into an open [BLOB handle] from a
5464 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5465 ** into the open BLOB, starting at offset iOffset.
5466 **
5467 ** ^If the [BLOB handle] passed as the first argument was not opened for
5468 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5469 ** this function returns [SQLITE_READONLY].
5470 **
5471 ** ^This function may only modify the contents of the BLOB; it is
5472 ** not possible to increase the size of a BLOB using this API.
5473 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5474 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5475 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5476 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5477 ** can be determined using the [sqlite3_blob_bytes()] interface.
5478 **
5479 ** ^An attempt to write to an expired [BLOB handle] fails with an
5480 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5481 ** before the [BLOB handle] expired are not rolled back by the
5482 ** expiration of the handle, though of course those changes might
5483 ** have been overwritten by the statement that expired the BLOB handle
5484 ** or by other independent statements.
5485 **
5486 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5487 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5488 **
5489 ** This routine only works on a [BLOB handle] which has been created
5490 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5491 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5492 ** to this routine results in undefined and probably undesirable behavior.
5493 **
5494 ** See also: [sqlite3_blob_read()].
5495 */
5496 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5497
5498 /*
5499 ** CAPI3REF: Virtual File System Objects
5500 **
5501 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5502 ** that SQLite uses to interact
5503 ** with the underlying operating system.  Most SQLite builds come with a
5504 ** single default VFS that is appropriate for the host computer.
5505 ** New VFSes can be registered and existing VFSes can be unregistered.
5506 ** The following interfaces are provided.
5507 **
5508 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5509 ** ^Names are case sensitive.
5510 ** ^Names are zero-terminated UTF-8 strings.
5511 ** ^If there is no match, a NULL pointer is returned.
5512 ** ^If zVfsName is NULL then the default VFS is returned.
5513 **
5514 ** ^New VFSes are registered with sqlite3_vfs_register().
5515 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5516 ** ^The same VFS can be registered multiple times without injury.
5517 ** ^To make an existing VFS into the default VFS, register it again
5518 ** with the makeDflt flag set.  If two different VFSes with the
5519 ** same name are registered, the behavior is undefined.  If a
5520 ** VFS is registered with a name that is NULL or an empty string,
5521 ** then the behavior is undefined.
5522 **
5523 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5524 ** ^(If the default VFS is unregistered, another VFS is chosen as
5525 ** the default.  The choice for the new VFS is arbitrary.)^
5526 */
5527 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5528 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5529 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5530
5531 /*
5532 ** CAPI3REF: Mutexes
5533 **
5534 ** The SQLite core uses these routines for thread
5535 ** synchronization. Though they are intended for internal
5536 ** use by SQLite, code that links against SQLite is
5537 ** permitted to use any of these routines.
5538 **
5539 ** The SQLite source code contains multiple implementations
5540 ** of these mutex routines.  An appropriate implementation
5541 ** is selected automatically at compile-time.  ^(The following
5542 ** implementations are available in the SQLite core:
5543 **
5544 ** <ul>
5545 ** <li>   SQLITE_MUTEX_OS2
5546 ** <li>   SQLITE_MUTEX_PTHREAD
5547 ** <li>   SQLITE_MUTEX_W32
5548 ** <li>   SQLITE_MUTEX_NOOP
5549 ** </ul>)^
5550 **
5551 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5552 ** that does no real locking and is appropriate for use in
5553 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5554 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5555 ** are appropriate for use on OS/2, Unix, and Windows.
5556 **
5557 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5558 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5559 ** implementation is included with the library. In this case the
5560 ** application must supply a custom mutex implementation using the
5561 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5562 ** before calling sqlite3_initialize() or any other public sqlite3_
5563 ** function that calls sqlite3_initialize().)^
5564 **
5565 ** ^The sqlite3_mutex_alloc() routine allocates a new
5566 ** mutex and returns a pointer to it. ^If it returns NULL
5567 ** that means that a mutex could not be allocated.  ^SQLite
5568 ** will unwind its stack and return an error.  ^(The argument
5569 ** to sqlite3_mutex_alloc() is one of these integer constants:
5570 **
5571 ** <ul>
5572 ** <li>  SQLITE_MUTEX_FAST
5573 ** <li>  SQLITE_MUTEX_RECURSIVE
5574 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5575 ** <li>  SQLITE_MUTEX_STATIC_MEM
5576 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5577 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5578 ** <li>  SQLITE_MUTEX_STATIC_LRU
5579 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5580 ** </ul>)^
5581 **
5582 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5583 ** cause sqlite3_mutex_alloc() to create
5584 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5585 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5586 ** The mutex implementation does not need to make a distinction
5587 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5588 ** not want to.  ^SQLite will only request a recursive mutex in
5589 ** cases where it really needs one.  ^If a faster non-recursive mutex
5590 ** implementation is available on the host platform, the mutex subsystem
5591 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5592 **
5593 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5594 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5595 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5596 ** used by the current version of SQLite.  Future versions of SQLite
5597 ** may add additional static mutexes.  Static mutexes are for internal
5598 ** use by SQLite only.  Applications that use SQLite mutexes should
5599 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5600 ** SQLITE_MUTEX_RECURSIVE.
5601 **
5602 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5603 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5604 ** returns a different mutex on every call.  ^But for the static
5605 ** mutex types, the same mutex is returned on every call that has
5606 ** the same type number.
5607 **
5608 ** ^The sqlite3_mutex_free() routine deallocates a previously
5609 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5610 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5611 ** use when they are deallocated.  Attempting to deallocate a static
5612 ** mutex results in undefined behavior.  ^SQLite never deallocates
5613 ** a static mutex.
5614 **
5615 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5616 ** to enter a mutex.  ^If another thread is already within the mutex,
5617 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5618 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5619 ** upon successful entry.  ^(Mutexes created using
5620 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5621 ** In such cases the,
5622 ** mutex must be exited an equal number of times before another thread
5623 ** can enter.)^  ^(If the same thread tries to enter any other
5624 ** kind of mutex more than once, the behavior is undefined.
5625 ** SQLite will never exhibit
5626 ** such behavior in its own use of mutexes.)^
5627 **
5628 ** ^(Some systems (for example, Windows 95) do not support the operation
5629 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5630 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5631 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5632 **
5633 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5634 ** previously entered by the same thread.   ^(The behavior
5635 ** is undefined if the mutex is not currently entered by the
5636 ** calling thread or is not currently allocated.  SQLite will
5637 ** never do either.)^
5638 **
5639 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5640 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5641 ** behave as no-ops.
5642 **
5643 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5644 */
5645 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5646 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5647 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5648 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5649 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5650
5651 /*
5652 ** CAPI3REF: Mutex Methods Object
5653 **
5654 ** An instance of this structure defines the low-level routines
5655 ** used to allocate and use mutexes.
5656 **
5657 ** Usually, the default mutex implementations provided by SQLite are
5658 ** sufficient, however the user has the option of substituting a custom
5659 ** implementation for specialized deployments or systems for which SQLite
5660 ** does not provide a suitable implementation. In this case, the user
5661 ** creates and populates an instance of this structure to pass
5662 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5663 ** Additionally, an instance of this structure can be used as an
5664 ** output variable when querying the system for the current mutex
5665 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5666 **
5667 ** ^The xMutexInit method defined by this structure is invoked as
5668 ** part of system initialization by the sqlite3_initialize() function.
5669 ** ^The xMutexInit routine is called by SQLite exactly once for each
5670 ** effective call to [sqlite3_initialize()].
5671 **
5672 ** ^The xMutexEnd method defined by this structure is invoked as
5673 ** part of system shutdown by the sqlite3_shutdown() function. The
5674 ** implementation of this method is expected to release all outstanding
5675 ** resources obtained by the mutex methods implementation, especially
5676 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5677 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5678 **
5679 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5680 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5681 ** xMutexNotheld) implement the following interfaces (respectively):
5682 **
5683 ** <ul>
5684 **   <li>  [sqlite3_mutex_alloc()] </li>
5685 **   <li>  [sqlite3_mutex_free()] </li>
5686 **   <li>  [sqlite3_mutex_enter()] </li>
5687 **   <li>  [sqlite3_mutex_try()] </li>
5688 **   <li>  [sqlite3_mutex_leave()] </li>
5689 **   <li>  [sqlite3_mutex_held()] </li>
5690 **   <li>  [sqlite3_mutex_notheld()] </li>
5691 ** </ul>)^
5692 **
5693 ** The only difference is that the public sqlite3_XXX functions enumerated
5694 ** above silently ignore any invocations that pass a NULL pointer instead
5695 ** of a valid mutex handle. The implementations of the methods defined
5696 ** by this structure are not required to handle this case, the results
5697 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5698 ** (i.e. it is acceptable to provide an implementation that segfaults if
5699 ** it is passed a NULL pointer).
5700 **
5701 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5702 ** invoke xMutexInit() multiple times within the same process and without
5703 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5704 ** xMutexInit() must be no-ops.
5705 **
5706 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5707 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5708 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5709 ** memory allocation for a fast or recursive mutex.
5710 **
5711 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5712 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5713 ** If xMutexInit fails in any way, it is expected to clean up after itself
5714 ** prior to returning.
5715 */
5716 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5717 struct sqlite3_mutex_methods {
5718   int (*xMutexInit)(void);
5719   int (*xMutexEnd)(void);
5720   sqlite3_mutex *(*xMutexAlloc)(int);
5721   void (*xMutexFree)(sqlite3_mutex *);
5722   void (*xMutexEnter)(sqlite3_mutex *);
5723   int (*xMutexTry)(sqlite3_mutex *);
5724   void (*xMutexLeave)(sqlite3_mutex *);
5725   int (*xMutexHeld)(sqlite3_mutex *);
5726   int (*xMutexNotheld)(sqlite3_mutex *);
5727 };
5728
5729 /*
5730 ** CAPI3REF: Mutex Verification Routines
5731 **
5732 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5733 ** are intended for use inside assert() statements.  ^The SQLite core
5734 ** never uses these routines except inside an assert() and applications
5735 ** are advised to follow the lead of the core.  ^The SQLite core only
5736 ** provides implementations for these routines when it is compiled
5737 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
5738 ** are only required to provide these routines if SQLITE_DEBUG is
5739 ** defined and if NDEBUG is not defined.
5740 **
5741 ** ^These routines should return true if the mutex in their argument
5742 ** is held or not held, respectively, by the calling thread.
5743 **
5744 ** ^The implementation is not required to provided versions of these
5745 ** routines that actually work. If the implementation does not provide working
5746 ** versions of these routines, it should at least provide stubs that always
5747 ** return true so that one does not get spurious assertion failures.
5748 **
5749 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5750 ** the routine should return 1.   This seems counter-intuitive since
5751 ** clearly the mutex cannot be held if it does not exist.  But the
5752 ** the reason the mutex does not exist is because the build is not
5753 ** using mutexes.  And we do not want the assert() containing the
5754 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5755 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5756 ** interface should also return 1 when given a NULL pointer.
5757 */
5758 #ifndef NDEBUG
5759 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5760 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5761 #endif
5762
5763 /*
5764 ** CAPI3REF: Mutex Types
5765 **
5766 ** The [sqlite3_mutex_alloc()] interface takes a single argument
5767 ** which is one of these integer constants.
5768 **
5769 ** The set of static mutexes may change from one SQLite release to the
5770 ** next.  Applications that override the built-in mutex logic must be
5771 ** prepared to accommodate additional static mutexes.
5772 */
5773 #define SQLITE_MUTEX_FAST             0
5774 #define SQLITE_MUTEX_RECURSIVE        1
5775 #define SQLITE_MUTEX_STATIC_MASTER    2
5776 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5777 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5778 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5779 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5780 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5781 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5782
5783 /*
5784 ** CAPI3REF: Retrieve the mutex for a database connection
5785 **
5786 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
5787 ** serializes access to the [database connection] given in the argument
5788 ** when the [threading mode] is Serialized.
5789 ** ^If the [threading mode] is Single-thread or Multi-thread then this
5790 ** routine returns a NULL pointer.
5791 */
5792 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5793
5794 /*
5795 ** CAPI3REF: Low-Level Control Of Database Files
5796 **
5797 ** ^The [sqlite3_file_control()] interface makes a direct call to the
5798 ** xFileControl method for the [sqlite3_io_methods] object associated
5799 ** with a particular database identified by the second argument. ^The
5800 ** name of the database is "main" for the main database or "temp" for the
5801 ** TEMP database, or the name that appears after the AS keyword for
5802 ** databases that are added using the [ATTACH] SQL command.
5803 ** ^A NULL pointer can be used in place of "main" to refer to the
5804 ** main database file.
5805 ** ^The third and fourth parameters to this routine
5806 ** are passed directly through to the second and third parameters of
5807 ** the xFileControl method.  ^The return value of the xFileControl
5808 ** method becomes the return value of this routine.
5809 **
5810 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
5811 ** a pointer to the underlying [sqlite3_file] object to be written into
5812 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
5813 ** case is a short-circuit path which does not actually invoke the
5814 ** underlying sqlite3_io_methods.xFileControl method.
5815 **
5816 ** ^If the second parameter (zDbName) does not match the name of any
5817 ** open database file, then SQLITE_ERROR is returned.  ^This error
5818 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5819 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
5820 ** also return SQLITE_ERROR.  There is no way to distinguish between
5821 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5822 ** xFileControl method.
5823 **
5824 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5825 */
5826 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5827
5828 /*
5829 ** CAPI3REF: Testing Interface
5830 **
5831 ** ^The sqlite3_test_control() interface is used to read out internal
5832 ** state of SQLite and to inject faults into SQLite for testing
5833 ** purposes.  ^The first parameter is an operation code that determines
5834 ** the number, meaning, and operation of all subsequent parameters.
5835 **
5836 ** This interface is not for use by applications.  It exists solely
5837 ** for verifying the correct operation of the SQLite library.  Depending
5838 ** on how the SQLite library is compiled, this interface might not exist.
5839 **
5840 ** The details of the operation codes, their meanings, the parameters
5841 ** they take, and what they do are all subject to change without notice.
5842 ** Unlike most of the SQLite API, this function is not guaranteed to
5843 ** operate consistently from one release to the next.
5844 */
5845 SQLITE_API int sqlite3_test_control(int op, ...);
5846
5847 /*
5848 ** CAPI3REF: Testing Interface Operation Codes
5849 **
5850 ** These constants are the valid operation code parameters used
5851 ** as the first argument to [sqlite3_test_control()].
5852 **
5853 ** These parameters and their meanings are subject to change
5854 ** without notice.  These values are for testing purposes only.
5855 ** Applications should not use any of these parameters or the
5856 ** [sqlite3_test_control()] interface.
5857 */
5858 #define SQLITE_TESTCTRL_FIRST                    5
5859 #define SQLITE_TESTCTRL_PRNG_SAVE                5
5860 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
5861 #define SQLITE_TESTCTRL_PRNG_RESET               7
5862 #define SQLITE_TESTCTRL_BITVEC_TEST              8
5863 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
5864 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5865 #define SQLITE_TESTCTRL_PENDING_BYTE            11
5866 #define SQLITE_TESTCTRL_ASSERT                  12
5867 #define SQLITE_TESTCTRL_ALWAYS                  13
5868 #define SQLITE_TESTCTRL_RESERVE                 14
5869 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5870 #define SQLITE_TESTCTRL_ISKEYWORD               16
5871 #define SQLITE_TESTCTRL_PGHDRSZ                 17
5872 #define SQLITE_TESTCTRL_SCRATCHMALLOC           18
5873 #define SQLITE_TESTCTRL_LAST                    18
5874
5875 /*
5876 ** CAPI3REF: SQLite Runtime Status
5877 **
5878 ** ^This interface is used to retrieve runtime status information
5879 ** about the performance of SQLite, and optionally to reset various
5880 ** highwater marks.  ^The first argument is an integer code for
5881 ** the specific parameter to measure.  ^(Recognized integer codes
5882 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5883 ** ^The current value of the parameter is returned into *pCurrent.
5884 ** ^The highest recorded value is returned in *pHighwater.  ^If the
5885 ** resetFlag is true, then the highest record value is reset after
5886 ** *pHighwater is written.  ^(Some parameters do not record the highest
5887 ** value.  For those parameters
5888 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5889 ** ^(Other parameters record only the highwater mark and not the current
5890 ** value.  For these latter parameters nothing is written into *pCurrent.)^
5891 **
5892 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
5893 ** non-zero [error code] on failure.
5894 **
5895 ** This routine is threadsafe but is not atomic.  This routine can be
5896 ** called while other threads are running the same or different SQLite
5897 ** interfaces.  However the values returned in *pCurrent and
5898 ** *pHighwater reflect the status of SQLite at different points in time
5899 ** and it is possible that another thread might change the parameter
5900 ** in between the times when *pCurrent and *pHighwater are written.
5901 **
5902 ** See also: [sqlite3_db_status()]
5903 */
5904 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5905
5906
5907 /*
5908 ** CAPI3REF: Status Parameters
5909 **
5910 ** These integer constants designate various run-time status parameters
5911 ** that can be returned by [sqlite3_status()].
5912 **
5913 ** <dl>
5914 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5915 ** <dd>This parameter is the current amount of memory checked out
5916 ** using [sqlite3_malloc()], either directly or indirectly.  The
5917 ** figure includes calls made to [sqlite3_malloc()] by the application
5918 ** and internal memory usage by the SQLite library.  Scratch memory
5919 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5920 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5921 ** this parameter.  The amount returned is the sum of the allocation
5922 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5923 **
5924 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5925 ** <dd>This parameter records the largest memory allocation request
5926 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5927 ** internal equivalents).  Only the value returned in the
5928 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5929 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5930 **
5931 ** ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
5932 ** <dd>This parameter records the number of separate memory allocations.</dd>)^
5933 **
5934 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5935 ** <dd>This parameter returns the number of pages used out of the
5936 ** [pagecache memory allocator] that was configured using 
5937 ** [SQLITE_CONFIG_PAGECACHE].  The
5938 ** value returned is in pages, not in bytes.</dd>)^
5939 **
5940 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5941 ** <dd>This parameter returns the number of bytes of page cache
5942 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
5943 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
5944 ** returned value includes allocations that overflowed because they
5945 ** where too large (they were larger than the "sz" parameter to
5946 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5947 ** no space was left in the page cache.</dd>)^
5948 **
5949 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5950 ** <dd>This parameter records the largest memory allocation request
5951 ** handed to [pagecache memory allocator].  Only the value returned in the
5952 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5953 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5954 **
5955 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5956 ** <dd>This parameter returns the number of allocations used out of the
5957 ** [scratch memory allocator] configured using
5958 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5959 ** in bytes.  Since a single thread may only have one scratch allocation
5960 ** outstanding at time, this parameter also reports the number of threads
5961 ** using scratch memory at the same time.</dd>)^
5962 **
5963 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5964 ** <dd>This parameter returns the number of bytes of scratch memory
5965 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
5966 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5967 ** returned include overflows because the requested allocation was too
5968 ** larger (that is, because the requested allocation was larger than the
5969 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5970 ** slots were available.
5971 ** </dd>)^
5972 **
5973 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5974 ** <dd>This parameter records the largest memory allocation request
5975 ** handed to [scratch memory allocator].  Only the value returned in the
5976 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5977 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5978 **
5979 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5980 ** <dd>This parameter records the deepest parser stack.  It is only
5981 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5982 ** </dl>
5983 **
5984 ** New status parameters may be added from time to time.
5985 */
5986 #define SQLITE_STATUS_MEMORY_USED          0
5987 #define SQLITE_STATUS_PAGECACHE_USED       1
5988 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5989 #define SQLITE_STATUS_SCRATCH_USED         3
5990 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5991 #define SQLITE_STATUS_MALLOC_SIZE          5
5992 #define SQLITE_STATUS_PARSER_STACK         6
5993 #define SQLITE_STATUS_PAGECACHE_SIZE       7
5994 #define SQLITE_STATUS_SCRATCH_SIZE         8
5995 #define SQLITE_STATUS_MALLOC_COUNT         9
5996
5997 /*
5998 ** CAPI3REF: Database Connection Status
5999 **
6000 ** ^This interface is used to retrieve runtime status information 
6001 ** about a single [database connection].  ^The first argument is the
6002 ** database connection object to be interrogated.  ^The second argument
6003 ** is an integer constant, taken from the set of
6004 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros, that
6005 ** determines the parameter to interrogate.  The set of 
6006 ** [SQLITE_DBSTATUS_LOOKASIDE_USED | SQLITE_DBSTATUS_*] macros is likely
6007 ** to grow in future releases of SQLite.
6008 **
6009 ** ^The current value of the requested parameter is written into *pCur
6010 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6011 ** the resetFlg is true, then the highest instantaneous value is
6012 ** reset back down to the current value.
6013 **
6014 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6015 ** non-zero [error code] on failure.
6016 **
6017 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6018 */
6019 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6020
6021 /*
6022 ** CAPI3REF: Status Parameters for database connections
6023 **
6024 ** These constants are the available integer "verbs" that can be passed as
6025 ** the second argument to the [sqlite3_db_status()] interface.
6026 **
6027 ** New verbs may be added in future releases of SQLite. Existing verbs
6028 ** might be discontinued. Applications should check the return code from
6029 ** [sqlite3_db_status()] to make sure that the call worked.
6030 ** The [sqlite3_db_status()] interface will return a non-zero error code
6031 ** if a discontinued or unsupported verb is invoked.
6032 **
6033 ** <dl>
6034 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6035 ** <dd>This parameter returns the number of lookaside memory slots currently
6036 ** checked out.</dd>)^
6037 **
6038 ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6039 ** <dd>This parameter returns the approximate number of of bytes of heap
6040 ** memory used by all pager caches associated with the database connection.)^
6041 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6042 **
6043 ** ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6044 ** <dd>This parameter returns the approximate number of of bytes of heap
6045 ** memory used to store the schema for all databases associated
6046 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6047 ** ^The full amount of memory used by the schemas is reported, even if the
6048 ** schema memory is shared with other database connections due to
6049 ** [shared cache mode] being enabled.
6050 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6051 **
6052 ** ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6053 ** <dd>This parameter returns the approximate number of of bytes of heap
6054 ** and lookaside memory used by all prepared statements associated with
6055 ** the database connection.)^
6056 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6057 ** </dd>
6058 ** </dl>
6059 */
6060 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
6061 #define SQLITE_DBSTATUS_CACHE_USED         1
6062 #define SQLITE_DBSTATUS_SCHEMA_USED        2
6063 #define SQLITE_DBSTATUS_STMT_USED          3
6064 #define SQLITE_DBSTATUS_MAX                3   /* Largest defined DBSTATUS */
6065
6066
6067 /*
6068 ** CAPI3REF: Prepared Statement Status
6069 **
6070 ** ^(Each prepared statement maintains various
6071 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
6072 ** of times it has performed specific operations.)^  These counters can
6073 ** be used to monitor the performance characteristics of the prepared
6074 ** statements.  For example, if the number of table steps greatly exceeds
6075 ** the number of table searches or result rows, that would tend to indicate
6076 ** that the prepared statement is using a full table scan rather than
6077 ** an index.  
6078 **
6079 ** ^(This interface is used to retrieve and reset counter values from
6080 ** a [prepared statement].  The first argument is the prepared statement
6081 ** object to be interrogated.  The second argument
6082 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
6083 ** to be interrogated.)^
6084 ** ^The current value of the requested counter is returned.
6085 ** ^If the resetFlg is true, then the counter is reset to zero after this
6086 ** interface call returns.
6087 **
6088 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6089 */
6090 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6091
6092 /*
6093 ** CAPI3REF: Status Parameters for prepared statements
6094 **
6095 ** These preprocessor macros define integer codes that name counter
6096 ** values associated with the [sqlite3_stmt_status()] interface.
6097 ** The meanings of the various counters are as follows:
6098 **
6099 ** <dl>
6100 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6101 ** <dd>^This is the number of times that SQLite has stepped forward in
6102 ** a table as part of a full table scan.  Large numbers for this counter
6103 ** may indicate opportunities for performance improvement through 
6104 ** careful use of indices.</dd>
6105 **
6106 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
6107 ** <dd>^This is the number of sort operations that have occurred.
6108 ** A non-zero value in this counter may indicate an opportunity to
6109 ** improvement performance through careful use of indices.</dd>
6110 **
6111 ** <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6112 ** <dd>^This is the number of rows inserted into transient indices that
6113 ** were created automatically in order to help joins run faster.
6114 ** A non-zero value in this counter may indicate an opportunity to
6115 ** improvement performance by adding permanent indices that do not
6116 ** need to be reinitialized each time the statement is run.</dd>
6117 **
6118 ** </dl>
6119 */
6120 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6121 #define SQLITE_STMTSTATUS_SORT              2
6122 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6123
6124 /*
6125 ** CAPI3REF: Custom Page Cache Object
6126 **
6127 ** The sqlite3_pcache type is opaque.  It is implemented by
6128 ** the pluggable module.  The SQLite core has no knowledge of
6129 ** its size or internal structure and never deals with the
6130 ** sqlite3_pcache object except by holding and passing pointers
6131 ** to the object.
6132 **
6133 ** See [sqlite3_pcache_methods] for additional information.
6134 */
6135 typedef struct sqlite3_pcache sqlite3_pcache;
6136
6137 /*
6138 ** CAPI3REF: Application Defined Page Cache.
6139 ** KEYWORDS: {page cache}
6140 **
6141 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6142 ** register an alternative page cache implementation by passing in an 
6143 ** instance of the sqlite3_pcache_methods structure.)^
6144 ** In many applications, most of the heap memory allocated by 
6145 ** SQLite is used for the page cache.
6146 ** By implementing a 
6147 ** custom page cache using this API, an application can better control
6148 ** the amount of memory consumed by SQLite, the way in which 
6149 ** that memory is allocated and released, and the policies used to 
6150 ** determine exactly which parts of a database file are cached and for 
6151 ** how long.
6152 **
6153 ** The alternative page cache mechanism is an
6154 ** extreme measure that is only needed by the most demanding applications.
6155 ** The built-in page cache is recommended for most uses.
6156 **
6157 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6158 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6159 ** the application may discard the parameter after the call to
6160 ** [sqlite3_config()] returns.)^
6161 **
6162 ** ^(The xInit() method is called once for each effective 
6163 ** call to [sqlite3_initialize()])^
6164 ** (usually only once during the lifetime of the process). ^(The xInit()
6165 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6166 ** The intent of the xInit() method is to set up global data structures 
6167 ** required by the custom page cache implementation. 
6168 ** ^(If the xInit() method is NULL, then the 
6169 ** built-in default page cache is used instead of the application defined
6170 ** page cache.)^
6171 **
6172 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6173 ** It can be used to clean up 
6174 ** any outstanding resources before process shutdown, if required.
6175 ** ^The xShutdown() method may be NULL.
6176 **
6177 ** ^SQLite automatically serializes calls to the xInit method,
6178 ** so the xInit method need not be threadsafe.  ^The
6179 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6180 ** not need to be threadsafe either.  All other methods must be threadsafe
6181 ** in multithreaded applications.
6182 **
6183 ** ^SQLite will never invoke xInit() more than once without an intervening
6184 ** call to xShutdown().
6185 **
6186 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6187 ** SQLite will typically create one cache instance for each open database file,
6188 ** though this is not guaranteed. ^The
6189 ** first parameter, szPage, is the size in bytes of the pages that must
6190 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
6191 ** will the page size of the database file that is to be cached plus an
6192 ** increment (here called "R") of about 100 or 200.  SQLite will use the
6193 ** extra R bytes on each page to store metadata about the underlying
6194 ** database page on disk.  The value of R depends
6195 ** on the SQLite version, the target platform, and how SQLite was compiled.
6196 ** ^R is constant for a particular build of SQLite.  ^The second argument to
6197 ** xCreate(), bPurgeable, is true if the cache being created will
6198 ** be used to cache database pages of a file stored on disk, or
6199 ** false if it is used for an in-memory database. The cache implementation
6200 ** does not have to do anything special based with the value of bPurgeable;
6201 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6202 ** never invoke xUnpin() except to deliberately delete a page.
6203 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6204 ** false will always have the "discard" flag set to true.  
6205 ** ^Hence, a cache created with bPurgeable false will
6206 ** never contain any unpinned pages.
6207 **
6208 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6209 ** suggested maximum cache-size (number of pages stored by) the cache
6210 ** instance passed as the first argument. This is the value configured using
6211 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6212 ** parameter, the implementation is not required to do anything with this
6213 ** value; it is advisory only.
6214 **
6215 ** The xPagecount() method must return the number of pages currently
6216 ** stored in the cache, both pinned and unpinned.
6217 ** 
6218 ** The xFetch() method locates a page in the cache and returns a pointer to 
6219 ** the page, or a NULL pointer.
6220 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6221 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6222 ** mimimum key value is 1.  After it has been retrieved using xFetch, the page 
6223 ** is considered to be "pinned".
6224 **
6225 ** If the requested page is already in the page cache, then the page cache
6226 ** implementation must return a pointer to the page buffer with its content
6227 ** intact.  If the requested page is not already in the cache, then the
6228 ** behavior of the cache implementation should use the value of the createFlag
6229 ** parameter to help it determined what action to take:
6230 **
6231 ** <table border=1 width=85% align=center>
6232 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6233 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6234 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6235 **                 Otherwise return NULL.
6236 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6237 **                 NULL if allocating a new page is effectively impossible.
6238 ** </table>
6239 **
6240 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6241 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6242 ** failed.)^  In between the to xFetch() calls, SQLite may
6243 ** attempt to unpin one or more cache pages by spilling the content of
6244 ** pinned pages to disk and synching the operating system disk cache.
6245 **
6246 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6247 ** as its second argument.  If the third parameter, discard, is non-zero,
6248 ** then the page must be evicted from the cache.
6249 ** ^If the discard parameter is
6250 ** zero, then the page may be discarded or retained at the discretion of
6251 ** page cache implementation. ^The page cache implementation
6252 ** may choose to evict unpinned pages at any time.
6253 **
6254 ** The cache must not perform any reference counting. A single 
6255 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6256 ** to xFetch().
6257 **
6258 ** The xRekey() method is used to change the key value associated with the
6259 ** page passed as the second argument. If the cache
6260 ** previously contains an entry associated with newKey, it must be
6261 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6262 ** to be pinned.
6263 **
6264 ** When SQLite calls the xTruncate() method, the cache must discard all
6265 ** existing cache entries with page numbers (keys) greater than or equal
6266 ** to the value of the iLimit parameter passed to xTruncate(). If any
6267 ** of these pages are pinned, they are implicitly unpinned, meaning that
6268 ** they can be safely discarded.
6269 **
6270 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6271 ** All resources associated with the specified cache should be freed. ^After
6272 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6273 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
6274 ** functions.
6275 */
6276 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6277 struct sqlite3_pcache_methods {
6278   void *pArg;
6279   int (*xInit)(void*);
6280   void (*xShutdown)(void*);
6281   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6282   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6283   int (*xPagecount)(sqlite3_pcache*);
6284   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6285   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6286   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6287   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6288   void (*xDestroy)(sqlite3_pcache*);
6289 };
6290
6291 /*
6292 ** CAPI3REF: Online Backup Object
6293 **
6294 ** The sqlite3_backup object records state information about an ongoing
6295 ** online backup operation.  ^The sqlite3_backup object is created by
6296 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6297 ** [sqlite3_backup_finish()].
6298 **
6299 ** See Also: [Using the SQLite Online Backup API]
6300 */
6301 typedef struct sqlite3_backup sqlite3_backup;
6302
6303 /*
6304 ** CAPI3REF: Online Backup API.
6305 **
6306 ** The backup API copies the content of one database into another.
6307 ** It is useful either for creating backups of databases or
6308 ** for copying in-memory databases to or from persistent files. 
6309 **
6310 ** See Also: [Using the SQLite Online Backup API]
6311 **
6312 ** ^Exclusive access is required to the destination database for the 
6313 ** duration of the operation. ^However the source database is only
6314 ** read-locked while it is actually being read; it is not locked
6315 ** continuously for the entire backup operation. ^Thus, the backup may be
6316 ** performed on a live source database without preventing other users from
6317 ** reading or writing to the source database while the backup is underway.
6318 ** 
6319 ** ^(To perform a backup operation: 
6320 **   <ol>
6321 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6322 **         backup, 
6323 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
6324 **         the data between the two databases, and finally
6325 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
6326 **         associated with the backup operation. 
6327 **   </ol>)^
6328 ** There should be exactly one call to sqlite3_backup_finish() for each
6329 ** successful call to sqlite3_backup_init().
6330 **
6331 ** <b>sqlite3_backup_init()</b>
6332 **
6333 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
6334 ** [database connection] associated with the destination database 
6335 ** and the database name, respectively.
6336 ** ^The database name is "main" for the main database, "temp" for the
6337 ** temporary database, or the name specified after the AS keyword in
6338 ** an [ATTACH] statement for an attached database.
6339 ** ^The S and M arguments passed to 
6340 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6341 ** and database name of the source database, respectively.
6342 ** ^The source and destination [database connections] (parameters S and D)
6343 ** must be different or else sqlite3_backup_init(D,N,S,M) will file with
6344 ** an error.
6345 **
6346 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6347 ** returned and an error code and error message are store3d in the
6348 ** destination [database connection] D.
6349 ** ^The error code and message for the failed call to sqlite3_backup_init()
6350 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6351 ** [sqlite3_errmsg16()] functions.
6352 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6353 ** [sqlite3_backup] object.
6354 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6355 ** sqlite3_backup_finish() functions to perform the specified backup 
6356 ** operation.
6357 **
6358 ** <b>sqlite3_backup_step()</b>
6359 **
6360 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
6361 ** the source and destination databases specified by [sqlite3_backup] object B.
6362 ** ^If N is negative, all remaining source pages are copied. 
6363 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6364 ** are still more pages to be copied, then the function resturns [SQLITE_OK].
6365 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6366 ** from source to destination, then it returns [SQLITE_DONE].
6367 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6368 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6369 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6370 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6371 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6372 **
6373 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6374 ** <ol>
6375 ** <li> the destination database was opened read-only, or
6376 ** <li> the destination database is using write-ahead-log journaling
6377 ** and the destination and source page sizes differ, or
6378 ** <li> The destination database is an in-memory database and the
6379 ** destination and source page sizes differ.
6380 ** </ol>)^
6381 **
6382 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6383 ** the [sqlite3_busy_handler | busy-handler function]
6384 ** is invoked (if one is specified). ^If the 
6385 ** busy-handler returns non-zero before the lock is available, then 
6386 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6387 ** sqlite3_backup_step() can be retried later. ^If the source
6388 ** [database connection]
6389 ** is being used to write to the source database when sqlite3_backup_step()
6390 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6391 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6392 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6393 ** [SQLITE_READONLY] is returned, then 
6394 ** there is no point in retrying the call to sqlite3_backup_step(). These 
6395 ** errors are considered fatal.)^  The application must accept 
6396 ** that the backup operation has failed and pass the backup operation handle 
6397 ** to the sqlite3_backup_finish() to release associated resources.
6398 **
6399 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6400 ** on the destination file. ^The exclusive lock is not released until either 
6401 ** sqlite3_backup_finish() is called or the backup operation is complete 
6402 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6403 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6404 ** lasts for the duration of the sqlite3_backup_step() call.
6405 ** ^Because the source database is not locked between calls to
6406 ** sqlite3_backup_step(), the source database may be modified mid-way
6407 ** through the backup process.  ^If the source database is modified by an
6408 ** external process or via a database connection other than the one being
6409 ** used by the backup operation, then the backup will be automatically
6410 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
6411 ** database is modified by the using the same database connection as is used
6412 ** by the backup operation, then the backup database is automatically
6413 ** updated at the same time.
6414 **
6415 ** <b>sqlite3_backup_finish()</b>
6416 **
6417 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
6418 ** application wishes to abandon the backup operation, the application
6419 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6420 ** ^The sqlite3_backup_finish() interfaces releases all
6421 ** resources associated with the [sqlite3_backup] object. 
6422 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6423 ** active write-transaction on the destination database is rolled back.
6424 ** The [sqlite3_backup] object is invalid
6425 ** and may not be used following a call to sqlite3_backup_finish().
6426 **
6427 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6428 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6429 ** sqlite3_backup_step() completed.
6430 ** ^If an out-of-memory condition or IO error occurred during any prior
6431 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6432 ** sqlite3_backup_finish() returns the corresponding [error code].
6433 **
6434 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6435 ** is not a permanent error and does not affect the return value of
6436 ** sqlite3_backup_finish().
6437 **
6438 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6439 **
6440 ** ^Each call to sqlite3_backup_step() sets two values inside
6441 ** the [sqlite3_backup] object: the number of pages still to be backed
6442 ** up and the total number of pages in the source database file.
6443 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6444 ** retrieve these two values, respectively.
6445 **
6446 ** ^The values returned by these functions are only updated by
6447 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6448 ** operation, then the values are not updated to account for any extra
6449 ** pages that need to be updated or the size of the source database file
6450 ** changing.
6451 **
6452 ** <b>Concurrent Usage of Database Handles</b>
6453 **
6454 ** ^The source [database connection] may be used by the application for other
6455 ** purposes while a backup operation is underway or being initialized.
6456 ** ^If SQLite is compiled and configured to support threadsafe database
6457 ** connections, then the source database connection may be used concurrently
6458 ** from within other threads.
6459 **
6460 ** However, the application must guarantee that the destination 
6461 ** [database connection] is not passed to any other API (by any thread) after 
6462 ** sqlite3_backup_init() is called and before the corresponding call to
6463 ** sqlite3_backup_finish().  SQLite does not currently check to see
6464 ** if the application incorrectly accesses the destination [database connection]
6465 ** and so no error code is reported, but the operations may malfunction
6466 ** nevertheless.  Use of the destination database connection while a
6467 ** backup is in progress might also also cause a mutex deadlock.
6468 **
6469 ** If running in [shared cache mode], the application must
6470 ** guarantee that the shared cache used by the destination database
6471 ** is not accessed while the backup is running. In practice this means
6472 ** that the application must guarantee that the disk file being 
6473 ** backed up to is not accessed by any connection within the process,
6474 ** not just the specific connection that was passed to sqlite3_backup_init().
6475 **
6476 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
6477 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6478 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6479 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6480 ** same time as another thread is invoking sqlite3_backup_step() it is
6481 ** possible that they return invalid values.
6482 */
6483 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6484   sqlite3 *pDest,                        /* Destination database handle */
6485   const char *zDestName,                 /* Destination database name */
6486   sqlite3 *pSource,                      /* Source database handle */
6487   const char *zSourceName                /* Source database name */
6488 );
6489 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6490 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6491 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6492 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6493
6494 /*
6495 ** CAPI3REF: Unlock Notification
6496 **
6497 ** ^When running in shared-cache mode, a database operation may fail with
6498 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6499 ** individual tables within the shared-cache cannot be obtained. See
6500 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6501 ** ^This API may be used to register a callback that SQLite will invoke 
6502 ** when the connection currently holding the required lock relinquishes it.
6503 ** ^This API is only available if the library was compiled with the
6504 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6505 **
6506 ** See Also: [Using the SQLite Unlock Notification Feature].
6507 **
6508 ** ^Shared-cache locks are released when a database connection concludes
6509 ** its current transaction, either by committing it or rolling it back. 
6510 **
6511 ** ^When a connection (known as the blocked connection) fails to obtain a
6512 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6513 ** identity of the database connection (the blocking connection) that
6514 ** has locked the required resource is stored internally. ^After an 
6515 ** application receives an SQLITE_LOCKED error, it may call the
6516 ** sqlite3_unlock_notify() method with the blocked connection handle as 
6517 ** the first argument to register for a callback that will be invoked
6518 ** when the blocking connections current transaction is concluded. ^The
6519 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6520 ** call that concludes the blocking connections transaction.
6521 **
6522 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6523 ** there is a chance that the blocking connection will have already
6524 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6525 ** If this happens, then the specified callback is invoked immediately,
6526 ** from within the call to sqlite3_unlock_notify().)^
6527 **
6528 ** ^If the blocked connection is attempting to obtain a write-lock on a
6529 ** shared-cache table, and more than one other connection currently holds
6530 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6531 ** the other connections to use as the blocking connection.
6532 **
6533 ** ^(There may be at most one unlock-notify callback registered by a 
6534 ** blocked connection. If sqlite3_unlock_notify() is called when the
6535 ** blocked connection already has a registered unlock-notify callback,
6536 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6537 ** called with a NULL pointer as its second argument, then any existing
6538 ** unlock-notify callback is canceled. ^The blocked connections 
6539 ** unlock-notify callback may also be canceled by closing the blocked
6540 ** connection using [sqlite3_close()].
6541 **
6542 ** The unlock-notify callback is not reentrant. If an application invokes
6543 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6544 ** crash or deadlock may be the result.
6545 **
6546 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6547 ** returns SQLITE_OK.
6548 **
6549 ** <b>Callback Invocation Details</b>
6550 **
6551 ** When an unlock-notify callback is registered, the application provides a 
6552 ** single void* pointer that is passed to the callback when it is invoked.
6553 ** However, the signature of the callback function allows SQLite to pass
6554 ** it an array of void* context pointers. The first argument passed to
6555 ** an unlock-notify callback is a pointer to an array of void* pointers,
6556 ** and the second is the number of entries in the array.
6557 **
6558 ** When a blocking connections transaction is concluded, there may be
6559 ** more than one blocked connection that has registered for an unlock-notify
6560 ** callback. ^If two or more such blocked connections have specified the
6561 ** same callback function, then instead of invoking the callback function
6562 ** multiple times, it is invoked once with the set of void* context pointers
6563 ** specified by the blocked connections bundled together into an array.
6564 ** This gives the application an opportunity to prioritize any actions 
6565 ** related to the set of unblocked database connections.
6566 **
6567 ** <b>Deadlock Detection</b>
6568 **
6569 ** Assuming that after registering for an unlock-notify callback a 
6570 ** database waits for the callback to be issued before taking any further
6571 ** action (a reasonable assumption), then using this API may cause the
6572 ** application to deadlock. For example, if connection X is waiting for
6573 ** connection Y's transaction to be concluded, and similarly connection
6574 ** Y is waiting on connection X's transaction, then neither connection
6575 ** will proceed and the system may remain deadlocked indefinitely.
6576 **
6577 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6578 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6579 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6580 ** unlock-notify callback is registered. The system is said to be in
6581 ** a deadlocked state if connection A has registered for an unlock-notify
6582 ** callback on the conclusion of connection B's transaction, and connection
6583 ** B has itself registered for an unlock-notify callback when connection
6584 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6585 ** the system is also considered to be deadlocked if connection B has
6586 ** registered for an unlock-notify callback on the conclusion of connection
6587 ** C's transaction, where connection C is waiting on connection A. ^Any
6588 ** number of levels of indirection are allowed.
6589 **
6590 ** <b>The "DROP TABLE" Exception</b>
6591 **
6592 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
6593 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6594 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6595 ** SQLite checks if there are any currently executing SELECT statements
6596 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6597 ** returned. In this case there is no "blocking connection", so invoking
6598 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6599 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6600 ** or "DROP INDEX" query, an infinite loop might be the result.
6601 **
6602 ** One way around this problem is to check the extended error code returned
6603 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6604 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6605 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6606 ** SQLITE_LOCKED.)^
6607 */
6608 SQLITE_API int sqlite3_unlock_notify(
6609   sqlite3 *pBlocked,                          /* Waiting connection */
6610   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6611   void *pNotifyArg                            /* Argument to pass to xNotify */
6612 );
6613
6614
6615 /*
6616 ** CAPI3REF: String Comparison
6617 **
6618 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6619 ** compare the contents of two buffers containing UTF-8 strings in a
6620 ** case-independent fashion, using the same definition of case independence 
6621 ** that SQLite uses internally when comparing identifiers.
6622 */
6623 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6624
6625 /*
6626 ** CAPI3REF: Error Logging Interface
6627 **
6628 ** ^The [sqlite3_log()] interface writes a message into the error log
6629 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6630 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6631 ** used with [sqlite3_snprintf()] to generate the final output string.
6632 **
6633 ** The sqlite3_log() interface is intended for use by extensions such as
6634 ** virtual tables, collating functions, and SQL functions.  While there is
6635 ** nothing to prevent an application from calling sqlite3_log(), doing so
6636 ** is considered bad form.
6637 **
6638 ** The zFormat string must not be NULL.
6639 **
6640 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6641 ** will not use dynamically allocated memory.  The log message is stored in
6642 ** a fixed-length buffer on the stack.  If the log message is longer than
6643 ** a few hundred characters, it will be truncated to the length of the
6644 ** buffer.
6645 */
6646 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6647
6648 /*
6649 ** CAPI3REF: Write-Ahead Log Commit Hook
6650 **
6651 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
6652 ** will be invoked each time a database connection commits data to a
6653 ** [write-ahead log] (i.e. whenever a transaction is committed in
6654 ** [journal_mode | journal_mode=WAL mode]). 
6655 **
6656 ** ^The callback is invoked by SQLite after the commit has taken place and 
6657 ** the associated write-lock on the database released, so the implementation 
6658 ** may read, write or [checkpoint] the database as required.
6659 **
6660 ** ^The first parameter passed to the callback function when it is invoked
6661 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
6662 ** registering the callback. ^The second is a copy of the database handle.
6663 ** ^The third parameter is the name of the database that was written to -
6664 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6665 ** is the number of pages currently in the write-ahead log file,
6666 ** including those that were just committed.
6667 **
6668 ** The callback function should normally return [SQLITE_OK].  ^If an error
6669 ** code is returned, that error will propagate back up through the
6670 ** SQLite code base to cause the statement that provoked the callback
6671 ** to report an error, though the commit will have still occurred. If the
6672 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
6673 ** that does not correspond to any valid SQLite error code, the results
6674 ** are undefined.
6675 **
6676 ** A single database handle may have at most a single write-ahead log callback 
6677 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
6678 ** previously registered write-ahead log callback. ^Note that the
6679 ** [sqlite3_wal_autocheckpoint()] interface and the
6680 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
6681 ** those overwrite any prior [sqlite3_wal_hook()] settings.
6682 */
6683 SQLITE_API void *sqlite3_wal_hook(
6684   sqlite3*, 
6685   int(*)(void *,sqlite3*,const char*,int),
6686   void*
6687 );
6688
6689 /*
6690 ** CAPI3REF: Configure an auto-checkpoint
6691 **
6692 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
6693 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
6694 ** to automatically [checkpoint]
6695 ** after committing a transaction if there are N or
6696 ** more frames in the [write-ahead log] file.  ^Passing zero or 
6697 ** a negative value as the nFrame parameter disables automatic
6698 ** checkpoints entirely.
6699 **
6700 ** ^The callback registered by this function replaces any existing callback
6701 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
6702 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
6703 ** configured by this function.
6704 **
6705 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
6706 ** from SQL.
6707 **
6708 ** ^Every new [database connection] defaults to having the auto-checkpoint
6709 ** enabled with a threshold of 1000 pages.  The use of this interface
6710 ** is only necessary if the default setting is found to be suboptimal
6711 ** for a particular application.
6712 */
6713 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
6714
6715 /*
6716 ** CAPI3REF: Checkpoint a database
6717 **
6718 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
6719 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
6720 ** empty string, then a checkpoint is run on all databases of
6721 ** connection D.  ^If the database connection D is not in
6722 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
6723 **
6724 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
6725 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
6726 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
6727 ** run whenever the WAL reaches a certain size threshold.
6728 */
6729 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
6730
6731 /*
6732 ** Undo the hack that converts floating point types to integer for
6733 ** builds on processors without floating point support.
6734 */
6735 #ifdef SQLITE_OMIT_FLOATING_POINT
6736 # undef double
6737 #endif
6738
6739 #if 0
6740 }  /* End of the 'extern "C"' block */
6741 #endif
6742 #endif
6743
6744 /*
6745 ** 2010 August 30
6746 **
6747 ** The author disclaims copyright to this source code.  In place of
6748 ** a legal notice, here is a blessing:
6749 **
6750 **    May you do good and not evil.
6751 **    May you find forgiveness for yourself and forgive others.
6752 **    May you share freely, never taking more than you give.
6753 **
6754 *************************************************************************
6755 */
6756
6757 #ifndef _SQLITE3RTREE_H_
6758 #define _SQLITE3RTREE_H_
6759
6760
6761 #if 0
6762 extern "C" {
6763 #endif
6764
6765 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
6766
6767 /*
6768 ** Register a geometry callback named zGeom that can be used as part of an
6769 ** R-Tree geometry query as follows:
6770 **
6771 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
6772 */
6773 SQLITE_API int sqlite3_rtree_geometry_callback(
6774   sqlite3 *db,
6775   const char *zGeom,
6776   int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
6777   void *pContext
6778 );
6779
6780
6781 /*
6782 ** A pointer to a structure of the following type is passed as the first
6783 ** argument to callbacks registered using rtree_geometry_callback().
6784 */
6785 struct sqlite3_rtree_geometry {
6786   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
6787   int nParam;                     /* Size of array aParam[] */
6788   double *aParam;                 /* Parameters passed to SQL geom function */
6789   void *pUser;                    /* Callback implementation user data */
6790   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
6791 };
6792
6793
6794 #if 0
6795 }  /* end of the 'extern "C"' block */
6796 #endif
6797
6798 #endif  /* ifndef _SQLITE3RTREE_H_ */
6799
6800
6801 /************** End of sqlite3.h *********************************************/
6802 /************** Continuing where we left off in sqliteInt.h ******************/
6803 /************** Include hash.h in the middle of sqliteInt.h ******************/
6804 /************** Begin file hash.h ********************************************/
6805 /*
6806 ** 2001 September 22
6807 **
6808 ** The author disclaims copyright to this source code.  In place of
6809 ** a legal notice, here is a blessing:
6810 **
6811 **    May you do good and not evil.
6812 **    May you find forgiveness for yourself and forgive others.
6813 **    May you share freely, never taking more than you give.
6814 **
6815 *************************************************************************
6816 ** This is the header file for the generic hash-table implemenation
6817 ** used in SQLite.
6818 */
6819 #ifndef _SQLITE_HASH_H_
6820 #define _SQLITE_HASH_H_
6821
6822 /* Forward declarations of structures. */
6823 typedef struct Hash Hash;
6824 typedef struct HashElem HashElem;
6825
6826 /* A complete hash table is an instance of the following structure.
6827 ** The internals of this structure are intended to be opaque -- client
6828 ** code should not attempt to access or modify the fields of this structure
6829 ** directly.  Change this structure only by using the routines below.
6830 ** However, some of the "procedures" and "functions" for modifying and
6831 ** accessing this structure are really macros, so we can't really make
6832 ** this structure opaque.
6833 **
6834 ** All elements of the hash table are on a single doubly-linked list.
6835 ** Hash.first points to the head of this list.
6836 **
6837 ** There are Hash.htsize buckets.  Each bucket points to a spot in
6838 ** the global doubly-linked list.  The contents of the bucket are the
6839 ** element pointed to plus the next _ht.count-1 elements in the list.
6840 **
6841 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6842 ** by a linear search of the global list.  For small tables, the 
6843 ** Hash.ht table is never allocated because if there are few elements
6844 ** in the table, it is faster to do a linear search than to manage
6845 ** the hash table.
6846 */
6847 struct Hash {
6848   unsigned int htsize;      /* Number of buckets in the hash table */
6849   unsigned int count;       /* Number of entries in this table */
6850   HashElem *first;          /* The first element of the array */
6851   struct _ht {              /* the hash table */
6852     int count;                 /* Number of entries with this hash */
6853     HashElem *chain;           /* Pointer to first entry with this hash */
6854   } *ht;
6855 };
6856
6857 /* Each element in the hash table is an instance of the following 
6858 ** structure.  All elements are stored on a single doubly-linked list.
6859 **
6860 ** Again, this structure is intended to be opaque, but it can't really
6861 ** be opaque because it is used by macros.
6862 */
6863 struct HashElem {
6864   HashElem *next, *prev;       /* Next and previous elements in the table */
6865   void *data;                  /* Data associated with this element */
6866   const char *pKey; int nKey;  /* Key associated with this element */
6867 };
6868
6869 /*
6870 ** Access routines.  To delete, insert a NULL pointer.
6871 */
6872 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6873 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6874 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6875 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6876
6877 /*
6878 ** Macros for looping over all elements of a hash table.  The idiom is
6879 ** like this:
6880 **
6881 **   Hash h;
6882 **   HashElem *p;
6883 **   ...
6884 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6885 **     SomeStructure *pData = sqliteHashData(p);
6886 **     // do something with pData
6887 **   }
6888 */
6889 #define sqliteHashFirst(H)  ((H)->first)
6890 #define sqliteHashNext(E)   ((E)->next)
6891 #define sqliteHashData(E)   ((E)->data)
6892 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6893 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6894
6895 /*
6896 ** Number of entries in a hash table
6897 */
6898 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6899
6900 #endif /* _SQLITE_HASH_H_ */
6901
6902 /************** End of hash.h ************************************************/
6903 /************** Continuing where we left off in sqliteInt.h ******************/
6904 /************** Include parse.h in the middle of sqliteInt.h *****************/
6905 /************** Begin file parse.h *******************************************/
6906 #define TK_SEMI                            1
6907 #define TK_EXPLAIN                         2
6908 #define TK_QUERY                           3
6909 #define TK_PLAN                            4
6910 #define TK_BEGIN                           5
6911 #define TK_TRANSACTION                     6
6912 #define TK_DEFERRED                        7
6913 #define TK_IMMEDIATE                       8
6914 #define TK_EXCLUSIVE                       9
6915 #define TK_COMMIT                         10
6916 #define TK_END                            11
6917 #define TK_ROLLBACK                       12
6918 #define TK_SAVEPOINT                      13
6919 #define TK_RELEASE                        14
6920 #define TK_TO                             15
6921 #define TK_TABLE                          16
6922 #define TK_CREATE                         17
6923 #define TK_IF                             18
6924 #define TK_NOT                            19
6925 #define TK_EXISTS                         20
6926 #define TK_TEMP                           21
6927 #define TK_LP                             22
6928 #define TK_RP                             23
6929 #define TK_AS                             24
6930 #define TK_COMMA                          25
6931 #define TK_ID                             26
6932 #define TK_INDEXED                        27
6933 #define TK_ABORT                          28
6934 #define TK_ACTION                         29
6935 #define TK_AFTER                          30
6936 #define TK_ANALYZE                        31
6937 #define TK_ASC                            32
6938 #define TK_ATTACH                         33
6939 #define TK_BEFORE                         34
6940 #define TK_BY                             35
6941 #define TK_CASCADE                        36
6942 #define TK_CAST                           37
6943 #define TK_COLUMNKW                       38
6944 #define TK_CONFLICT                       39
6945 #define TK_DATABASE                       40
6946 #define TK_DESC                           41
6947 #define TK_DETACH                         42
6948 #define TK_EACH                           43
6949 #define TK_FAIL                           44
6950 #define TK_FOR                            45
6951 #define TK_IGNORE                         46
6952 #define TK_INITIALLY                      47
6953 #define TK_INSTEAD                        48
6954 #define TK_LIKE_KW                        49
6955 #define TK_MATCH                          50
6956 #define TK_NO                             51
6957 #define TK_KEY                            52
6958 #define TK_OF                             53
6959 #define TK_OFFSET                         54
6960 #define TK_PRAGMA                         55
6961 #define TK_RAISE                          56
6962 #define TK_REPLACE                        57
6963 #define TK_RESTRICT                       58
6964 #define TK_ROW                            59
6965 #define TK_TRIGGER                        60
6966 #define TK_VACUUM                         61
6967 #define TK_VIEW                           62
6968 #define TK_VIRTUAL                        63
6969 #define TK_REINDEX                        64
6970 #define TK_RENAME                         65
6971 #define TK_CTIME_KW                       66
6972 #define TK_ANY                            67
6973 #define TK_OR                             68
6974 #define TK_AND                            69
6975 #define TK_IS                             70
6976 #define TK_BETWEEN                        71
6977 #define TK_IN                             72
6978 #define TK_ISNULL                         73
6979 #define TK_NOTNULL                        74
6980 #define TK_NE                             75
6981 #define TK_EQ                             76
6982 #define TK_GT                             77
6983 #define TK_LE                             78
6984 #define TK_LT                             79
6985 #define TK_GE                             80
6986 #define TK_ESCAPE                         81
6987 #define TK_BITAND                         82
6988 #define TK_BITOR                          83
6989 #define TK_LSHIFT                         84
6990 #define TK_RSHIFT                         85
6991 #define TK_PLUS                           86
6992 #define TK_MINUS                          87
6993 #define TK_STAR                           88
6994 #define TK_SLASH                          89
6995 #define TK_REM                            90
6996 #define TK_CONCAT                         91
6997 #define TK_COLLATE                        92
6998 #define TK_BITNOT                         93
6999 #define TK_STRING                         94
7000 #define TK_JOIN_KW                        95
7001 #define TK_CONSTRAINT                     96
7002 #define TK_DEFAULT                        97
7003 #define TK_NULL                           98
7004 #define TK_PRIMARY                        99
7005 #define TK_UNIQUE                         100
7006 #define TK_CHECK                          101
7007 #define TK_REFERENCES                     102
7008 #define TK_AUTOINCR                       103
7009 #define TK_ON                             104
7010 #define TK_INSERT                         105
7011 #define TK_DELETE                         106
7012 #define TK_UPDATE                         107
7013 #define TK_SET                            108
7014 #define TK_DEFERRABLE                     109
7015 #define TK_FOREIGN                        110
7016 #define TK_DROP                           111
7017 #define TK_UNION                          112
7018 #define TK_ALL                            113
7019 #define TK_EXCEPT                         114
7020 #define TK_INTERSECT                      115
7021 #define TK_SELECT                         116
7022 #define TK_DISTINCT                       117
7023 #define TK_DOT                            118
7024 #define TK_FROM                           119
7025 #define TK_JOIN                           120
7026 #define TK_USING                          121
7027 #define TK_ORDER                          122
7028 #define TK_GROUP                          123
7029 #define TK_HAVING                         124
7030 #define TK_LIMIT                          125
7031 #define TK_WHERE                          126
7032 #define TK_INTO                           127
7033 #define TK_VALUES                         128
7034 #define TK_INTEGER                        129
7035 #define TK_FLOAT                          130
7036 #define TK_BLOB                           131
7037 #define TK_REGISTER                       132
7038 #define TK_VARIABLE                       133
7039 #define TK_CASE                           134
7040 #define TK_WHEN                           135
7041 #define TK_THEN                           136
7042 #define TK_ELSE                           137
7043 #define TK_INDEX                          138
7044 #define TK_ALTER                          139
7045 #define TK_ADD                            140
7046 #define TK_TO_TEXT                        141
7047 #define TK_TO_BLOB                        142
7048 #define TK_TO_NUMERIC                     143
7049 #define TK_TO_INT                         144
7050 #define TK_TO_REAL                        145
7051 #define TK_ISNOT                          146
7052 #define TK_END_OF_FILE                    147
7053 #define TK_ILLEGAL                        148
7054 #define TK_SPACE                          149
7055 #define TK_UNCLOSED_STRING                150
7056 #define TK_FUNCTION                       151
7057 #define TK_COLUMN                         152
7058 #define TK_AGG_FUNCTION                   153
7059 #define TK_AGG_COLUMN                     154
7060 #define TK_CONST_FUNC                     155
7061 #define TK_UMINUS                         156
7062 #define TK_UPLUS                          157
7063
7064 /************** End of parse.h ***********************************************/
7065 /************** Continuing where we left off in sqliteInt.h ******************/
7066 #include <stdio.h>
7067 #include <stdlib.h>
7068 #include <string.h>
7069 #include <assert.h>
7070 #include <stddef.h>
7071
7072 /*
7073 ** If compiling for a processor that lacks floating point support,
7074 ** substitute integer for floating-point
7075 */
7076 #ifdef SQLITE_OMIT_FLOATING_POINT
7077 # define double sqlite_int64
7078 # define float sqlite_int64
7079 # define LONGDOUBLE_TYPE sqlite_int64
7080 # ifndef SQLITE_BIG_DBL
7081 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7082 # endif
7083 # define SQLITE_OMIT_DATETIME_FUNCS 1
7084 # define SQLITE_OMIT_TRACE 1
7085 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7086 # undef SQLITE_HAVE_ISNAN
7087 #endif
7088 #ifndef SQLITE_BIG_DBL
7089 # define SQLITE_BIG_DBL (1e99)
7090 #endif
7091
7092 /*
7093 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7094 ** afterward. Having this macro allows us to cause the C compiler 
7095 ** to omit code used by TEMP tables without messy #ifndef statements.
7096 */
7097 #ifdef SQLITE_OMIT_TEMPDB
7098 #define OMIT_TEMPDB 1
7099 #else
7100 #define OMIT_TEMPDB 0
7101 #endif
7102
7103 /*
7104 ** The "file format" number is an integer that is incremented whenever
7105 ** the VDBE-level file format changes.  The following macros define the
7106 ** the default file format for new databases and the maximum file format
7107 ** that the library can read.
7108 */
7109 #define SQLITE_MAX_FILE_FORMAT 4
7110 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7111 # define SQLITE_DEFAULT_FILE_FORMAT 1
7112 #endif
7113
7114 /*
7115 ** Determine whether triggers are recursive by default.  This can be
7116 ** changed at run-time using a pragma.
7117 */
7118 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7119 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7120 #endif
7121
7122 /*
7123 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7124 ** on the command-line
7125 */
7126 #ifndef SQLITE_TEMP_STORE
7127 # define SQLITE_TEMP_STORE 1
7128 #endif
7129
7130 /*
7131 ** GCC does not define the offsetof() macro so we'll have to do it
7132 ** ourselves.
7133 */
7134 #ifndef offsetof
7135 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7136 #endif
7137
7138 /*
7139 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7140 ** not, there are still machines out there that use EBCDIC.)
7141 */
7142 #if 'A' == '\301'
7143 # define SQLITE_EBCDIC 1
7144 #else
7145 # define SQLITE_ASCII 1
7146 #endif
7147
7148 /*
7149 ** Integers of known sizes.  These typedefs might change for architectures
7150 ** where the sizes very.  Preprocessor macros are available so that the
7151 ** types can be conveniently redefined at compile-type.  Like this:
7152 **
7153 **         cc '-DUINTPTR_TYPE=long long int' ...
7154 */
7155 #ifndef UINT32_TYPE
7156 # ifdef HAVE_UINT32_T
7157 #  define UINT32_TYPE uint32_t
7158 # else
7159 #  define UINT32_TYPE unsigned int
7160 # endif
7161 #endif
7162 #ifndef UINT16_TYPE
7163 # ifdef HAVE_UINT16_T
7164 #  define UINT16_TYPE uint16_t
7165 # else
7166 #  define UINT16_TYPE unsigned short int
7167 # endif
7168 #endif
7169 #ifndef INT16_TYPE
7170 # ifdef HAVE_INT16_T
7171 #  define INT16_TYPE int16_t
7172 # else
7173 #  define INT16_TYPE short int
7174 # endif
7175 #endif
7176 #ifndef UINT8_TYPE
7177 # ifdef HAVE_UINT8_T
7178 #  define UINT8_TYPE uint8_t
7179 # else
7180 #  define UINT8_TYPE unsigned char
7181 # endif
7182 #endif
7183 #ifndef INT8_TYPE
7184 # ifdef HAVE_INT8_T
7185 #  define INT8_TYPE int8_t
7186 # else
7187 #  define INT8_TYPE signed char
7188 # endif
7189 #endif
7190 #ifndef LONGDOUBLE_TYPE
7191 # define LONGDOUBLE_TYPE long double
7192 #endif
7193 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7194 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7195 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7196 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7197 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7198 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7199 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7200
7201 /*
7202 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7203 ** that can be stored in a u32 without loss of data.  The value
7204 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7205 ** have to specify the value in the less intuitive manner shown:
7206 */
7207 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
7208
7209 /*
7210 ** Macros to determine whether the machine is big or little endian,
7211 ** evaluated at runtime.
7212 */
7213 #ifdef SQLITE_AMALGAMATION
7214 SQLITE_PRIVATE const int sqlite3one = 1;
7215 #else
7216 SQLITE_PRIVATE const int sqlite3one;
7217 #endif
7218 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7219                              || defined(__x86_64) || defined(__x86_64__)
7220 # define SQLITE_BIGENDIAN    0
7221 # define SQLITE_LITTLEENDIAN 1
7222 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7223 #else
7224 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7225 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7226 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7227 #endif
7228
7229 /*
7230 ** Constants for the largest and smallest possible 64-bit signed integers.
7231 ** These macros are designed to work correctly on both 32-bit and 64-bit
7232 ** compilers.
7233 */
7234 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7235 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7236
7237 /* 
7238 ** Round up a number to the next larger multiple of 8.  This is used
7239 ** to force 8-byte alignment on 64-bit architectures.
7240 */
7241 #define ROUND8(x)     (((x)+7)&~7)
7242
7243 /*
7244 ** Round down to the nearest multiple of 8
7245 */
7246 #define ROUNDDOWN8(x) ((x)&~7)
7247
7248 /*
7249 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
7250 ** macro is used only within assert() to verify that the code gets
7251 ** all alignment restrictions correct.
7252 **
7253 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7254 ** underlying malloc() implemention might return us 4-byte aligned
7255 ** pointers.  In that case, only verify 4-byte alignment.
7256 */
7257 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7258 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
7259 #else
7260 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
7261 #endif
7262
7263
7264 /*
7265 ** An instance of the following structure is used to store the busy-handler
7266 ** callback for a given sqlite handle. 
7267 **
7268 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7269 ** callback for the database handle. Each pager opened via the sqlite
7270 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7271 ** callback is currently invoked only from within pager.c.
7272 */
7273 typedef struct BusyHandler BusyHandler;
7274 struct BusyHandler {
7275   int (*xFunc)(void *,int);  /* The busy callback */
7276   void *pArg;                /* First arg to busy callback */
7277   int nBusy;                 /* Incremented with each busy call */
7278 };
7279
7280 /*
7281 ** Name of the master database table.  The master database table
7282 ** is a special table that holds the names and attributes of all
7283 ** user tables and indices.
7284 */
7285 #define MASTER_NAME       "sqlite_master"
7286 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7287
7288 /*
7289 ** The root-page of the master database table.
7290 */
7291 #define MASTER_ROOT       1
7292
7293 /*
7294 ** The name of the schema table.
7295 */
7296 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7297
7298 /*
7299 ** A convenience macro that returns the number of elements in
7300 ** an array.
7301 */
7302 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7303
7304 /*
7305 ** The following value as a destructor means to use sqlite3DbFree().
7306 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7307 */
7308 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7309
7310 /*
7311 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7312 ** not support Writable Static Data (WSD) such as global and static variables.
7313 ** All variables must either be on the stack or dynamically allocated from
7314 ** the heap.  When WSD is unsupported, the variable declarations scattered
7315 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7316 ** macro is used for this purpose.  And instead of referencing the variable
7317 ** directly, we use its constant as a key to lookup the run-time allocated
7318 ** buffer that holds real variable.  The constant is also the initializer
7319 ** for the run-time allocated buffer.
7320 **
7321 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7322 ** macros become no-ops and have zero performance impact.
7323 */
7324 #ifdef SQLITE_OMIT_WSD
7325   #define SQLITE_WSD const
7326   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7327   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7328 SQLITE_API   int sqlite3_wsd_init(int N, int J);
7329 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7330 #else
7331   #define SQLITE_WSD 
7332   #define GLOBAL(t,v) v
7333   #define sqlite3GlobalConfig sqlite3Config
7334 #endif
7335
7336 /*
7337 ** The following macros are used to suppress compiler warnings and to
7338 ** make it clear to human readers when a function parameter is deliberately 
7339 ** left unused within the body of a function. This usually happens when
7340 ** a function is called via a function pointer. For example the 
7341 ** implementation of an SQL aggregate step callback may not use the
7342 ** parameter indicating the number of arguments passed to the aggregate,
7343 ** if it knows that this is enforced elsewhere.
7344 **
7345 ** When a function parameter is not used at all within the body of a function,
7346 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7347 ** However, these macros may also be used to suppress warnings related to
7348 ** parameters that may or may not be used depending on compilation options.
7349 ** For example those parameters only used in assert() statements. In these
7350 ** cases the parameters are named as per the usual conventions.
7351 */
7352 #define UNUSED_PARAMETER(x) (void)(x)
7353 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7354
7355 /*
7356 ** Forward references to structures
7357 */
7358 typedef struct AggInfo AggInfo;
7359 typedef struct AuthContext AuthContext;
7360 typedef struct AutoincInfo AutoincInfo;
7361 typedef struct Bitvec Bitvec;
7362 typedef struct CollSeq CollSeq;
7363 typedef struct Column Column;
7364 typedef struct Db Db;
7365 typedef struct Schema Schema;
7366 typedef struct Expr Expr;
7367 typedef struct ExprList ExprList;
7368 typedef struct ExprSpan ExprSpan;
7369 typedef struct FKey FKey;
7370 typedef struct FuncDestructor FuncDestructor;
7371 typedef struct FuncDef FuncDef;
7372 typedef struct FuncDefHash FuncDefHash;
7373 typedef struct IdList IdList;
7374 typedef struct Index Index;
7375 typedef struct IndexSample IndexSample;
7376 typedef struct KeyClass KeyClass;
7377 typedef struct KeyInfo KeyInfo;
7378 typedef struct Lookaside Lookaside;
7379 typedef struct LookasideSlot LookasideSlot;
7380 typedef struct Module Module;
7381 typedef struct NameContext NameContext;
7382 typedef struct Parse Parse;
7383 typedef struct RowSet RowSet;
7384 typedef struct Savepoint Savepoint;
7385 typedef struct Select Select;
7386 typedef struct SrcList SrcList;
7387 typedef struct StrAccum StrAccum;
7388 typedef struct Table Table;
7389 typedef struct TableLock TableLock;
7390 typedef struct Token Token;
7391 typedef struct Trigger Trigger;
7392 typedef struct TriggerPrg TriggerPrg;
7393 typedef struct TriggerStep TriggerStep;
7394 typedef struct UnpackedRecord UnpackedRecord;
7395 typedef struct VTable VTable;
7396 typedef struct Walker Walker;
7397 typedef struct WherePlan WherePlan;
7398 typedef struct WhereInfo WhereInfo;
7399 typedef struct WhereLevel WhereLevel;
7400
7401 /*
7402 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
7403 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7404 ** pointer types (i.e. FuncDef) defined above.
7405 */
7406 /************** Include btree.h in the middle of sqliteInt.h *****************/
7407 /************** Begin file btree.h *******************************************/
7408 /*
7409 ** 2001 September 15
7410 **
7411 ** The author disclaims copyright to this source code.  In place of
7412 ** a legal notice, here is a blessing:
7413 **
7414 **    May you do good and not evil.
7415 **    May you find forgiveness for yourself and forgive others.
7416 **    May you share freely, never taking more than you give.
7417 **
7418 *************************************************************************
7419 ** This header file defines the interface that the sqlite B-Tree file
7420 ** subsystem.  See comments in the source code for a detailed description
7421 ** of what each interface routine does.
7422 */
7423 #ifndef _BTREE_H_
7424 #define _BTREE_H_
7425
7426 /* TODO: This definition is just included so other modules compile. It
7427 ** needs to be revisited.
7428 */
7429 #define SQLITE_N_BTREE_META 10
7430
7431 /*
7432 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7433 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7434 */
7435 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7436   #define SQLITE_DEFAULT_AUTOVACUUM 0
7437 #endif
7438
7439 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7440 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7441 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7442
7443 /*
7444 ** Forward declarations of structure
7445 */
7446 typedef struct Btree Btree;
7447 typedef struct BtCursor BtCursor;
7448 typedef struct BtShared BtShared;
7449 typedef struct BtreeMutexArray BtreeMutexArray;
7450
7451 /*
7452 ** This structure records all of the Btrees that need to hold
7453 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
7454 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
7455 ** we can always lock and unlock them all quickly.
7456 */
7457 struct BtreeMutexArray {
7458   int nMutex;
7459   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
7460 };
7461
7462
7463 SQLITE_PRIVATE int sqlite3BtreeOpen(
7464   const char *zFilename,   /* Name of database file to open */
7465   sqlite3 *db,             /* Associated database connection */
7466   Btree **ppBtree,         /* Return open Btree* here */
7467   int flags,               /* Flags */
7468   int vfsFlags             /* Flags passed through to VFS open */
7469 );
7470
7471 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7472 ** following values.
7473 **
7474 ** NOTE:  These values must match the corresponding PAGER_ values in
7475 ** pager.h.
7476 */
7477 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
7478 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7479 #define BTREE_MEMORY        4  /* This is an in-memory DB */
7480 #define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
7481 #define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
7482
7483 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7484 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7485 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
7486 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7487 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7488 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7489 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7490 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7491 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7492 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7493 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7494 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7495 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7496 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7497 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
7498 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7499 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7500 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7501 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
7502 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
7503 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
7504 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
7505 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
7506 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
7507 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
7508 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
7509
7510 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
7511 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
7512 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
7513
7514 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
7515
7516 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
7517 ** of the flags shown below.
7518 **
7519 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
7520 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
7521 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
7522 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
7523 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
7524 ** indices.)
7525 */
7526 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
7527 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
7528
7529 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
7530 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
7531 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
7532
7533 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
7534 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
7535
7536 /*
7537 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
7538 ** should be one of the following values. The integer values are assigned 
7539 ** to constants so that the offset of the corresponding field in an
7540 ** SQLite database header may be found using the following formula:
7541 **
7542 **   offset = 36 + (idx * 4)
7543 **
7544 ** For example, the free-page-count field is located at byte offset 36 of
7545 ** the database file header. The incr-vacuum-flag field is located at
7546 ** byte offset 64 (== 36+4*7).
7547 */
7548 #define BTREE_FREE_PAGE_COUNT     0
7549 #define BTREE_SCHEMA_VERSION      1
7550 #define BTREE_FILE_FORMAT         2
7551 #define BTREE_DEFAULT_CACHE_SIZE  3
7552 #define BTREE_LARGEST_ROOT_PAGE   4
7553 #define BTREE_TEXT_ENCODING       5
7554 #define BTREE_USER_VERSION        6
7555 #define BTREE_INCR_VACUUM         7
7556
7557 SQLITE_PRIVATE int sqlite3BtreeCursor(
7558   Btree*,                              /* BTree containing table to open */
7559   int iTable,                          /* Index of root page */
7560   int wrFlag,                          /* 1 for writing.  0 for read-only */
7561   struct KeyInfo*,                     /* First argument to compare function */
7562   BtCursor *pCursor                    /* Space to write cursor structure */
7563 );
7564 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7565 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7566
7567 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7568 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7569   BtCursor*,
7570   UnpackedRecord *pUnKey,
7571   i64 intKey,
7572   int bias,
7573   int *pRes
7574 );
7575 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7576 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7577 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7578                                   const void *pData, int nData,
7579                                   int nZero, int bias, int seekResult);
7580 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7581 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7582 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7583 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7584 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7585 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7586 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7587 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7588 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7589 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7590 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7591 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7592 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7593
7594 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7595 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7596
7597 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7598 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7599 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7600
7601 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
7602
7603 #ifndef NDEBUG
7604 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7605 #endif
7606
7607 #ifndef SQLITE_OMIT_BTREECOUNT
7608 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7609 #endif
7610
7611 #ifdef SQLITE_TEST
7612 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7613 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7614 #endif
7615
7616 #ifndef SQLITE_OMIT_WAL
7617 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*);
7618 #endif
7619
7620 /*
7621 ** If we are not using shared cache, then there is no need to
7622 ** use mutexes to access the BtShared structures.  So make the
7623 ** Enter and Leave procedures no-ops.
7624 */
7625 #ifndef SQLITE_OMIT_SHARED_CACHE
7626 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7627 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7628 #else
7629 # define sqlite3BtreeEnter(X) 
7630 # define sqlite3BtreeEnterAll(X)
7631 #endif
7632
7633 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7634 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7635 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7636 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7637 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7638 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7639 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7640 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7641 #ifndef NDEBUG
7642   /* These routines are used inside assert() statements only. */
7643 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7644 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7645 #endif
7646 #else
7647
7648 # define sqlite3BtreeLeave(X)
7649 # define sqlite3BtreeEnterCursor(X)
7650 # define sqlite3BtreeLeaveCursor(X)
7651 # define sqlite3BtreeLeaveAll(X)
7652 # define sqlite3BtreeMutexArrayEnter(X)
7653 # define sqlite3BtreeMutexArrayLeave(X)
7654 # define sqlite3BtreeMutexArrayInsert(X,Y)
7655
7656 # define sqlite3BtreeHoldsMutex(X) 1
7657 # define sqlite3BtreeHoldsAllMutexes(X) 1
7658 #endif
7659
7660
7661 #endif /* _BTREE_H_ */
7662
7663 /************** End of btree.h ***********************************************/
7664 /************** Continuing where we left off in sqliteInt.h ******************/
7665 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7666 /************** Begin file vdbe.h ********************************************/
7667 /*
7668 ** 2001 September 15
7669 **
7670 ** The author disclaims copyright to this source code.  In place of
7671 ** a legal notice, here is a blessing:
7672 **
7673 **    May you do good and not evil.
7674 **    May you find forgiveness for yourself and forgive others.
7675 **    May you share freely, never taking more than you give.
7676 **
7677 *************************************************************************
7678 ** Header file for the Virtual DataBase Engine (VDBE)
7679 **
7680 ** This header defines the interface to the virtual database engine
7681 ** or VDBE.  The VDBE implements an abstract machine that runs a
7682 ** simple program to access and modify the underlying database.
7683 */
7684 #ifndef _SQLITE_VDBE_H_
7685 #define _SQLITE_VDBE_H_
7686
7687 /*
7688 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7689 ** in the source file sqliteVdbe.c are allowed to see the insides
7690 ** of this structure.
7691 */
7692 typedef struct Vdbe Vdbe;
7693
7694 /*
7695 ** The names of the following types declared in vdbeInt.h are required
7696 ** for the VdbeOp definition.
7697 */
7698 typedef struct VdbeFunc VdbeFunc;
7699 typedef struct Mem Mem;
7700 typedef struct SubProgram SubProgram;
7701
7702 /*
7703 ** A single instruction of the virtual machine has an opcode
7704 ** and as many as three operands.  The instruction is recorded
7705 ** as an instance of the following structure:
7706 */
7707 struct VdbeOp {
7708   u8 opcode;          /* What operation to perform */
7709   signed char p4type; /* One of the P4_xxx constants for p4 */
7710   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7711   u8 p5;              /* Fifth parameter is an unsigned character */
7712   int p1;             /* First operand */
7713   int p2;             /* Second parameter (often the jump destination) */
7714   int p3;             /* The third parameter */
7715   union {             /* fourth parameter */
7716     int i;                 /* Integer value if p4type==P4_INT32 */
7717     void *p;               /* Generic pointer */
7718     char *z;               /* Pointer to data for string (char array) types */
7719     i64 *pI64;             /* Used when p4type is P4_INT64 */
7720     double *pReal;         /* Used when p4type is P4_REAL */
7721     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7722     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7723     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7724     Mem *pMem;             /* Used when p4type is P4_MEM */
7725     VTable *pVtab;         /* Used when p4type is P4_VTAB */
7726     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7727     int *ai;               /* Used when p4type is P4_INTARRAY */
7728     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7729   } p4;
7730 #ifdef SQLITE_DEBUG
7731   char *zComment;          /* Comment to improve readability */
7732 #endif
7733 #ifdef VDBE_PROFILE
7734   int cnt;                 /* Number of times this instruction was executed */
7735   u64 cycles;              /* Total time spent executing this instruction */
7736 #endif
7737 };
7738 typedef struct VdbeOp VdbeOp;
7739
7740
7741 /*
7742 ** A sub-routine used to implement a trigger program.
7743 */
7744 struct SubProgram {
7745   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7746   int nOp;                      /* Elements in aOp[] */
7747   int nMem;                     /* Number of memory cells required */
7748   int nCsr;                     /* Number of cursors required */
7749   void *token;                  /* id that may be used to recursive triggers */
7750   SubProgram *pNext;            /* Next sub-program already visited */
7751 };
7752
7753 /*
7754 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7755 ** it takes up less space.
7756 */
7757 struct VdbeOpList {
7758   u8 opcode;          /* What operation to perform */
7759   signed char p1;     /* First operand */
7760   signed char p2;     /* Second parameter (often the jump destination) */
7761   signed char p3;     /* Third parameter */
7762 };
7763 typedef struct VdbeOpList VdbeOpList;
7764
7765 /*
7766 ** Allowed values of VdbeOp.p4type
7767 */
7768 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7769 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7770 #define P4_STATIC   (-2)  /* Pointer to a static string */
7771 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7772 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7773 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7774 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7775 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7776 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7777 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7778 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7779 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7780 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7781 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7782 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7783 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7784
7785 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7786 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7787 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7788 ** gets freed when the Vdbe is finalized so it still should be obtained
7789 ** from a single sqliteMalloc().  But no copy is made and the calling
7790 ** function should *not* try to free the KeyInfo.
7791 */
7792 #define P4_KEYINFO_HANDOFF (-16)
7793 #define P4_KEYINFO_STATIC  (-17)
7794
7795 /*
7796 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7797 ** number of columns of data returned by the statement.
7798 */
7799 #define COLNAME_NAME     0
7800 #define COLNAME_DECLTYPE 1
7801 #define COLNAME_DATABASE 2
7802 #define COLNAME_TABLE    3
7803 #define COLNAME_COLUMN   4
7804 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7805 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7806 #else
7807 # ifdef SQLITE_OMIT_DECLTYPE
7808 #   define COLNAME_N      1      /* Store only the name */
7809 # else
7810 #   define COLNAME_N      2      /* Store the name and decltype */
7811 # endif
7812 #endif
7813
7814 /*
7815 ** The following macro converts a relative address in the p2 field
7816 ** of a VdbeOp structure into a negative number so that 
7817 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7818 ** the macro again restores the address.
7819 */
7820 #define ADDR(X)  (-1-(X))
7821
7822 /*
7823 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7824 ** header file that defines a number for each opcode used by the VDBE.
7825 */
7826 /************** Include opcodes.h in the middle of vdbe.h ********************/
7827 /************** Begin file opcodes.h *****************************************/
7828 /* Automatically generated.  Do not edit */
7829 /* See the mkopcodeh.awk script for details */
7830 #define OP_Goto                                 1
7831 #define OP_Gosub                                2
7832 #define OP_Return                               3
7833 #define OP_Yield                                4
7834 #define OP_HaltIfNull                           5
7835 #define OP_Halt                                 6
7836 #define OP_Integer                              7
7837 #define OP_Int64                                8
7838 #define OP_Real                               130   /* same as TK_FLOAT    */
7839 #define OP_String8                             94   /* same as TK_STRING   */
7840 #define OP_String                               9
7841 #define OP_Null                                10
7842 #define OP_Blob                                11
7843 #define OP_Variable                            12
7844 #define OP_Move                                13
7845 #define OP_Copy                                14
7846 #define OP_SCopy                               15
7847 #define OP_ResultRow                           16
7848 #define OP_Concat                              91   /* same as TK_CONCAT   */
7849 #define OP_Add                                 86   /* same as TK_PLUS     */
7850 #define OP_Subtract                            87   /* same as TK_MINUS    */
7851 #define OP_Multiply                            88   /* same as TK_STAR     */
7852 #define OP_Divide                              89   /* same as TK_SLASH    */
7853 #define OP_Remainder                           90   /* same as TK_REM      */
7854 #define OP_CollSeq                             17
7855 #define OP_Function                            18
7856 #define OP_BitAnd                              82   /* same as TK_BITAND   */
7857 #define OP_BitOr                               83   /* same as TK_BITOR    */
7858 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7859 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7860 #define OP_AddImm                              20
7861 #define OP_MustBeInt                           21
7862 #define OP_RealAffinity                        22
7863 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
7864 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7865 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7866 #define OP_ToInt                              144   /* same as TK_TO_INT   */
7867 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
7868 #define OP_Eq                                  76   /* same as TK_EQ       */
7869 #define OP_Ne                                  75   /* same as TK_NE       */
7870 #define OP_Lt                                  79   /* same as TK_LT       */
7871 #define OP_Le                                  78   /* same as TK_LE       */
7872 #define OP_Gt                                  77   /* same as TK_GT       */
7873 #define OP_Ge                                  80   /* same as TK_GE       */
7874 #define OP_Permutation                         23
7875 #define OP_Compare                             24
7876 #define OP_Jump                                25
7877 #define OP_And                                 69   /* same as TK_AND      */
7878 #define OP_Or                                  68   /* same as TK_OR       */
7879 #define OP_Not                                 19   /* same as TK_NOT      */
7880 #define OP_BitNot                              93   /* same as TK_BITNOT   */
7881 #define OP_If                                  26
7882 #define OP_IfNot                               27
7883 #define OP_IsNull                              73   /* same as TK_ISNULL   */
7884 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
7885 #define OP_Column                              28
7886 #define OP_Affinity                            29
7887 #define OP_MakeRecord                          30
7888 #define OP_Count                               31
7889 #define OP_Savepoint                           32
7890 #define OP_AutoCommit                          33
7891 #define OP_Transaction                         34
7892 #define OP_ReadCookie                          35
7893 #define OP_SetCookie                           36
7894 #define OP_VerifyCookie                        37
7895 #define OP_OpenRead                            38
7896 #define OP_OpenWrite                           39
7897 #define OP_OpenAutoindex                       40
7898 #define OP_OpenEphemeral                       41
7899 #define OP_OpenPseudo                          42
7900 #define OP_Close                               43
7901 #define OP_SeekLt                              44
7902 #define OP_SeekLe                              45
7903 #define OP_SeekGe                              46
7904 #define OP_SeekGt                              47
7905 #define OP_Seek                                48
7906 #define OP_NotFound                            49
7907 #define OP_Found                               50
7908 #define OP_IsUnique                            51
7909 #define OP_NotExists                           52
7910 #define OP_Sequence                            53
7911 #define OP_NewRowid                            54
7912 #define OP_Insert                              55
7913 #define OP_InsertInt                           56
7914 #define OP_Delete                              57
7915 #define OP_ResetCount                          58
7916 #define OP_RowKey                              59
7917 #define OP_RowData                             60
7918 #define OP_Rowid                               61
7919 #define OP_NullRow                             62
7920 #define OP_Last                                63
7921 #define OP_Sort                                64
7922 #define OP_Rewind                              65
7923 #define OP_Prev                                66
7924 #define OP_Next                                67
7925 #define OP_IdxInsert                           70
7926 #define OP_IdxDelete                           71
7927 #define OP_IdxRowid                            72
7928 #define OP_IdxLT                               81
7929 #define OP_IdxGE                               92
7930 #define OP_Destroy                             95
7931 #define OP_Clear                               96
7932 #define OP_CreateIndex                         97
7933 #define OP_CreateTable                         98
7934 #define OP_ParseSchema                         99
7935 #define OP_LoadAnalysis                       100
7936 #define OP_DropTable                          101
7937 #define OP_DropIndex                          102
7938 #define OP_DropTrigger                        103
7939 #define OP_IntegrityCk                        104
7940 #define OP_RowSetAdd                          105
7941 #define OP_RowSetRead                         106
7942 #define OP_RowSetTest                         107
7943 #define OP_Program                            108
7944 #define OP_Param                              109
7945 #define OP_FkCounter                          110
7946 #define OP_FkIfZero                           111
7947 #define OP_MemMax                             112
7948 #define OP_IfPos                              113
7949 #define OP_IfNeg                              114
7950 #define OP_IfZero                             115
7951 #define OP_AggStep                            116
7952 #define OP_AggFinal                           117
7953 #define OP_Checkpoint                         118
7954 #define OP_JournalMode                        119
7955 #define OP_Vacuum                             120
7956 #define OP_IncrVacuum                         121
7957 #define OP_Expire                             122
7958 #define OP_TableLock                          123
7959 #define OP_VBegin                             124
7960 #define OP_VCreate                            125
7961 #define OP_VDestroy                           126
7962 #define OP_VOpen                              127
7963 #define OP_VFilter                            128
7964 #define OP_VColumn                            129
7965 #define OP_VNext                              131
7966 #define OP_VRename                            132
7967 #define OP_VUpdate                            133
7968 #define OP_Pagecount                          134
7969 #define OP_MaxPgcnt                           135
7970 #define OP_Trace                              136
7971 #define OP_Noop                               137
7972 #define OP_Explain                            138
7973
7974 /* The following opcode values are never used */
7975 #define OP_NotUsed_139                        139
7976 #define OP_NotUsed_140                        140
7977
7978
7979 /* Properties such as "out2" or "jump" that are specified in
7980 ** comments following the "case" for each opcode in the vdbe.c
7981 ** are encoded into bitvectors as follows:
7982 */
7983 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7984 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7985 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7986 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7987 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7988 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7989 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7990 #define OPFLG_INITIALIZER {\
7991 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7992 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
7993 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7994 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7995 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7996 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11,\
7997 /*  48 */ 0x08, 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00,\
7998 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01,\
7999 /*  64 */ 0x01, 0x01, 0x01, 0x01, 0x4c, 0x4c, 0x08, 0x00,\
8000 /*  72 */ 0x02, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8001 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8002 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x02,\
8003 /*  96 */ 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8004 /* 104 */ 0x00, 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01,\
8005 /* 112 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
8006 /* 120 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8007 /* 128 */ 0x01, 0x00, 0x02, 0x01, 0x00, 0x00, 0x02, 0x02,\
8008 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
8009 /* 144 */ 0x04, 0x04,}
8010
8011 /************** End of opcodes.h *********************************************/
8012 /************** Continuing where we left off in vdbe.h ***********************/
8013
8014 /*
8015 ** Prototypes for the VDBE interface.  See comments on the implementation
8016 ** for a description of what each of these routines does.
8017 */
8018 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8019 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8020 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8021 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8022 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8023 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8024 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8025 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8026 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
8027 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
8028 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
8029 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8030 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8031 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
8032 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8033 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8034 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8035 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8036 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8037 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8038 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8039 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
8040 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8041 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8042 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8043 #ifdef SQLITE_DEBUG
8044 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8045 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8046 #endif
8047 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8048 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8049 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8050 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8051 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8052 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8053 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8054 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8055 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8056 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8057 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8058 #ifndef SQLITE_OMIT_TRACE
8059 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8060 #endif
8061
8062 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
8063 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
8064 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8065
8066 #ifndef SQLITE_OMIT_TRIGGER
8067 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8068 #endif
8069
8070
8071 #ifndef NDEBUG
8072 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8073 # define VdbeComment(X)  sqlite3VdbeComment X
8074 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8075 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8076 #else
8077 # define VdbeComment(X)
8078 # define VdbeNoopComment(X)
8079 #endif
8080
8081 #endif
8082
8083 /************** End of vdbe.h ************************************************/
8084 /************** Continuing where we left off in sqliteInt.h ******************/
8085 /************** Include pager.h in the middle of sqliteInt.h *****************/
8086 /************** Begin file pager.h *******************************************/
8087 /*
8088 ** 2001 September 15
8089 **
8090 ** The author disclaims copyright to this source code.  In place of
8091 ** a legal notice, here is a blessing:
8092 **
8093 **    May you do good and not evil.
8094 **    May you find forgiveness for yourself and forgive others.
8095 **    May you share freely, never taking more than you give.
8096 **
8097 *************************************************************************
8098 ** This header file defines the interface that the sqlite page cache
8099 ** subsystem.  The page cache subsystem reads and writes a file a page
8100 ** at a time and provides a journal for rollback.
8101 */
8102
8103 #ifndef _PAGER_H_
8104 #define _PAGER_H_
8105
8106 /*
8107 ** Default maximum size for persistent journal files. A negative 
8108 ** value means no limit. This value may be overridden using the 
8109 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8110 */
8111 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8112   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8113 #endif
8114
8115 /*
8116 ** The type used to represent a page number.  The first page in a file
8117 ** is called page 1.  0 is used to represent "not a page".
8118 */
8119 typedef u32 Pgno;
8120
8121 /*
8122 ** Each open file is managed by a separate instance of the "Pager" structure.
8123 */
8124 typedef struct Pager Pager;
8125
8126 /*
8127 ** Handle type for pages.
8128 */
8129 typedef struct PgHdr DbPage;
8130
8131 /*
8132 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8133 ** reserved for working around a windows/posix incompatibility). It is
8134 ** used in the journal to signify that the remainder of the journal file 
8135 ** is devoted to storing a master journal name - there are no more pages to
8136 ** roll back. See comments for function writeMasterJournal() in pager.c 
8137 ** for details.
8138 */
8139 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8140
8141 /*
8142 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8143 **
8144 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8145 */
8146 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8147 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8148 #define PAGER_MEMORY        0x0004    /* In-memory database */
8149
8150 /*
8151 ** Valid values for the second argument to sqlite3PagerLockingMode().
8152 */
8153 #define PAGER_LOCKINGMODE_QUERY      -1
8154 #define PAGER_LOCKINGMODE_NORMAL      0
8155 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8156
8157 /*
8158 ** Numeric constants that encode the journalmode.  
8159 */
8160 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8161 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8162 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8163 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8164 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8165 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8166 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8167
8168 /*
8169 ** The remainder of this file contains the declarations of the functions
8170 ** that make up the Pager sub-system API. See source code comments for 
8171 ** a detailed description of each routine.
8172 */
8173
8174 /* Open and close a Pager connection. */ 
8175 SQLITE_PRIVATE int sqlite3PagerOpen(
8176   sqlite3_vfs*,
8177   Pager **ppPager,
8178   const char*,
8179   int,
8180   int,
8181   int,
8182   void(*)(DbPage*)
8183 );
8184 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8185 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8186
8187 /* Functions used to configure a Pager object. */
8188 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8189 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8190 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8191 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8192 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8193 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8194 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8195 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8196 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8197 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8198 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8199
8200 /* Functions used to obtain and release page references. */ 
8201 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8202 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8203 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8204 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8205 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8206
8207 /* Operations on page references. */
8208 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8209 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8210 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8211 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8212 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
8213 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
8214
8215 /* Functions used to manage pager transactions and savepoints. */
8216 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8217 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8218 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8219 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8220 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8221 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8222 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8223 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8224 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8225 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8226
8227 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager);
8228 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8229 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8230 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8231 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8232
8233 /* Functions used to query pager state and configuration. */
8234 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8235 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8236 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8237 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8238 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8239 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8240 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8241 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8242 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8243 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8244
8245 /* Functions used to truncate the database file. */
8246 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8247
8248 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8249 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8250 #endif
8251
8252 /* Functions to support testing and debugging. */
8253 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8254 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8255 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8256 #endif
8257 #ifdef SQLITE_TEST
8258 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8259 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8260   void disable_simulated_io_errors(void);
8261   void enable_simulated_io_errors(void);
8262 #else
8263 # define disable_simulated_io_errors()
8264 # define enable_simulated_io_errors()
8265 #endif
8266
8267 #endif /* _PAGER_H_ */
8268
8269 /************** End of pager.h ***********************************************/
8270 /************** Continuing where we left off in sqliteInt.h ******************/
8271 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8272 /************** Begin file pcache.h ******************************************/
8273 /*
8274 ** 2008 August 05
8275 **
8276 ** The author disclaims copyright to this source code.  In place of
8277 ** a legal notice, here is a blessing:
8278 **
8279 **    May you do good and not evil.
8280 **    May you find forgiveness for yourself and forgive others.
8281 **    May you share freely, never taking more than you give.
8282 **
8283 *************************************************************************
8284 ** This header file defines the interface that the sqlite page cache
8285 ** subsystem. 
8286 */
8287
8288 #ifndef _PCACHE_H_
8289
8290 typedef struct PgHdr PgHdr;
8291 typedef struct PCache PCache;
8292
8293 /*
8294 ** Every page in the cache is controlled by an instance of the following
8295 ** structure.
8296 */
8297 struct PgHdr {
8298   void *pData;                   /* Content of this page */
8299   void *pExtra;                  /* Extra content */
8300   PgHdr *pDirty;                 /* Transient list of dirty pages */
8301   Pgno pgno;                     /* Page number for this page */
8302   Pager *pPager;                 /* The pager this page is part of */
8303 #ifdef SQLITE_CHECK_PAGES
8304   u32 pageHash;                  /* Hash of page content */
8305 #endif
8306   u16 flags;                     /* PGHDR flags defined below */
8307
8308   /**********************************************************************
8309   ** Elements above are public.  All that follows is private to pcache.c
8310   ** and should not be accessed by other modules.
8311   */
8312   i16 nRef;                      /* Number of users of this page */
8313   PCache *pCache;                /* Cache that owns this page */
8314
8315   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8316   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8317 };
8318
8319 /* Bit values for PgHdr.flags */
8320 #define PGHDR_DIRTY             0x002  /* Page has changed */
8321 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8322                                        ** writing this page to the database */
8323 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8324 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8325 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8326
8327 /* Initialize and shutdown the page cache subsystem */
8328 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8329 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8330
8331 /* Page cache buffer management:
8332 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8333 */
8334 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8335
8336 /* Create a new pager cache.
8337 ** Under memory stress, invoke xStress to try to make pages clean.
8338 ** Only clean and unpinned pages can be reclaimed.
8339 */
8340 SQLITE_PRIVATE void sqlite3PcacheOpen(
8341   int szPage,                    /* Size of every page */
8342   int szExtra,                   /* Extra space associated with each page */
8343   int bPurgeable,                /* True if pages are on backing store */
8344   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8345   void *pStress,                 /* Argument to xStress */
8346   PCache *pToInit                /* Preallocated space for the PCache */
8347 );
8348
8349 /* Modify the page-size after the cache has been created. */
8350 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8351
8352 /* Return the size in bytes of a PCache object.  Used to preallocate
8353 ** storage space.
8354 */
8355 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8356
8357 /* One release per successful fetch.  Page is pinned until released.
8358 ** Reference counted. 
8359 */
8360 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8361 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8362
8363 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8364 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8365 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8366 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8367
8368 /* Change a page number.  Used by incr-vacuum. */
8369 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8370
8371 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8372 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8373
8374 /* Get a list of all dirty pages in the cache, sorted by page number */
8375 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8376
8377 /* Reset and close the cache object */
8378 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8379
8380 /* Clear flags from pages of the page cache */
8381 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8382
8383 /* Discard the contents of the cache */
8384 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8385
8386 /* Return the total number of outstanding page references */
8387 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8388
8389 /* Increment the reference count of an existing page */
8390 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8391
8392 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8393
8394 /* Return the total number of pages stored in the cache */
8395 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8396
8397 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8398 /* Iterate through all dirty pages currently stored in the cache. This
8399 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
8400 ** library is built.
8401 */
8402 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8403 #endif
8404
8405 /* Set and get the suggested cache-size for the specified pager-cache.
8406 **
8407 ** If no global maximum is configured, then the system attempts to limit
8408 ** the total number of pages cached by purgeable pager-caches to the sum
8409 ** of the suggested cache-sizes.
8410 */
8411 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8412 #ifdef SQLITE_TEST
8413 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8414 #endif
8415
8416 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8417 /* Try to return memory used by the pcache module to the main memory heap */
8418 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8419 #endif
8420
8421 #ifdef SQLITE_TEST
8422 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8423 #endif
8424
8425 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8426
8427 #endif /* _PCACHE_H_ */
8428
8429 /************** End of pcache.h **********************************************/
8430 /************** Continuing where we left off in sqliteInt.h ******************/
8431
8432 /************** Include os.h in the middle of sqliteInt.h ********************/
8433 /************** Begin file os.h **********************************************/
8434 /*
8435 ** 2001 September 16
8436 **
8437 ** The author disclaims copyright to this source code.  In place of
8438 ** a legal notice, here is a blessing:
8439 **
8440 **    May you do good and not evil.
8441 **    May you find forgiveness for yourself and forgive others.
8442 **    May you share freely, never taking more than you give.
8443 **
8444 ******************************************************************************
8445 **
8446 ** This header file (together with is companion C source-code file
8447 ** "os.c") attempt to abstract the underlying operating system so that
8448 ** the SQLite library will work on both POSIX and windows systems.
8449 **
8450 ** This header file is #include-ed by sqliteInt.h and thus ends up
8451 ** being included by every source file.
8452 */
8453 #ifndef _SQLITE_OS_H_
8454 #define _SQLITE_OS_H_
8455
8456 /*
8457 ** Figure out if we are dealing with Unix, Windows, or some other
8458 ** operating system.  After the following block of preprocess macros,
8459 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
8460 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
8461 ** three will be 0.
8462 */
8463 #if defined(SQLITE_OS_OTHER)
8464 # if SQLITE_OS_OTHER==1
8465 #   undef SQLITE_OS_UNIX
8466 #   define SQLITE_OS_UNIX 0
8467 #   undef SQLITE_OS_WIN
8468 #   define SQLITE_OS_WIN 0
8469 #   undef SQLITE_OS_OS2
8470 #   define SQLITE_OS_OS2 0
8471 # else
8472 #   undef SQLITE_OS_OTHER
8473 # endif
8474 #endif
8475 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8476 # define SQLITE_OS_OTHER 0
8477 # ifndef SQLITE_OS_WIN
8478 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8479 #     define SQLITE_OS_WIN 1
8480 #     define SQLITE_OS_UNIX 0
8481 #     define SQLITE_OS_OS2 0
8482 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8483 #     define SQLITE_OS_WIN 0
8484 #     define SQLITE_OS_UNIX 0
8485 #     define SQLITE_OS_OS2 1
8486 #   else
8487 #     define SQLITE_OS_WIN 0
8488 #     define SQLITE_OS_UNIX 1
8489 #     define SQLITE_OS_OS2 0
8490 #  endif
8491 # else
8492 #  define SQLITE_OS_UNIX 0
8493 #  define SQLITE_OS_OS2 0
8494 # endif
8495 #else
8496 # ifndef SQLITE_OS_WIN
8497 #  define SQLITE_OS_WIN 0
8498 # endif
8499 #endif
8500
8501 /*
8502 ** Determine if we are dealing with WindowsCE - which has a much
8503 ** reduced API.
8504 */
8505 #if defined(_WIN32_WCE)
8506 # define SQLITE_OS_WINCE 1
8507 #else
8508 # define SQLITE_OS_WINCE 0
8509 #endif
8510
8511
8512 /*
8513 ** Define the maximum size of a temporary filename
8514 */
8515 #if SQLITE_OS_WIN
8516 # include <windows.h>
8517 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
8518 #elif SQLITE_OS_OS2
8519 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
8520 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
8521 # endif
8522 # define INCL_DOSDATETIME
8523 # define INCL_DOSFILEMGR
8524 # define INCL_DOSERRORS
8525 # define INCL_DOSMISC
8526 # define INCL_DOSPROCESS
8527 # define INCL_DOSMODULEMGR
8528 # define INCL_DOSSEMAPHORES
8529 # include <os2.h>
8530 # include <uconv.h>
8531 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
8532 #else
8533 # define SQLITE_TEMPNAME_SIZE 200
8534 #endif
8535
8536 /* If the SET_FULLSYNC macro is not defined above, then make it
8537 ** a no-op
8538 */
8539 #ifndef SET_FULLSYNC
8540 # define SET_FULLSYNC(x,y)
8541 #endif
8542
8543 /*
8544 ** The default size of a disk sector
8545 */
8546 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
8547 # define SQLITE_DEFAULT_SECTOR_SIZE 512
8548 #endif
8549
8550 /*
8551 ** Temporary files are named starting with this prefix followed by 16 random
8552 ** alphanumeric characters, and no file extension. They are stored in the
8553 ** OS's standard temporary file directory, and are deleted prior to exit.
8554 ** If sqlite is being embedded in another program, you may wish to change the
8555 ** prefix to reflect your program's name, so that if your program exits
8556 ** prematurely, old temporary files can be easily identified. This can be done
8557 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
8558 **
8559 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
8560 ** Mcafee started using SQLite in their anti-virus product and it
8561 ** started putting files with the "sqlite" name in the c:/temp folder.
8562 ** This annoyed many windows users.  Those users would then do a 
8563 ** Google search for "sqlite", find the telephone numbers of the
8564 ** developers and call to wake them up at night and complain.
8565 ** For this reason, the default name prefix is changed to be "sqlite" 
8566 ** spelled backwards.  So the temp files are still identified, but
8567 ** anybody smart enough to figure out the code is also likely smart
8568 ** enough to know that calling the developer will not help get rid
8569 ** of the file.
8570 */
8571 #ifndef SQLITE_TEMP_FILE_PREFIX
8572 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
8573 #endif
8574
8575 /*
8576 ** The following values may be passed as the second argument to
8577 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8578 **
8579 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8580 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8581 **            any time. Other processes may hold and obtain new SHARED locks.
8582 ** PENDING:   A single process may hold a PENDING lock on a file at
8583 **            any one time. Existing SHARED locks may persist, but no new
8584 **            SHARED locks may be obtained by other processes.
8585 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8586 **
8587 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8588 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8589 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8590 ** sqlite3OsLock().
8591 */
8592 #define NO_LOCK         0
8593 #define SHARED_LOCK     1
8594 #define RESERVED_LOCK   2
8595 #define PENDING_LOCK    3
8596 #define EXCLUSIVE_LOCK  4
8597
8598 /*
8599 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8600 **
8601 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8602 ** those functions are not available.  So we use only LockFile() and
8603 ** UnlockFile().
8604 **
8605 ** LockFile() prevents not just writing but also reading by other processes.
8606 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8607 ** byte out of a specific range of bytes. The lock byte is obtained at 
8608 ** random so two separate readers can probably access the file at the 
8609 ** same time, unless they are unlucky and choose the same lock byte.
8610 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8611 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8612 ** a single byte of the file that is designated as the reserved lock byte.
8613 ** A PENDING_LOCK is obtained by locking a designated byte different from
8614 ** the RESERVED_LOCK byte.
8615 **
8616 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8617 ** which means we can use reader/writer locks.  When reader/writer locks
8618 ** are used, the lock is placed on the same range of bytes that is used
8619 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8620 ** will support two or more Win95 readers or two or more WinNT readers.
8621 ** But a single Win95 reader will lock out all WinNT readers and a single
8622 ** WinNT reader will lock out all other Win95 readers.
8623 **
8624 ** The following #defines specify the range of bytes used for locking.
8625 ** SHARED_SIZE is the number of bytes available in the pool from which
8626 ** a random byte is selected for a shared lock.  The pool of bytes for
8627 ** shared locks begins at SHARED_FIRST. 
8628 **
8629 ** The same locking strategy and
8630 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8631 ** clients on win95, winNT, and unix all talking to the same shared file
8632 ** and all locking correctly.  To do so would require that samba (or whatever
8633 ** tool is being used for file sharing) implements locks correctly between
8634 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8635 ** using the same locking range we are at least open to the possibility.
8636 **
8637 ** Locking in windows is manditory.  For this reason, we cannot store
8638 ** actual data in the bytes used for locking.  The pager never allocates
8639 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8640 ** that all locks will fit on a single page even at the minimum page size.
8641 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8642 ** is set high so that we don't have to allocate an unused page except
8643 ** for very large databases.  But one should test the page skipping logic 
8644 ** by setting PENDING_BYTE low and running the entire regression suite.
8645 **
8646 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8647 ** file format.  Depending on how it is changed, you might not notice
8648 ** the incompatibility right away, even running a full regression test.
8649 ** The default location of PENDING_BYTE is the first byte past the
8650 ** 1GB boundary.
8651 **
8652 */
8653 #ifdef SQLITE_OMIT_WSD
8654 # define PENDING_BYTE     (0x40000000)
8655 #else
8656 # define PENDING_BYTE      sqlite3PendingByte
8657 #endif
8658 #define RESERVED_BYTE     (PENDING_BYTE+1)
8659 #define SHARED_FIRST      (PENDING_BYTE+2)
8660 #define SHARED_SIZE       510
8661
8662 /*
8663 ** Wrapper around OS specific sqlite3_os_init() function.
8664 */
8665 SQLITE_PRIVATE int sqlite3OsInit(void);
8666
8667 /* 
8668 ** Functions for accessing sqlite3_file methods 
8669 */
8670 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8671 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8672 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8673 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8674 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8675 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8676 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8677 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8678 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8679 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8680 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8681 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8682 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8683 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
8684 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
8685 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
8686 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
8687
8688 /* 
8689 ** Functions for accessing sqlite3_vfs methods 
8690 */
8691 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8692 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8693 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8694 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8695 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8696 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8697 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8698 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8699 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8700 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8701 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8702 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8703 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
8704
8705 /*
8706 ** Convenience functions for opening and closing files using 
8707 ** sqlite3_malloc() to obtain space for the file-handle structure.
8708 */
8709 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8710 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8711
8712 #endif /* _SQLITE_OS_H_ */
8713
8714 /************** End of os.h **************************************************/
8715 /************** Continuing where we left off in sqliteInt.h ******************/
8716 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8717 /************** Begin file mutex.h *******************************************/
8718 /*
8719 ** 2007 August 28
8720 **
8721 ** The author disclaims copyright to this source code.  In place of
8722 ** a legal notice, here is a blessing:
8723 **
8724 **    May you do good and not evil.
8725 **    May you find forgiveness for yourself and forgive others.
8726 **    May you share freely, never taking more than you give.
8727 **
8728 *************************************************************************
8729 **
8730 ** This file contains the common header for all mutex implementations.
8731 ** The sqliteInt.h header #includes this file so that it is available
8732 ** to all source files.  We break it out in an effort to keep the code
8733 ** better organized.
8734 **
8735 ** NOTE:  source files should *not* #include this header file directly.
8736 ** Source files should #include the sqliteInt.h file and let that file
8737 ** include this one indirectly.
8738 */
8739
8740
8741 /*
8742 ** Figure out what version of the code to use.  The choices are
8743 **
8744 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8745 **                             mutexes implemention cannot be overridden
8746 **                             at start-time.
8747 **
8748 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8749 **                             mutual exclusion is provided.  But this
8750 **                             implementation can be overridden at
8751 **                             start-time.
8752 **
8753 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8754 **
8755 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8756 **
8757 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8758 */
8759 #if !SQLITE_THREADSAFE
8760 # define SQLITE_MUTEX_OMIT
8761 #endif
8762 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8763 #  if SQLITE_OS_UNIX
8764 #    define SQLITE_MUTEX_PTHREADS
8765 #  elif SQLITE_OS_WIN
8766 #    define SQLITE_MUTEX_W32
8767 #  elif SQLITE_OS_OS2
8768 #    define SQLITE_MUTEX_OS2
8769 #  else
8770 #    define SQLITE_MUTEX_NOOP
8771 #  endif
8772 #endif
8773
8774 #ifdef SQLITE_MUTEX_OMIT
8775 /*
8776 ** If this is a no-op implementation, implement everything as macros.
8777 */
8778 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8779 #define sqlite3_mutex_free(X)
8780 #define sqlite3_mutex_enter(X)
8781 #define sqlite3_mutex_try(X)      SQLITE_OK
8782 #define sqlite3_mutex_leave(X)
8783 #define sqlite3_mutex_held(X)     ((void)(X),1)
8784 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
8785 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8786 #define sqlite3MutexInit()        SQLITE_OK
8787 #define sqlite3MutexEnd()
8788 #endif /* defined(SQLITE_MUTEX_OMIT) */
8789
8790 /************** End of mutex.h ***********************************************/
8791 /************** Continuing where we left off in sqliteInt.h ******************/
8792
8793
8794 /*
8795 ** Each database file to be accessed by the system is an instance
8796 ** of the following structure.  There are normally two of these structures
8797 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8798 ** aDb[1] is the database file used to hold temporary tables.  Additional
8799 ** databases may be attached.
8800 */
8801 struct Db {
8802   char *zName;         /* Name of this database */
8803   Btree *pBt;          /* The B*Tree structure for this database file */
8804   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8805   u8 safety_level;     /* How aggressive at syncing data to disk */
8806   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8807 };
8808
8809 /*
8810 ** An instance of the following structure stores a database schema.
8811 */
8812 struct Schema {
8813   int schema_cookie;   /* Database schema version number for this file */
8814   Hash tblHash;        /* All tables indexed by name */
8815   Hash idxHash;        /* All (named) indices indexed by name */
8816   Hash trigHash;       /* All triggers indexed by name */
8817   Hash fkeyHash;       /* All foreign keys by referenced table name */
8818   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8819   u8 file_format;      /* Schema format version for this file */
8820   u8 enc;              /* Text encoding used by this database */
8821   u16 flags;           /* Flags associated with this schema */
8822   int cache_size;      /* Number of pages to use in the cache */
8823 };
8824
8825 /*
8826 ** These macros can be used to test, set, or clear bits in the 
8827 ** Db.pSchema->flags field.
8828 */
8829 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8830 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8831 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8832 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8833
8834 /*
8835 ** Allowed values for the DB.pSchema->flags field.
8836 **
8837 ** The DB_SchemaLoaded flag is set after the database schema has been
8838 ** read into internal hash tables.
8839 **
8840 ** DB_UnresetViews means that one or more views have column names that
8841 ** have been filled out.  If the schema changes, these column names might
8842 ** changes and so the view will need to be reset.
8843 */
8844 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8845 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
8846 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8847
8848 /*
8849 ** The number of different kinds of things that can be limited
8850 ** using the sqlite3_limit() interface.
8851 */
8852 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8853
8854 /*
8855 ** Lookaside malloc is a set of fixed-size buffers that can be used
8856 ** to satisfy small transient memory allocation requests for objects
8857 ** associated with a particular database connection.  The use of
8858 ** lookaside malloc provides a significant performance enhancement
8859 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
8860 ** SQL statements.
8861 **
8862 ** The Lookaside structure holds configuration information about the
8863 ** lookaside malloc subsystem.  Each available memory allocation in
8864 ** the lookaside subsystem is stored on a linked list of LookasideSlot
8865 ** objects.
8866 **
8867 ** Lookaside allocations are only allowed for objects that are associated
8868 ** with a particular database connection.  Hence, schema information cannot
8869 ** be stored in lookaside because in shared cache mode the schema information
8870 ** is shared by multiple database connections.  Therefore, while parsing
8871 ** schema information, the Lookaside.bEnabled flag is cleared so that
8872 ** lookaside allocations are not used to construct the schema objects.
8873 */
8874 struct Lookaside {
8875   u16 sz;                 /* Size of each buffer in bytes */
8876   u8 bEnabled;            /* False to disable new lookaside allocations */
8877   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8878   int nOut;               /* Number of buffers currently checked out */
8879   int mxOut;              /* Highwater mark for nOut */
8880   LookasideSlot *pFree;   /* List of available buffers */
8881   void *pStart;           /* First byte of available memory space */
8882   void *pEnd;             /* First byte past end of available space */
8883 };
8884 struct LookasideSlot {
8885   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8886 };
8887
8888 /*
8889 ** A hash table for function definitions.
8890 **
8891 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8892 ** Collisions are on the FuncDef.pHash chain.
8893 */
8894 struct FuncDefHash {
8895   FuncDef *a[23];       /* Hash table for functions */
8896 };
8897
8898 /*
8899 ** Each database connection is an instance of the following structure.
8900 **
8901 ** The sqlite.lastRowid records the last insert rowid generated by an
8902 ** insert statement.  Inserts on views do not affect its value.  Each
8903 ** trigger has its own context, so that lastRowid can be updated inside
8904 ** triggers as usual.  The previous value will be restored once the trigger
8905 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
8906 ** longer (since after version 2.8.12) reset to -1.
8907 **
8908 ** The sqlite.nChange does not count changes within triggers and keeps no
8909 ** context.  It is reset at start of sqlite3_exec.
8910 ** The sqlite.lsChange represents the number of changes made by the last
8911 ** insert, update, or delete statement.  It remains constant throughout the
8912 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
8913 ** context stack just like lastRowid so that the count of changes
8914 ** within a trigger is not seen outside the trigger.  Changes to views do not
8915 ** affect the value of lsChange.
8916 ** The sqlite.csChange keeps track of the number of current changes (since
8917 ** the last statement) and is used to update sqlite_lsChange.
8918 **
8919 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8920 ** store the most recent error code and, if applicable, string. The
8921 ** internal function sqlite3Error() is used to set these variables
8922 ** consistently.
8923 */
8924 struct sqlite3 {
8925   sqlite3_vfs *pVfs;            /* OS Interface */
8926   int nDb;                      /* Number of backends currently in use */
8927   Db *aDb;                      /* All backends */
8928   int flags;                    /* Miscellaneous flags. See below */
8929   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8930   int errCode;                  /* Most recent error code (SQLITE_*) */
8931   int errMask;                  /* & result codes with this before returning */
8932   u8 autoCommit;                /* The auto-commit flag. */
8933   u8 temp_store;                /* 1: file 2: memory 0: default */
8934   u8 mallocFailed;              /* True if we have seen a malloc failure */
8935   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8936   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8937   u8 suppressErr;               /* Do not issue error messages if true */
8938   int nextPagesize;             /* Pagesize after VACUUM if >0 */
8939   int nTable;                   /* Number of tables in the database */
8940   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8941   i64 lastRowid;                /* ROWID of most recent insert (see above) */
8942   u32 magic;                    /* Magic number for detect library misuse */
8943   int nChange;                  /* Value returned by sqlite3_changes() */
8944   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8945   sqlite3_mutex *mutex;         /* Connection mutex */
8946   int aLimit[SQLITE_N_LIMIT];   /* Limits */
8947   struct sqlite3InitInfo {      /* Information used during initialization */
8948     int iDb;                    /* When back is being initialized */
8949     int newTnum;                /* Rootpage of table being initialized */
8950     u8 busy;                    /* TRUE if currently initializing */
8951     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8952   } init;
8953   int nExtension;               /* Number of loaded extensions */
8954   void **aExtension;            /* Array of shared library handles */
8955   struct Vdbe *pVdbe;           /* List of active virtual machines */
8956   int activeVdbeCnt;            /* Number of VDBEs currently executing */
8957   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8958   void (*xTrace)(void*,const char*);        /* Trace function */
8959   void *pTraceArg;                          /* Argument to the trace function */
8960   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8961   void *pProfileArg;                        /* Argument to profile function */
8962   void *pCommitArg;                 /* Argument to xCommitCallback() */   
8963   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8964   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
8965   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8966   void *pUpdateArg;
8967   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8968 #ifndef SQLITE_OMIT_WAL
8969   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
8970   void *pWalArg;
8971 #endif
8972   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8973   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8974   void *pCollNeededArg;
8975   sqlite3_value *pErr;          /* Most recent error message */
8976   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8977   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8978   union {
8979     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8980     double notUsed1;            /* Spacer */
8981   } u1;
8982   Lookaside lookaside;          /* Lookaside malloc configuration */
8983 #ifndef SQLITE_OMIT_AUTHORIZATION
8984   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8985                                 /* Access authorization function */
8986   void *pAuthArg;               /* 1st argument to the access auth function */
8987 #endif
8988 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8989   int (*xProgress)(void *);     /* The progress callback */
8990   void *pProgressArg;           /* Argument to the progress callback */
8991   int nProgressOps;             /* Number of opcodes for progress callback */
8992 #endif
8993 #ifndef SQLITE_OMIT_VIRTUALTABLE
8994   Hash aModule;                 /* populated by sqlite3_create_module() */
8995   Table *pVTab;                 /* vtab with active Connect/Create method */
8996   VTable **aVTrans;             /* Virtual tables with open transactions */
8997   int nVTrans;                  /* Allocated size of aVTrans */
8998   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8999 #endif
9000   FuncDefHash aFunc;            /* Hash table of connection functions */
9001   Hash aCollSeq;                /* All collating sequences */
9002   BusyHandler busyHandler;      /* Busy callback */
9003   int busyTimeout;              /* Busy handler timeout, in msec */
9004   Db aDbStatic[2];              /* Static space for the 2 default backends */
9005   Savepoint *pSavepoint;        /* List of active savepoints */
9006   int nSavepoint;               /* Number of non-transaction savepoints */
9007   int nStatement;               /* Number of nested statement-transactions  */
9008   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9009   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9010   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9011
9012 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9013   /* The following variables are all protected by the STATIC_MASTER 
9014   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
9015   **
9016   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9017   ** unlock so that it can proceed.
9018   **
9019   ** When X.pBlockingConnection==Y, that means that something that X tried
9020   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9021   ** held by Y.
9022   */
9023   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9024   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9025   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9026   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9027   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9028 #endif
9029 };
9030
9031 /*
9032 ** A macro to discover the encoding of a database.
9033 */
9034 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9035
9036 /*
9037 ** Possible values for the sqlite3.flags.
9038 */
9039 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9040 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9041 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9042 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9043 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9044                                           /*   DELETE, or UPDATE and return */
9045                                           /*   the count using a callback. */
9046 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9047                                           /*   result set is empty */
9048 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9049 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9050 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9051 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when 
9052                                           ** accessing read-only databases */
9053 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9054 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9055 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9056 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9057 #define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9058 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9059 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9060 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9061 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9062 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9063 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9064 #define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9065
9066 /*
9067 ** Bits of the sqlite3.flags field that are used by the
9068 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9069 ** These must be the low-order bits of the flags field.
9070 */
9071 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9072 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9073 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9074 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9075 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
9076 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9077 #define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9078 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9079
9080 /*
9081 ** Possible values for the sqlite.magic field.
9082 ** The numbers are obtained at random and have no special meaning, other
9083 ** than being distinct from one another.
9084 */
9085 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9086 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9087 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9088 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9089 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9090
9091 /*
9092 ** Each SQL function is defined by an instance of the following
9093 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9094 ** hash table.  When multiple functions have the same name, the hash table
9095 ** points to a linked list of these structures.
9096 */
9097 struct FuncDef {
9098   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9099   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9100   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9101   void *pUserData;     /* User data parameter */
9102   FuncDef *pNext;      /* Next function with same name */
9103   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9104   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9105   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9106   char *zName;         /* SQL name of the function. */
9107   FuncDef *pHash;      /* Next with a different name but the same hash */
9108   FuncDestructor *pDestructor;   /* Reference counted destructor function */
9109 };
9110
9111 /*
9112 ** This structure encapsulates a user-function destructor callback (as
9113 ** configured using create_function_v2()) and a reference counter. When
9114 ** create_function_v2() is called to create a function with a destructor,
9115 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
9116 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9117 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9118 ** member of each of the new FuncDef objects is set to point to the allocated
9119 ** FuncDestructor.
9120 **
9121 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9122 ** count on this object is decremented. When it reaches 0, the destructor
9123 ** is invoked and the FuncDestructor structure freed.
9124 */
9125 struct FuncDestructor {
9126   int nRef;
9127   void (*xDestroy)(void *);
9128   void *pUserData;
9129 };
9130
9131 /*
9132 ** Possible values for FuncDef.flags
9133 */
9134 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9135 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9136 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9137 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9138 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9139 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9140 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9141
9142 /*
9143 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9144 ** used to create the initializers for the FuncDef structures.
9145 **
9146 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9147 **     Used to create a scalar function definition of a function zName 
9148 **     implemented by C function xFunc that accepts nArg arguments. The
9149 **     value passed as iArg is cast to a (void*) and made available
9150 **     as the user-data (sqlite3_user_data()) for the function. If 
9151 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9152 **
9153 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9154 **     Used to create an aggregate function definition implemented by
9155 **     the C functions xStep and xFinal. The first four parameters
9156 **     are interpreted in the same way as the first 4 parameters to
9157 **     FUNCTION().
9158 **
9159 **   LIKEFUNC(zName, nArg, pArg, flags)
9160 **     Used to create a scalar function definition of a function zName 
9161 **     that accepts nArg arguments and is implemented by a call to C 
9162 **     function likeFunc. Argument pArg is cast to a (void *) and made
9163 **     available as the function user-data (sqlite3_user_data()). The
9164 **     FuncDef.flags variable is set to the value passed as the flags
9165 **     parameter.
9166 */
9167 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9168   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9169    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9170 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9171   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9172    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9173 #define LIKEFUNC(zName, nArg, arg, flags) \
9174   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9175 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9176   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9177    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9178
9179 /*
9180 ** All current savepoints are stored in a linked list starting at
9181 ** sqlite3.pSavepoint. The first element in the list is the most recently
9182 ** opened savepoint. Savepoints are added to the list by the vdbe
9183 ** OP_Savepoint instruction.
9184 */
9185 struct Savepoint {
9186   char *zName;                        /* Savepoint name (nul-terminated) */
9187   i64 nDeferredCons;                  /* Number of deferred fk violations */
9188   Savepoint *pNext;                   /* Parent savepoint (if any) */
9189 };
9190
9191 /*
9192 ** The following are used as the second parameter to sqlite3Savepoint(),
9193 ** and as the P1 argument to the OP_Savepoint instruction.
9194 */
9195 #define SAVEPOINT_BEGIN      0
9196 #define SAVEPOINT_RELEASE    1
9197 #define SAVEPOINT_ROLLBACK   2
9198
9199
9200 /*
9201 ** Each SQLite module (virtual table definition) is defined by an
9202 ** instance of the following structure, stored in the sqlite3.aModule
9203 ** hash table.
9204 */
9205 struct Module {
9206   const sqlite3_module *pModule;       /* Callback pointers */
9207   const char *zName;                   /* Name passed to create_module() */
9208   void *pAux;                          /* pAux passed to create_module() */
9209   void (*xDestroy)(void *);            /* Module destructor function */
9210 };
9211
9212 /*
9213 ** information about each column of an SQL table is held in an instance
9214 ** of this structure.
9215 */
9216 struct Column {
9217   char *zName;     /* Name of this column */
9218   Expr *pDflt;     /* Default value of this column */
9219   char *zDflt;     /* Original text of the default value */
9220   char *zType;     /* Data type for this column */
9221   char *zColl;     /* Collating sequence.  If NULL, use the default */
9222   u8 notNull;      /* True if there is a NOT NULL constraint */
9223   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9224   char affinity;   /* One of the SQLITE_AFF_... values */
9225 #ifndef SQLITE_OMIT_VIRTUALTABLE
9226   u8 isHidden;     /* True if this column is 'hidden' */
9227 #endif
9228 };
9229
9230 /*
9231 ** A "Collating Sequence" is defined by an instance of the following
9232 ** structure. Conceptually, a collating sequence consists of a name and
9233 ** a comparison routine that defines the order of that sequence.
9234 **
9235 ** There may two separate implementations of the collation function, one
9236 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9237 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9238 ** native byte order. When a collation sequence is invoked, SQLite selects
9239 ** the version that will require the least expensive encoding
9240 ** translations, if any.
9241 **
9242 ** The CollSeq.pUser member variable is an extra parameter that passed in
9243 ** as the first argument to the UTF-8 comparison function, xCmp.
9244 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9245 ** xCmp16.
9246 **
9247 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9248 ** collating sequence is undefined.  Indices built on an undefined
9249 ** collating sequence may not be read or written.
9250 */
9251 struct CollSeq {
9252   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9253   u8 enc;               /* Text encoding handled by xCmp() */
9254   u8 type;              /* One of the SQLITE_COLL_... values below */
9255   void *pUser;          /* First argument to xCmp() */
9256   int (*xCmp)(void*,int, const void*, int, const void*);
9257   void (*xDel)(void*);  /* Destructor for pUser */
9258 };
9259
9260 /*
9261 ** Allowed values of CollSeq.type:
9262 */
9263 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9264 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9265 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9266 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9267
9268 /*
9269 ** A sort order can be either ASC or DESC.
9270 */
9271 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9272 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9273
9274 /*
9275 ** Column affinity types.
9276 **
9277 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9278 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9279 ** the speed a little by numbering the values consecutively.  
9280 **
9281 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9282 ** when multiple affinity types are concatenated into a string and
9283 ** used as the P4 operand, they will be more readable.
9284 **
9285 ** Note also that the numeric types are grouped together so that testing
9286 ** for a numeric type is a single comparison.
9287 */
9288 #define SQLITE_AFF_TEXT     'a'
9289 #define SQLITE_AFF_NONE     'b'
9290 #define SQLITE_AFF_NUMERIC  'c'
9291 #define SQLITE_AFF_INTEGER  'd'
9292 #define SQLITE_AFF_REAL     'e'
9293
9294 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9295
9296 /*
9297 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9298 ** affinity value. 
9299 */
9300 #define SQLITE_AFF_MASK     0x67
9301
9302 /*
9303 ** Additional bit values that can be ORed with an affinity without
9304 ** changing the affinity.
9305 */
9306 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9307 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9308 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
9309
9310 /*
9311 ** An object of this type is created for each virtual table present in
9312 ** the database schema. 
9313 **
9314 ** If the database schema is shared, then there is one instance of this
9315 ** structure for each database connection (sqlite3*) that uses the shared
9316 ** schema. This is because each database connection requires its own unique
9317 ** instance of the sqlite3_vtab* handle used to access the virtual table 
9318 ** implementation. sqlite3_vtab* handles can not be shared between 
9319 ** database connections, even when the rest of the in-memory database 
9320 ** schema is shared, as the implementation often stores the database
9321 ** connection handle passed to it via the xConnect() or xCreate() method
9322 ** during initialization internally. This database connection handle may
9323 ** then used by the virtual table implementation to access real tables 
9324 ** within the database. So that they appear as part of the callers 
9325 ** transaction, these accesses need to be made via the same database 
9326 ** connection as that used to execute SQL operations on the virtual table.
9327 **
9328 ** All VTable objects that correspond to a single table in a shared
9329 ** database schema are initially stored in a linked-list pointed to by
9330 ** the Table.pVTable member variable of the corresponding Table object.
9331 ** When an sqlite3_prepare() operation is required to access the virtual
9332 ** table, it searches the list for the VTable that corresponds to the
9333 ** database connection doing the preparing so as to use the correct
9334 ** sqlite3_vtab* handle in the compiled query.
9335 **
9336 ** When an in-memory Table object is deleted (for example when the
9337 ** schema is being reloaded for some reason), the VTable objects are not 
9338 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
9339 ** immediately. Instead, they are moved from the Table.pVTable list to
9340 ** another linked list headed by the sqlite3.pDisconnect member of the
9341 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
9342 ** next time a statement is prepared using said sqlite3*. This is done
9343 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9344 ** Refer to comments above function sqlite3VtabUnlockList() for an
9345 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9346 ** list without holding the corresponding sqlite3.mutex mutex.
9347 **
9348 ** The memory for objects of this type is always allocated by 
9349 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
9350 ** the first argument.
9351 */
9352 struct VTable {
9353   sqlite3 *db;              /* Database connection associated with this table */
9354   Module *pMod;             /* Pointer to module implementation */
9355   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
9356   int nRef;                 /* Number of pointers to this structure */
9357   VTable *pNext;            /* Next in linked list (see above) */
9358 };
9359
9360 /*
9361 ** Each SQL table is represented in memory by an instance of the
9362 ** following structure.
9363 **
9364 ** Table.zName is the name of the table.  The case of the original
9365 ** CREATE TABLE statement is stored, but case is not significant for
9366 ** comparisons.
9367 **
9368 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9369 ** pointer to an array of Column structures, one for each column.
9370 **
9371 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9372 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9373 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9374 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9375 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9376 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9377 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9378 **
9379 ** Table.tnum is the page number for the root BTree page of the table in the
9380 ** database file.  If Table.iDb is the index of the database table backend
9381 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9382 ** holds temporary tables and indices.  If TF_Ephemeral is set
9383 ** then the table is stored in a file that is automatically deleted
9384 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
9385 ** refers VDBE cursor number that holds the table open, not to the root
9386 ** page number.  Transient tables are used to hold the results of a
9387 ** sub-query that appears instead of a real table name in the FROM clause 
9388 ** of a SELECT statement.
9389 */
9390 struct Table {
9391   char *zName;         /* Name of the table or view */
9392   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9393   int nCol;            /* Number of columns in this table */
9394   Column *aCol;        /* Information about each column */
9395   Index *pIndex;       /* List of SQL indexes on this table. */
9396   int tnum;            /* Root BTree node for this table (see note above) */
9397   unsigned nRowEst;    /* Estimated rows in table - from sqlite_stat1 table */
9398   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9399   u16 nRef;            /* Number of pointers to this Table */
9400   u8 tabFlags;         /* Mask of TF_* values */
9401   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9402   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9403   char *zColAff;       /* String defining the affinity of each column */
9404 #ifndef SQLITE_OMIT_CHECK
9405   Expr *pCheck;        /* The AND of all CHECK constraints */
9406 #endif
9407 #ifndef SQLITE_OMIT_ALTERTABLE
9408   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9409 #endif
9410 #ifndef SQLITE_OMIT_VIRTUALTABLE
9411   VTable *pVTable;     /* List of VTable objects. */
9412   int nModuleArg;      /* Number of arguments to the module */
9413   char **azModuleArg;  /* Text of all module args. [0] is module name */
9414 #endif
9415   Trigger *pTrigger;   /* List of triggers stored in pSchema */
9416   Schema *pSchema;     /* Schema that contains this table */
9417   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9418 };
9419
9420 /*
9421 ** Allowed values for Tabe.tabFlags.
9422 */
9423 #define TF_Readonly        0x01    /* Read-only system table */
9424 #define TF_Ephemeral       0x02    /* An ephemeral table */
9425 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9426 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9427 #define TF_Virtual         0x10    /* Is a virtual table */
9428 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9429
9430
9431
9432 /*
9433 ** Test to see whether or not a table is a virtual table.  This is
9434 ** done as a macro so that it will be optimized out when virtual
9435 ** table support is omitted from the build.
9436 */
9437 #ifndef SQLITE_OMIT_VIRTUALTABLE
9438 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9439 #  define IsHiddenColumn(X) ((X)->isHidden)
9440 #else
9441 #  define IsVirtual(X)      0
9442 #  define IsHiddenColumn(X) 0
9443 #endif
9444
9445 /*
9446 ** Each foreign key constraint is an instance of the following structure.
9447 **
9448 ** A foreign key is associated with two tables.  The "from" table is
9449 ** the table that contains the REFERENCES clause that creates the foreign
9450 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9451 ** Consider this example:
9452 **
9453 **     CREATE TABLE ex1(
9454 **       a INTEGER PRIMARY KEY,
9455 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9456 **     );
9457 **
9458 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9459 **
9460 ** Each REFERENCES clause generates an instance of the following structure
9461 ** which is attached to the from-table.  The to-table need not exist when
9462 ** the from-table is created.  The existence of the to-table is not checked.
9463 */
9464 struct FKey {
9465   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9466   FKey *pNextFrom;  /* Next foreign key in pFrom */
9467   char *zTo;        /* Name of table that the key points to (aka: Parent) */
9468   FKey *pNextTo;    /* Next foreign key on table named zTo */
9469   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9470   int nCol;         /* Number of columns in this key */
9471   /* EV: R-30323-21917 */
9472   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
9473   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
9474   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
9475   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
9476     int iFrom;         /* Index of column in pFrom */
9477     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
9478   } aCol[1];        /* One entry for each of nCol column s */
9479 };
9480
9481 /*
9482 ** SQLite supports many different ways to resolve a constraint
9483 ** error.  ROLLBACK processing means that a constraint violation
9484 ** causes the operation in process to fail and for the current transaction
9485 ** to be rolled back.  ABORT processing means the operation in process
9486 ** fails and any prior changes from that one operation are backed out,
9487 ** but the transaction is not rolled back.  FAIL processing means that
9488 ** the operation in progress stops and returns an error code.  But prior
9489 ** changes due to the same operation are not backed out and no rollback
9490 ** occurs.  IGNORE means that the particular row that caused the constraint
9491 ** error is not inserted or updated.  Processing continues and no error
9492 ** is returned.  REPLACE means that preexisting database rows that caused
9493 ** a UNIQUE constraint violation are removed so that the new insert or
9494 ** update can proceed.  Processing continues and no error is reported.
9495 **
9496 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
9497 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
9498 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
9499 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
9500 ** referenced table row is propagated into the row that holds the
9501 ** foreign key.
9502 ** 
9503 ** The following symbolic values are used to record which type
9504 ** of action to take.
9505 */
9506 #define OE_None     0   /* There is no constraint to check */
9507 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
9508 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
9509 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
9510 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
9511 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
9512
9513 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
9514 #define OE_SetNull  7   /* Set the foreign key value to NULL */
9515 #define OE_SetDflt  8   /* Set the foreign key value to its default */
9516 #define OE_Cascade  9   /* Cascade the changes */
9517
9518 #define OE_Default  99  /* Do whatever the default action is */
9519
9520
9521 /*
9522 ** An instance of the following structure is passed as the first
9523 ** argument to sqlite3VdbeKeyCompare and is used to control the 
9524 ** comparison of the two index keys.
9525 */
9526 struct KeyInfo {
9527   sqlite3 *db;        /* The database connection */
9528   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
9529   u16 nField;         /* Number of entries in aColl[] */
9530   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
9531   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
9532 };
9533
9534 /*
9535 ** An instance of the following structure holds information about a
9536 ** single index record that has already been parsed out into individual
9537 ** values.
9538 **
9539 ** A record is an object that contains one or more fields of data.
9540 ** Records are used to store the content of a table row and to store
9541 ** the key of an index.  A blob encoding of a record is created by
9542 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
9543 ** OP_Column opcode.
9544 **
9545 ** This structure holds a record that has already been disassembled
9546 ** into its constituent fields.
9547 */
9548 struct UnpackedRecord {
9549   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
9550   u16 nField;         /* Number of entries in apMem[] */
9551   u16 flags;          /* Boolean settings.  UNPACKED_... below */
9552   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
9553   Mem *aMem;          /* Values */
9554 };
9555
9556 /*
9557 ** Allowed values of UnpackedRecord.flags
9558 */
9559 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
9560 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
9561 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
9562 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
9563 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
9564 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
9565
9566 /*
9567 ** Each SQL index is represented in memory by an
9568 ** instance of the following structure.
9569 **
9570 ** The columns of the table that are to be indexed are described
9571 ** by the aiColumn[] field of this structure.  For example, suppose
9572 ** we have the following table and index:
9573 **
9574 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
9575 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
9576 **
9577 ** In the Table structure describing Ex1, nCol==3 because there are
9578 ** three columns in the table.  In the Index structure describing
9579 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
9580 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
9581 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
9582 ** The second column to be indexed (c1) has an index of 0 in
9583 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
9584 **
9585 ** The Index.onError field determines whether or not the indexed columns
9586 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
9587 ** it means this is not a unique index.  Otherwise it is a unique index
9588 ** and the value of Index.onError indicate the which conflict resolution 
9589 ** algorithm to employ whenever an attempt is made to insert a non-unique
9590 ** element.
9591 */
9592 struct Index {
9593   char *zName;     /* Name of this index */
9594   int nColumn;     /* Number of columns in the table used by this index */
9595   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
9596   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
9597   Table *pTable;   /* The SQL table being indexed */
9598   int tnum;        /* Page containing root of this index in database file */
9599   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
9600   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
9601   char *zColAff;   /* String defining the affinity of each column */
9602   Index *pNext;    /* The next index associated with the same table */
9603   Schema *pSchema; /* Schema containing this index */
9604   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9605   char **azColl;   /* Array of collation sequence names for index */
9606   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9607 };
9608
9609 /*
9610 ** Each sample stored in the sqlite_stat2 table is represented in memory 
9611 ** using a structure of this type.
9612 */
9613 struct IndexSample {
9614   union {
9615     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9616     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9617   } u;
9618   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9619   u8 nByte;         /* Size in byte of text or blob. */
9620 };
9621
9622 /*
9623 ** Each token coming out of the lexer is an instance of
9624 ** this structure.  Tokens are also used as part of an expression.
9625 **
9626 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9627 ** may contain random values.  Do not make any assumptions about Token.dyn
9628 ** and Token.n when Token.z==0.
9629 */
9630 struct Token {
9631   const char *z;     /* Text of the token.  Not NULL-terminated! */
9632   unsigned int n;    /* Number of characters in this token */
9633 };
9634
9635 /*
9636 ** An instance of this structure contains information needed to generate
9637 ** code for a SELECT that contains aggregate functions.
9638 **
9639 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9640 ** pointer to this structure.  The Expr.iColumn field is the index in
9641 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9642 ** code for that node.
9643 **
9644 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9645 ** original Select structure that describes the SELECT statement.  These
9646 ** fields do not need to be freed when deallocating the AggInfo structure.
9647 */
9648 struct AggInfo {
9649   u8 directMode;          /* Direct rendering mode means take data directly
9650                           ** from source tables rather than from accumulators */
9651   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9652                           ** than the source table */
9653   int sortingIdx;         /* Cursor number of the sorting index */
9654   ExprList *pGroupBy;     /* The group by clause */
9655   int nSortingColumn;     /* Number of columns in the sorting index */
9656   struct AggInfo_col {    /* For each column used in source tables */
9657     Table *pTab;             /* Source table */
9658     int iTable;              /* Cursor number of the source table */
9659     int iColumn;             /* Column number within the source table */
9660     int iSorterColumn;       /* Column number in the sorting index */
9661     int iMem;                /* Memory location that acts as accumulator */
9662     Expr *pExpr;             /* The original expression */
9663   } *aCol;
9664   int nColumn;            /* Number of used entries in aCol[] */
9665   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9666   int nAccumulator;       /* Number of columns that show through to the output.
9667                           ** Additional columns are used only as parameters to
9668                           ** aggregate functions */
9669   struct AggInfo_func {   /* For each aggregate function */
9670     Expr *pExpr;             /* Expression encoding the function */
9671     FuncDef *pFunc;          /* The aggregate function implementation */
9672     int iMem;                /* Memory location that acts as accumulator */
9673     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9674   } *aFunc;
9675   int nFunc;              /* Number of entries in aFunc[] */
9676   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9677 };
9678
9679 /*
9680 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9681 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9682 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
9683 ** it uses less memory in the Expr object, which is a big memory user
9684 ** in systems with lots of prepared statements.  And few applications
9685 ** need more than about 10 or 20 variables.  But some extreme users want
9686 ** to have prepared statements with over 32767 variables, and for them
9687 ** the option is available (at compile-time).
9688 */
9689 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9690 typedef i16 ynVar;
9691 #else
9692 typedef int ynVar;
9693 #endif
9694
9695 /*
9696 ** Each node of an expression in the parse tree is an instance
9697 ** of this structure.
9698 **
9699 ** Expr.op is the opcode. The integer parser token codes are reused
9700 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9701 ** code representing the ">=" operator. This same integer code is reused
9702 ** to represent the greater-than-or-equal-to operator in the expression
9703 ** tree.
9704 **
9705 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
9706 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9707 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
9708 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9709 ** then Expr.token contains the name of the function.
9710 **
9711 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9712 ** binary operator. Either or both may be NULL.
9713 **
9714 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9715 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9716 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9717 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9718 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
9719 ** valid.
9720 **
9721 ** An expression of the form ID or ID.ID refers to a column in a table.
9722 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9723 ** the integer cursor number of a VDBE cursor pointing to that table and
9724 ** Expr.iColumn is the column number for the specific column.  If the
9725 ** expression is used as a result in an aggregate SELECT, then the
9726 ** value is also stored in the Expr.iAgg column in the aggregate so that
9727 ** it can be accessed after all aggregates are computed.
9728 **
9729 ** If the expression is an unbound variable marker (a question mark 
9730 ** character '?' in the original SQL) then the Expr.iTable holds the index 
9731 ** number for that variable.
9732 **
9733 ** If the expression is a subquery then Expr.iColumn holds an integer
9734 ** register number containing the result of the subquery.  If the
9735 ** subquery gives a constant result, then iTable is -1.  If the subquery
9736 ** gives a different answer at different times during statement processing
9737 ** then iTable is the address of a subroutine that computes the subquery.
9738 **
9739 ** If the Expr is of type OP_Column, and the table it is selecting from
9740 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9741 ** corresponding table definition.
9742 **
9743 ** ALLOCATION NOTES:
9744 **
9745 ** Expr objects can use a lot of memory space in database schema.  To
9746 ** help reduce memory requirements, sometimes an Expr object will be
9747 ** truncated.  And to reduce the number of memory allocations, sometimes
9748 ** two or more Expr objects will be stored in a single memory allocation,
9749 ** together with Expr.zToken strings.
9750 **
9751 ** If the EP_Reduced and EP_TokenOnly flags are set when
9752 ** an Expr object is truncated.  When EP_Reduced is set, then all
9753 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9754 ** are contained within the same memory allocation.  Note, however, that
9755 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9756 ** allocated, regardless of whether or not EP_Reduced is set.
9757 */
9758 struct Expr {
9759   u8 op;                 /* Operation performed by this node */
9760   char affinity;         /* The affinity of the column or 0 if not a column */
9761   u16 flags;             /* Various flags.  EP_* See below */
9762   union {
9763     char *zToken;          /* Token value. Zero terminated and dequoted */
9764     int iValue;            /* Integer value if EP_IntValue */
9765   } u;
9766
9767   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9768   ** space is allocated for the fields below this point. An attempt to
9769   ** access them will result in a segfault or malfunction. 
9770   *********************************************************************/
9771
9772   Expr *pLeft;           /* Left subnode */
9773   Expr *pRight;          /* Right subnode */
9774   union {
9775     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9776     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9777   } x;
9778   CollSeq *pColl;        /* The collation type of the column or 0 */
9779
9780   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9781   ** space is allocated for the fields below this point. An attempt to
9782   ** access them will result in a segfault or malfunction.
9783   *********************************************************************/
9784
9785   int iTable;            /* TK_COLUMN: cursor number of table holding column
9786                          ** TK_REGISTER: register number
9787                          ** TK_TRIGGER: 1 -> new, 0 -> old */
9788   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9789                          ** TK_VARIABLE: variable number (always >= 1). */
9790   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9791   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9792   u8 flags2;             /* Second set of flags.  EP2_... */
9793   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9794   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9795   Table *pTab;           /* Table for TK_COLUMN expressions. */
9796 #if SQLITE_MAX_EXPR_DEPTH>0
9797   int nHeight;           /* Height of the tree headed by this node */
9798 #endif
9799 };
9800
9801 /*
9802 ** The following are the meanings of bits in the Expr.flags field.
9803 */
9804 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9805 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9806 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9807 #define EP_Error      0x0008  /* Expression contains one or more errors */
9808 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9809 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9810 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9811 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9812 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9813 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
9814 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9815 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9816
9817 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9818 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9819 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9820
9821 /*
9822 ** The following are the meanings of bits in the Expr.flags2 field.
9823 */
9824 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9825 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9826
9827 /*
9828 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9829 ** flag on an expression structure.  This flag is used for VV&A only.  The
9830 ** routine is implemented as a macro that only works when in debugging mode,
9831 ** so as not to burden production code.
9832 */
9833 #ifdef SQLITE_DEBUG
9834 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9835 #else
9836 # define ExprSetIrreducible(X)
9837 #endif
9838
9839 /*
9840 ** These macros can be used to test, set, or clear bits in the 
9841 ** Expr.flags field.
9842 */
9843 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9844 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9845 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9846 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9847
9848 /*
9849 ** Macros to determine the number of bytes required by a normal Expr 
9850 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
9851 ** and an Expr struct with the EP_TokenOnly flag set.
9852 */
9853 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9854 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9855 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9856
9857 /*
9858 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
9859 ** above sqlite3ExprDup() for details.
9860 */
9861 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9862
9863 /*
9864 ** A list of expressions.  Each expression may optionally have a
9865 ** name.  An expr/name combination can be used in several ways, such
9866 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9867 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9868 ** also be used as the argument to a function, in which case the a.zName
9869 ** field is not used.
9870 */
9871 struct ExprList {
9872   int nExpr;             /* Number of expressions on the list */
9873   int nAlloc;            /* Number of entries allocated below */
9874   int iECursor;          /* VDBE Cursor associated with this ExprList */
9875   struct ExprList_item {
9876     Expr *pExpr;           /* The list of expressions */
9877     char *zName;           /* Token associated with this expression */
9878     char *zSpan;           /* Original text of the expression */
9879     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9880     u8 done;               /* A flag to indicate when processing is finished */
9881     u16 iCol;              /* For ORDER BY, column number in result set */
9882     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9883   } *a;                  /* One entry for each expression */
9884 };
9885
9886 /*
9887 ** An instance of this structure is used by the parser to record both
9888 ** the parse tree for an expression and the span of input text for an
9889 ** expression.
9890 */
9891 struct ExprSpan {
9892   Expr *pExpr;          /* The expression parse tree */
9893   const char *zStart;   /* First character of input text */
9894   const char *zEnd;     /* One character past the end of input text */
9895 };
9896
9897 /*
9898 ** An instance of this structure can hold a simple list of identifiers,
9899 ** such as the list "a,b,c" in the following statements:
9900 **
9901 **      INSERT INTO t(a,b,c) VALUES ...;
9902 **      CREATE INDEX idx ON t(a,b,c);
9903 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9904 **
9905 ** The IdList.a.idx field is used when the IdList represents the list of
9906 ** column names after a table name in an INSERT statement.  In the statement
9907 **
9908 **     INSERT INTO t(a,b,c) ...
9909 **
9910 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9911 */
9912 struct IdList {
9913   struct IdList_item {
9914     char *zName;      /* Name of the identifier */
9915     int idx;          /* Index in some Table.aCol[] of a column named zName */
9916   } *a;
9917   int nId;         /* Number of identifiers on the list */
9918   int nAlloc;      /* Number of entries allocated for a[] below */
9919 };
9920
9921 /*
9922 ** The bitmask datatype defined below is used for various optimizations.
9923 **
9924 ** Changing this from a 64-bit to a 32-bit type limits the number of
9925 ** tables in a join to 32 instead of 64.  But it also reduces the size
9926 ** of the library by 738 bytes on ix86.
9927 */
9928 typedef u64 Bitmask;
9929
9930 /*
9931 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9932 */
9933 #define BMS  ((int)(sizeof(Bitmask)*8))
9934
9935 /*
9936 ** The following structure describes the FROM clause of a SELECT statement.
9937 ** Each table or subquery in the FROM clause is a separate element of
9938 ** the SrcList.a[] array.
9939 **
9940 ** With the addition of multiple database support, the following structure
9941 ** can also be used to describe a particular table such as the table that
9942 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9943 ** such a table must be a simple name: ID.  But in SQLite, the table can
9944 ** now be identified by a database name, a dot, then the table name: ID.ID.
9945 **
9946 ** The jointype starts out showing the join type between the current table
9947 ** and the next table on the list.  The parser builds the list this way.
9948 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9949 ** jointype expresses the join between the table and the previous table.
9950 **
9951 ** In the colUsed field, the high-order bit (bit 63) is set if the table
9952 ** contains more than 63 columns and the 64-th or later column is used.
9953 */
9954 struct SrcList {
9955   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9956   i16 nAlloc;      /* Number of entries allocated in a[] below */
9957   struct SrcList_item {
9958     char *zDatabase;  /* Name of database holding this table */
9959     char *zName;      /* Name of the table */
9960     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9961     Table *pTab;      /* An SQL table corresponding to zName */
9962     Select *pSelect;  /* A SELECT statement used in place of a table name */
9963     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9964     u8 jointype;      /* Type of join between this able and the previous */
9965     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9966 #ifndef SQLITE_OMIT_EXPLAIN
9967     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
9968 #endif
9969     int iCursor;      /* The VDBE cursor number used to access this table */
9970     Expr *pOn;        /* The ON clause of a join */
9971     IdList *pUsing;   /* The USING clause of a join */
9972     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9973     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9974     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9975   } a[1];             /* One entry for each identifier on the list */
9976 };
9977
9978 /*
9979 ** Permitted values of the SrcList.a.jointype field
9980 */
9981 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
9982 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9983 #define JT_NATURAL   0x0004    /* True for a "natural" join */
9984 #define JT_LEFT      0x0008    /* Left outer join */
9985 #define JT_RIGHT     0x0010    /* Right outer join */
9986 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9987 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
9988
9989
9990 /*
9991 ** A WherePlan object holds information that describes a lookup
9992 ** strategy.
9993 **
9994 ** This object is intended to be opaque outside of the where.c module.
9995 ** It is included here only so that that compiler will know how big it
9996 ** is.  None of the fields in this object should be used outside of
9997 ** the where.c module.
9998 **
9999 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10000 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10001 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10002 ** case that more than one of these conditions is true.
10003 */
10004 struct WherePlan {
10005   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10006   u32 nEq;                       /* Number of == constraints */
10007   double nRow;                   /* Estimated number of rows (for EQP) */
10008   union {
10009     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10010     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10011     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10012   } u;
10013 };
10014
10015 /*
10016 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10017 ** structure contains a single instance of this structure.  This structure
10018 ** is intended to be private the the where.c module and should not be
10019 ** access or modified by other modules.
10020 **
10021 ** The pIdxInfo field is used to help pick the best index on a
10022 ** virtual table.  The pIdxInfo pointer contains indexing
10023 ** information for the i-th table in the FROM clause before reordering.
10024 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10025 ** All other information in the i-th WhereLevel object for the i-th table
10026 ** after FROM clause ordering.
10027 */
10028 struct WhereLevel {
10029   WherePlan plan;       /* query plan for this element of the FROM clause */
10030   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10031   int iTabCur;          /* The VDBE cursor used to access the table */
10032   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10033   int addrBrk;          /* Jump here to break out of the loop */
10034   int addrNxt;          /* Jump here to start the next IN combination */
10035   int addrCont;         /* Jump here to continue with the next loop cycle */
10036   int addrFirst;        /* First instruction of interior of the loop */
10037   u8 iFrom;             /* Which entry in the FROM clause */
10038   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10039   int p1, p2;           /* Operands of the opcode used to ends the loop */
10040   union {               /* Information that depends on plan.wsFlags */
10041     struct {
10042       int nIn;              /* Number of entries in aInLoop[] */
10043       struct InLoop {
10044         int iCur;              /* The VDBE cursor used by this IN operator */
10045         int addrInTop;         /* Top of the IN loop */
10046       } *aInLoop;           /* Information about each nested IN operator */
10047     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10048   } u;
10049
10050   /* The following field is really not part of the current level.  But
10051   ** we need a place to cache virtual table index information for each
10052   ** virtual table in the FROM clause and the WhereLevel structure is
10053   ** a convenient place since there is one WhereLevel for each FROM clause
10054   ** element.
10055   */
10056   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10057 };
10058
10059 /*
10060 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10061 ** and the WhereInfo.wctrlFlags member.
10062 */
10063 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10064 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10065 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10066 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10067 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10068 #define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
10069 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
10070 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
10071 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
10072
10073 /*
10074 ** The WHERE clause processing routine has two halves.  The
10075 ** first part does the start of the WHERE loop and the second
10076 ** half does the tail of the WHERE loop.  An instance of
10077 ** this structure is returned by the first half and passed
10078 ** into the second half to give some continuity.
10079 */
10080 struct WhereInfo {
10081   Parse *pParse;       /* Parsing and code generating context */
10082   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10083   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10084   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10085   SrcList *pTabList;             /* List of tables in the join */
10086   int iTop;                      /* The very beginning of the WHERE loop */
10087   int iContinue;                 /* Jump here to continue with next record */
10088   int iBreak;                    /* Jump here to break out of the loop */
10089   int nLevel;                    /* Number of nested loop */
10090   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10091   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10092   double nRowOut;                /* Estimated number of output rows */
10093   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10094 };
10095
10096 /*
10097 ** A NameContext defines a context in which to resolve table and column
10098 ** names.  The context consists of a list of tables (the pSrcList) field and
10099 ** a list of named expression (pEList).  The named expression list may
10100 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10101 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10102 ** pEList corresponds to the result set of a SELECT and is NULL for
10103 ** other statements.
10104 **
10105 ** NameContexts can be nested.  When resolving names, the inner-most 
10106 ** context is searched first.  If no match is found, the next outer
10107 ** context is checked.  If there is still no match, the next context
10108 ** is checked.  This process continues until either a match is found
10109 ** or all contexts are check.  When a match is found, the nRef member of
10110 ** the context containing the match is incremented. 
10111 **
10112 ** Each subquery gets a new NameContext.  The pNext field points to the
10113 ** NameContext in the parent query.  Thus the process of scanning the
10114 ** NameContext list corresponds to searching through successively outer
10115 ** subqueries looking for a match.
10116 */
10117 struct NameContext {
10118   Parse *pParse;       /* The parser */
10119   SrcList *pSrcList;   /* One or more tables used to resolve names */
10120   ExprList *pEList;    /* Optional list of named expressions */
10121   int nRef;            /* Number of names resolved by this context */
10122   int nErr;            /* Number of errors encountered while resolving names */
10123   u8 allowAgg;         /* Aggregate functions allowed here */
10124   u8 hasAgg;           /* True if aggregates are seen */
10125   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10126   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10127   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10128   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10129 };
10130
10131 /*
10132 ** An instance of the following structure contains all information
10133 ** needed to generate code for a single SELECT statement.
10134 **
10135 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10136 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10137 ** limit and nOffset to the value of the offset (or 0 if there is not
10138 ** offset).  But later on, nLimit and nOffset become the memory locations
10139 ** in the VDBE that record the limit and offset counters.
10140 **
10141 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10142 ** These addresses must be stored so that we can go back and fill in
10143 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10144 ** the number of columns in P2 can be computed at the same time
10145 ** as the OP_OpenEphm instruction is coded because not
10146 ** enough information about the compound query is known at that point.
10147 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10148 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10149 ** sequences for the ORDER BY clause.
10150 */
10151 struct Select {
10152   ExprList *pEList;      /* The fields of the result */
10153   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10154   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10155   u16 selFlags;          /* Various SF_* values */
10156   SrcList *pSrc;         /* The FROM clause */
10157   Expr *pWhere;          /* The WHERE clause */
10158   ExprList *pGroupBy;    /* The GROUP BY clause */
10159   Expr *pHaving;         /* The HAVING clause */
10160   ExprList *pOrderBy;    /* The ORDER BY clause */
10161   Select *pPrior;        /* Prior select in a compound select statement */
10162   Select *pNext;         /* Next select to the left in a compound */
10163   Select *pRightmost;    /* Right-most select in a compound select statement */
10164   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10165   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10166   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10167   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10168   double nSelectRow;     /* Estimated number of result rows */
10169 };
10170
10171 /*
10172 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10173 ** "Select Flag".
10174 */
10175 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10176 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10177 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10178 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10179 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
10180 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10181
10182
10183 /*
10184 ** The results of a select can be distributed in several ways.  The
10185 ** "SRT" prefix means "SELECT Result Type".
10186 */
10187 #define SRT_Union        1  /* Store result as keys in an index */
10188 #define SRT_Except       2  /* Remove result from a UNION index */
10189 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10190 #define SRT_Discard      4  /* Do not save the results anywhere */
10191
10192 /* The ORDER BY clause is ignored for all of the above */
10193 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10194
10195 #define SRT_Output       5  /* Output each row of result */
10196 #define SRT_Mem          6  /* Store result in a memory cell */
10197 #define SRT_Set          7  /* Store results as keys in an index */
10198 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10199 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10200 #define SRT_Coroutine   10  /* Generate a single row of result */
10201
10202 /*
10203 ** A structure used to customize the behavior of sqlite3Select(). See
10204 ** comments above sqlite3Select() for details.
10205 */
10206 typedef struct SelectDest SelectDest;
10207 struct SelectDest {
10208   u8 eDest;         /* How to dispose of the results */
10209   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10210   int iParm;        /* A parameter used by the eDest disposal method */
10211   int iMem;         /* Base register where results are written */
10212   int nMem;         /* Number of registers allocated */
10213 };
10214
10215 /*
10216 ** During code generation of statements that do inserts into AUTOINCREMENT 
10217 ** tables, the following information is attached to the Table.u.autoInc.p
10218 ** pointer of each autoincrement table to record some side information that
10219 ** the code generator needs.  We have to keep per-table autoincrement
10220 ** information in case inserts are down within triggers.  Triggers do not
10221 ** normally coordinate their activities, but we do need to coordinate the
10222 ** loading and saving of autoincrement information.
10223 */
10224 struct AutoincInfo {
10225   AutoincInfo *pNext;   /* Next info block in a list of them all */
10226   Table *pTab;          /* Table this info block refers to */
10227   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
10228   int regCtr;           /* Memory register holding the rowid counter */
10229 };
10230
10231 /*
10232 ** Size of the column cache
10233 */
10234 #ifndef SQLITE_N_COLCACHE
10235 # define SQLITE_N_COLCACHE 10
10236 #endif
10237
10238 /*
10239 ** At least one instance of the following structure is created for each 
10240 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10241 ** statement. All such objects are stored in the linked list headed at
10242 ** Parse.pTriggerPrg and deleted once statement compilation has been
10243 ** completed.
10244 **
10245 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10246 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10247 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10248 ** The Parse.pTriggerPrg list never contains two entries with the same
10249 ** values for both pTrigger and orconf.
10250 **
10251 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10252 ** accessed (or set to 0 for triggers fired as a result of INSERT 
10253 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10254 ** a mask of new.* columns used by the program.
10255 */
10256 struct TriggerPrg {
10257   Trigger *pTrigger;      /* Trigger this program was coded from */
10258   int orconf;             /* Default ON CONFLICT policy */
10259   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
10260   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
10261   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
10262 };
10263
10264 /*
10265 ** An SQL parser context.  A copy of this structure is passed through
10266 ** the parser and down into all the parser action routine in order to
10267 ** carry around information that is global to the entire parse.
10268 **
10269 ** The structure is divided into two parts.  When the parser and code
10270 ** generate call themselves recursively, the first part of the structure
10271 ** is constant but the second part is reset at the beginning and end of
10272 ** each recursion.
10273 **
10274 ** The nTableLock and aTableLock variables are only used if the shared-cache 
10275 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10276 ** used to store the set of table-locks required by the statement being
10277 ** compiled. Function sqlite3TableLock() is used to add entries to the
10278 ** list.
10279 */
10280 struct Parse {
10281   sqlite3 *db;         /* The main database structure */
10282   int rc;              /* Return code from execution */
10283   char *zErrMsg;       /* An error message */
10284   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10285   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10286   u8 nameClash;        /* A permanent table name clashes with temp table name */
10287   u8 checkSchema;      /* Causes schema cookie check after an error */
10288   u8 nested;           /* Number of nested calls to the parser/code generator */
10289   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10290   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10291   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10292   int aTempReg[8];     /* Holding area for temporary registers */
10293   int nRangeReg;       /* Size of the temporary register block */
10294   int iRangeReg;       /* First register in temporary register block */
10295   int nErr;            /* Number of errors seen */
10296   int nTab;            /* Number of previously allocated VDBE cursors */
10297   int nMem;            /* Number of memory cells used so far */
10298   int nSet;            /* Number of sets used so far */
10299   int ckBase;          /* Base register of data during check constraints */
10300   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10301   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
10302   u8 nColCache;        /* Number of entries in the column cache */
10303   u8 iColCache;        /* Next entry of the cache to replace */
10304   struct yColCache {
10305     int iTable;           /* Table cursor number */
10306     int iColumn;          /* Table column number */
10307     u8 tempReg;           /* iReg is a temp register that needs to be freed */
10308     int iLevel;           /* Nesting level */
10309     int iReg;             /* Reg with value of this column. 0 means none. */
10310     int lru;              /* Least recently used entry has the smallest value */
10311   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
10312   u32 writeMask;       /* Start a write transaction on these databases */
10313   u32 cookieMask;      /* Bitmask of schema verified databases */
10314   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
10315   u8 mayAbort;         /* True if statement may throw an ABORT exception */
10316   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10317   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10318 #ifndef SQLITE_OMIT_SHARED_CACHE
10319   int nTableLock;        /* Number of locks in aTableLock */
10320   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10321 #endif
10322   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10323   int regRoot;         /* Register holding root page number for new objects */
10324   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
10325   int nMaxArg;         /* Max args passed to user function by sub-program */
10326
10327   /* Information used while coding trigger programs. */
10328   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
10329   Table *pTriggerTab;  /* Table triggers are being coded for */
10330   u32 oldmask;         /* Mask of old.* columns referenced */
10331   u32 newmask;         /* Mask of new.* columns referenced */
10332   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
10333   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
10334   u8 disableTriggers;  /* True to disable triggers */
10335   double nQueryLoop;   /* Estimated number of iterations of a query */
10336
10337   /* Above is constant between recursions.  Below is reset before and after
10338   ** each recursion */
10339
10340   int nVar;            /* Number of '?' variables seen in the SQL so far */
10341   int nVarExpr;        /* Number of used slots in apVarExpr[] */
10342   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
10343   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
10344   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
10345   int nAlias;          /* Number of aliased result set columns */
10346   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10347   int *aAlias;         /* Register used to hold aliased result */
10348   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10349   Token sNameToken;    /* Token with unqualified schema object name */
10350   Token sLastToken;    /* The last token parsed */
10351   const char *zTail;   /* All SQL text past the last semicolon parsed */
10352   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10353   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10354   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10355 #ifndef SQLITE_OMIT_VIRTUALTABLE
10356   Token sArg;                /* Complete text of a module argument */
10357   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10358   int nVtabLock;             /* Number of virtual tables to lock */
10359   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10360 #endif
10361   int nHeight;            /* Expression tree height of current sub-select */
10362   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10363   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10364
10365 #ifndef SQLITE_OMIT_EXPLAIN
10366   int iSelectId;
10367   int iNextSelectId;
10368 #endif
10369 };
10370
10371 #ifdef SQLITE_OMIT_VIRTUALTABLE
10372   #define IN_DECLARE_VTAB 0
10373 #else
10374   #define IN_DECLARE_VTAB (pParse->declareVtab)
10375 #endif
10376
10377 /*
10378 ** An instance of the following structure can be declared on a stack and used
10379 ** to save the Parse.zAuthContext value so that it can be restored later.
10380 */
10381 struct AuthContext {
10382   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10383   Parse *pParse;              /* The Parse structure */
10384 };
10385
10386 /*
10387 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10388 */
10389 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10390 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10391 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10392 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10393 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10394 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10395
10396 /*
10397  * Each trigger present in the database schema is stored as an instance of
10398  * struct Trigger. 
10399  *
10400  * Pointers to instances of struct Trigger are stored in two ways.
10401  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
10402  *    database). This allows Trigger structures to be retrieved by name.
10403  * 2. All triggers associated with a single table form a linked list, using the
10404  *    pNext member of struct Trigger. A pointer to the first element of the
10405  *    linked list is stored as the "pTrigger" member of the associated
10406  *    struct Table.
10407  *
10408  * The "step_list" member points to the first element of a linked list
10409  * containing the SQL statements specified as the trigger program.
10410  */
10411 struct Trigger {
10412   char *zName;            /* The name of the trigger                        */
10413   char *table;            /* The table or view to which the trigger applies */
10414   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10415   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10416   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10417   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10418                              the <column-list> is stored here */
10419   Schema *pSchema;        /* Schema containing the trigger */
10420   Schema *pTabSchema;     /* Schema containing the table */
10421   TriggerStep *step_list; /* Link list of trigger program steps             */
10422   Trigger *pNext;         /* Next trigger associated with the table */
10423 };
10424
10425 /*
10426 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10427 ** determine which. 
10428 **
10429 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10430 ** In that cases, the constants below can be ORed together.
10431 */
10432 #define TRIGGER_BEFORE  1
10433 #define TRIGGER_AFTER   2
10434
10435 /*
10436  * An instance of struct TriggerStep is used to store a single SQL statement
10437  * that is a part of a trigger-program. 
10438  *
10439  * Instances of struct TriggerStep are stored in a singly linked list (linked
10440  * using the "pNext" member) referenced by the "step_list" member of the 
10441  * associated struct Trigger instance. The first element of the linked list is
10442  * the first step of the trigger-program.
10443  * 
10444  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10445  * "SELECT" statement. The meanings of the other members is determined by the 
10446  * value of "op" as follows:
10447  *
10448  * (op == TK_INSERT)
10449  * orconf    -> stores the ON CONFLICT algorithm
10450  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10451  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10452  * target    -> A token holding the quoted name of the table to insert into.
10453  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10454  *              this stores values to be inserted. Otherwise NULL.
10455  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
10456  *              statement, then this stores the column-names to be
10457  *              inserted into.
10458  *
10459  * (op == TK_DELETE)
10460  * target    -> A token holding the quoted name of the table to delete from.
10461  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
10462  *              Otherwise NULL.
10463  * 
10464  * (op == TK_UPDATE)
10465  * target    -> A token holding the quoted name of the table to update rows of.
10466  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
10467  *              Otherwise NULL.
10468  * pExprList -> A list of the columns to update and the expressions to update
10469  *              them to. See sqlite3Update() documentation of "pChanges"
10470  *              argument.
10471  * 
10472  */
10473 struct TriggerStep {
10474   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
10475   u8 orconf;           /* OE_Rollback etc. */
10476   Trigger *pTrig;      /* The trigger that this step is a part of */
10477   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
10478   Token target;        /* Target table for DELETE, UPDATE, INSERT */
10479   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
10480   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
10481   IdList *pIdList;     /* Column names for INSERT */
10482   TriggerStep *pNext;  /* Next in the link-list */
10483   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
10484 };
10485
10486 /*
10487 ** The following structure contains information used by the sqliteFix...
10488 ** routines as they walk the parse tree to make database references
10489 ** explicit.  
10490 */
10491 typedef struct DbFixer DbFixer;
10492 struct DbFixer {
10493   Parse *pParse;      /* The parsing context.  Error messages written here */
10494   const char *zDb;    /* Make sure all objects are contained in this database */
10495   const char *zType;  /* Type of the container - used for error messages */
10496   const Token *pName; /* Name of the container - used for error messages */
10497 };
10498
10499 /*
10500 ** An objected used to accumulate the text of a string where we
10501 ** do not necessarily know how big the string will be in the end.
10502 */
10503 struct StrAccum {
10504   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
10505   char *zBase;         /* A base allocation.  Not from malloc. */
10506   char *zText;         /* The string collected so far */
10507   int  nChar;          /* Length of the string so far */
10508   int  nAlloc;         /* Amount of space allocated in zText */
10509   int  mxAlloc;        /* Maximum allowed string length */
10510   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
10511   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
10512   u8   tooBig;         /* Becomes true if string size exceeds limits */
10513 };
10514
10515 /*
10516 ** A pointer to this structure is used to communicate information
10517 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
10518 */
10519 typedef struct {
10520   sqlite3 *db;        /* The database being initialized */
10521   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
10522   char **pzErrMsg;    /* Error message stored here */
10523   int rc;             /* Result code stored here */
10524 } InitData;
10525
10526 /*
10527 ** Structure containing global configuration data for the SQLite library.
10528 **
10529 ** This structure also contains some state information.
10530 */
10531 struct Sqlite3Config {
10532   int bMemstat;                     /* True to enable memory status */
10533   int bCoreMutex;                   /* True to enable core mutexing */
10534   int bFullMutex;                   /* True to enable full mutexing */
10535   int mxStrlen;                     /* Maximum string length */
10536   int szLookaside;                  /* Default lookaside buffer size */
10537   int nLookaside;                   /* Default lookaside buffer count */
10538   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
10539   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
10540   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
10541   void *pHeap;                      /* Heap storage space */
10542   int nHeap;                        /* Size of pHeap[] */
10543   int mnReq, mxReq;                 /* Min and max heap requests sizes */
10544   void *pScratch;                   /* Scratch memory */
10545   int szScratch;                    /* Size of each scratch buffer */
10546   int nScratch;                     /* Number of scratch buffers */
10547   void *pPage;                      /* Page cache memory */
10548   int szPage;                       /* Size of each page in pPage[] */
10549   int nPage;                        /* Number of pages in pPage[] */
10550   int mxParserStack;                /* maximum depth of the parser stack */
10551   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
10552   /* The above might be initialized to non-zero.  The following need to always
10553   ** initially be zero, however. */
10554   int isInit;                       /* True after initialization has finished */
10555   int inProgress;                   /* True while initialization in progress */
10556   int isMutexInit;                  /* True after mutexes are initialized */
10557   int isMallocInit;                 /* True after malloc is initialized */
10558   int isPCacheInit;                 /* True after malloc is initialized */
10559   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
10560   int nRefInitMutex;                /* Number of users of pInitMutex */
10561   void (*xLog)(void*,int,const char*); /* Function for logging */
10562   void *pLogArg;                       /* First argument to xLog() */
10563 };
10564
10565 /*
10566 ** Context pointer passed down through the tree-walk.
10567 */
10568 struct Walker {
10569   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
10570   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
10571   Parse *pParse;                            /* Parser context.  */
10572   union {                                   /* Extra data for callback */
10573     NameContext *pNC;                          /* Naming context */
10574     int i;                                     /* Integer value */
10575   } u;
10576 };
10577
10578 /* Forward declarations */
10579 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
10580 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
10581 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
10582 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
10583 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
10584
10585 /*
10586 ** Return code from the parse-tree walking primitives and their
10587 ** callbacks.
10588 */
10589 #define WRC_Continue    0   /* Continue down into children */
10590 #define WRC_Prune       1   /* Omit children but continue walking siblings */
10591 #define WRC_Abort       2   /* Abandon the tree walk */
10592
10593 /*
10594 ** Assuming zIn points to the first byte of a UTF-8 character,
10595 ** advance zIn to point to the first byte of the next UTF-8 character.
10596 */
10597 #define SQLITE_SKIP_UTF8(zIn) {                        \
10598   if( (*(zIn++))>=0xc0 ){                              \
10599     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
10600   }                                                    \
10601 }
10602
10603 /*
10604 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
10605 ** the same name but without the _BKPT suffix.  These macros invoke
10606 ** routines that report the line-number on which the error originated
10607 ** using sqlite3_log().  The routines also provide a convenient place
10608 ** to set a debugger breakpoint.
10609 */
10610 SQLITE_PRIVATE int sqlite3CorruptError(int);
10611 SQLITE_PRIVATE int sqlite3MisuseError(int);
10612 SQLITE_PRIVATE int sqlite3CantopenError(int);
10613 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
10614 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
10615 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
10616
10617
10618 /*
10619 ** FTS4 is really an extension for FTS3.  It is enabled using the
10620 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10621 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10622 */
10623 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10624 # define SQLITE_ENABLE_FTS3
10625 #endif
10626
10627 /*
10628 ** The ctype.h header is needed for non-ASCII systems.  It is also
10629 ** needed by FTS3 when FTS3 is included in the amalgamation.
10630 */
10631 #if !defined(SQLITE_ASCII) || \
10632     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10633 # include <ctype.h>
10634 #endif
10635
10636 /*
10637 ** The following macros mimic the standard library functions toupper(),
10638 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10639 ** sqlite versions only work for ASCII characters, regardless of locale.
10640 */
10641 #ifdef SQLITE_ASCII
10642 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10643 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10644 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10645 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10646 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10647 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10648 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10649 #else
10650 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
10651 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
10652 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10653 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10654 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10655 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10656 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
10657 #endif
10658
10659 /*
10660 ** Internal function prototypes
10661 */
10662 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10663 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10664 #define sqlite3StrNICmp sqlite3_strnicmp
10665
10666 SQLITE_PRIVATE int sqlite3MallocInit(void);
10667 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10668 SQLITE_PRIVATE void *sqlite3Malloc(int);
10669 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10670 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10671 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10672 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10673 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10674 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10675 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10676 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10677 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10678 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10679 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10680 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10681 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10682 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10683 SQLITE_PRIVATE void sqlite3PageFree(void*);
10684 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10685 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10686 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
10687
10688 /*
10689 ** On systems with ample stack space and that support alloca(), make
10690 ** use of alloca() to obtain space for large automatic objects.  By default,
10691 ** obtain space from malloc().
10692 **
10693 ** The alloca() routine never returns NULL.  This will cause code paths
10694 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10695 */
10696 #ifdef SQLITE_USE_ALLOCA
10697 # define sqlite3StackAllocRaw(D,N)   alloca(N)
10698 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10699 # define sqlite3StackFree(D,P)       
10700 #else
10701 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10702 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10703 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10704 #endif
10705
10706 #ifdef SQLITE_ENABLE_MEMSYS3
10707 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10708 #endif
10709 #ifdef SQLITE_ENABLE_MEMSYS5
10710 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10711 #endif
10712
10713
10714 #ifndef SQLITE_MUTEX_OMIT
10715 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
10716 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
10717 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10718 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10719 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10720 #endif
10721
10722 SQLITE_PRIVATE int sqlite3StatusValue(int);
10723 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10724 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10725
10726 #ifndef SQLITE_OMIT_FLOATING_POINT
10727 SQLITE_PRIVATE   int sqlite3IsNaN(double);
10728 #else
10729 # define sqlite3IsNaN(X)  0
10730 #endif
10731
10732 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10733 #ifndef SQLITE_OMIT_TRACE
10734 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10735 #endif
10736 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10737 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10738 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10739 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10740 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10741 #endif
10742 #if defined(SQLITE_TEST)
10743 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10744 #endif
10745 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10746 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10747 SQLITE_PRIVATE int sqlite3Dequote(char*);
10748 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10749 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10750 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10751 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10752 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10753 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10754 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10755 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10756 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10757 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10758 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10759 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10760 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10761 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10762 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10763 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10764 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10765 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10766 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10767 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10768 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10769 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10770 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10771 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10772 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10773 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10774 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10775 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10776 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10777 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10778 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10779 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10780 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10781 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10782 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10783 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10784
10785 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10786 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10787 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10788 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10789 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10790 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10791 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10792
10793 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10794 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10795 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10796 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10797 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10798
10799 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10800
10801 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10802 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10803 #else
10804 # define sqlite3ViewGetColumnNames(A,B) 0
10805 #endif
10806
10807 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10808 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
10809 #ifndef SQLITE_OMIT_AUTOINCREMENT
10810 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10811 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10812 #else
10813 # define sqlite3AutoincrementBegin(X)
10814 # define sqlite3AutoincrementEnd(X)
10815 #endif
10816 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10817 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10818 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10819 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10820 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10821 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10822 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10823                                       Token*, Select*, Expr*, IdList*);
10824 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10825 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10826 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10827 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10828 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10829 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10830 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10831                         Token*, int, int);
10832 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10833 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10834 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10835                          Expr*,ExprList*,int,Expr*,Expr*);
10836 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10837 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10838 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10839 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10840 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10841 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10842 #endif
10843 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10844 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10845 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10846 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10847 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10848 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
10849 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10850 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10851 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10852 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10853 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10854 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10855 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10856 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10857 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10858 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10859 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10860 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10861 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10862 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10863 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10864 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10865 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10866 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10867 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10868 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10869 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10870 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10871 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10872 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10873 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10874 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
10875 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10876 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10877 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10878 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10879 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10880 SQLITE_PRIVATE void sqlite3PrngResetState(void);
10881 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10882 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10883 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10884 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10885 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10886 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10887 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10888 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10889 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10890 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10891 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10892 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10893 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10894 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10895 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10896 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10897 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10898 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10899 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10900                                      int*,int,int,int,int,int*);
10901 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10902 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10903 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10904 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10905 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10906 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10907 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10908 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10909 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10910 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10911 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10912 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10913 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10914 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10915 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10916 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10917 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10918 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10919 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10920
10921 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10922 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10923 #endif
10924
10925 #ifndef SQLITE_OMIT_TRIGGER
10926 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10927                            Expr*,int, int);
10928 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10929 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10930 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10931 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10932 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10933 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10934                             int, int, int);
10935 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10936   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10937 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10938 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10939 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10940                                         ExprList*,Select*,u8);
10941 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10942 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10943 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10944 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10945 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10946 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10947 #else
10948 # define sqlite3TriggersExist(B,C,D,E,F) 0
10949 # define sqlite3DeleteTrigger(A,B)
10950 # define sqlite3DropTriggerPtr(A,B)
10951 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10952 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10953 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10954 # define sqlite3TriggerList(X, Y) 0
10955 # define sqlite3ParseToplevel(p) p
10956 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10957 #endif
10958
10959 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10960 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10961 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10962 #ifndef SQLITE_OMIT_AUTHORIZATION
10963 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10964 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10965 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10966 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10967 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10968 #else
10969 # define sqlite3AuthRead(a,b,c,d)
10970 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10971 # define sqlite3AuthContextPush(a,b,c)
10972 # define sqlite3AuthContextPop(a)  ((void)(a))
10973 #endif
10974 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10975 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10976 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10977 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10978 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10979 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10980 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10981 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10982 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
10983 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10984 SQLITE_PRIVATE int sqlite3Atoi(const char*);
10985 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10986 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10987 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10988
10989 /*
10990 ** Routines to read and write variable-length integers.  These used to
10991 ** be defined locally, but now we use the varint routines in the util.c
10992 ** file.  Code should use the MACRO forms below, as the Varint32 versions
10993 ** are coded to assume the single byte case is already handled (which 
10994 ** the MACRO form does).
10995 */
10996 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10997 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10998 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10999 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11000 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11001
11002 /*
11003 ** The header of a record consists of a sequence variable-length integers.
11004 ** These integers are almost always small and are encoded as a single byte.
11005 ** The following macros take advantage this fact to provide a fast encode
11006 ** and decode of the integers in a record header.  It is faster for the common
11007 ** case where the integer is a single byte.  It is a little slower when the
11008 ** integer is two or more bytes.  But overall it is faster.
11009 **
11010 ** The following expressions are equivalent:
11011 **
11012 **     x = sqlite3GetVarint32( A, &B );
11013 **     x = sqlite3PutVarint32( A, B );
11014 **
11015 **     x = getVarint32( A, B );
11016 **     x = putVarint32( A, B );
11017 **
11018 */
11019 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11020 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11021 #define getVarint    sqlite3GetVarint
11022 #define putVarint    sqlite3PutVarint
11023
11024
11025 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11026 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11027 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11028 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11029 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11030 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11031 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11032 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11033 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11034 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11035 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11036 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11037 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11038 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11039 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11040 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11041 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11042 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11043 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11044
11045 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11046 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11047 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
11048                         void(*)(void*));
11049 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11050 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11051 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11052 #ifdef SQLITE_ENABLE_STAT2
11053 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11054 #endif
11055 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11056 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11057 #ifndef SQLITE_AMALGAMATION
11058 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11059 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11060 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11061 SQLITE_PRIVATE const Token sqlite3IntTokens[];
11062 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11063 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11064 #ifndef SQLITE_OMIT_WSD
11065 SQLITE_PRIVATE int sqlite3PendingByte;
11066 #endif
11067 #endif
11068 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
11069 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11070 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11071 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11072 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11073 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11074 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11075 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11076 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11077 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11078 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11079 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11080 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11081 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11082 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11083 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11084 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11085 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11086 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11087 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11088 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11089 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11090 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11091 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11092 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11093 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11094 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11095 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
11096 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11097 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11098 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11099 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
11100   void (*)(sqlite3_context*,int,sqlite3_value **),
11101   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11102   FuncDestructor *pDestructor
11103 );
11104 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11105 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11106
11107 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11108 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11109 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11110 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11111 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11112 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11113
11114 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11115 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11116
11117 /*
11118 ** The interface to the LEMON-generated parser
11119 */
11120 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11121 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11122 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11123 #ifdef YYTRACKMAXSTACKDEPTH
11124 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11125 #endif
11126
11127 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11128 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11129 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11130 #else
11131 # define sqlite3CloseExtensions(X)
11132 #endif
11133
11134 #ifndef SQLITE_OMIT_SHARED_CACHE
11135 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11136 #else
11137   #define sqlite3TableLock(v,w,x,y,z)
11138 #endif
11139
11140 #ifdef SQLITE_TEST
11141 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11142 #endif
11143
11144 #ifdef SQLITE_OMIT_VIRTUALTABLE
11145 #  define sqlite3VtabClear(Y)
11146 #  define sqlite3VtabSync(X,Y) SQLITE_OK
11147 #  define sqlite3VtabRollback(X)
11148 #  define sqlite3VtabCommit(X)
11149 #  define sqlite3VtabInSync(db) 0
11150 #  define sqlite3VtabLock(X) 
11151 #  define sqlite3VtabUnlock(X)
11152 #  define sqlite3VtabUnlockList(X)
11153 #else
11154 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
11155 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
11156 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
11157 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
11158 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
11159 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
11160 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
11161 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11162 #endif
11163 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11164 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11165 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11166 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11167 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11168 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11169 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11170 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11171 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11172 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11173 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11174 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11175 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11176 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11177 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11178 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11179 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11180 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11181 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11182 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int);
11183 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11184
11185 /* Declarations for functions in fkey.c. All of these are replaced by
11186 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11187 ** key functionality is available. If OMIT_TRIGGER is defined but
11188 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11189 ** this case foreign keys are parsed, but no other functionality is 
11190 ** provided (enforcement of FK constraints requires the triggers sub-system).
11191 */
11192 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11193 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
11194 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11195 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11196 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
11197 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
11198 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
11199 #else
11200   #define sqlite3FkActions(a,b,c,d)
11201   #define sqlite3FkCheck(a,b,c,d)
11202   #define sqlite3FkDropTable(a,b,c)
11203   #define sqlite3FkOldmask(a,b)      0
11204   #define sqlite3FkRequired(a,b,c,d) 0
11205 #endif
11206 #ifndef SQLITE_OMIT_FOREIGN_KEY
11207 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
11208 #else
11209   #define sqlite3FkDelete(a,b)
11210 #endif
11211
11212
11213 /*
11214 ** Available fault injectors.  Should be numbered beginning with 0.
11215 */
11216 #define SQLITE_FAULTINJECTOR_MALLOC     0
11217 #define SQLITE_FAULTINJECTOR_COUNT      1
11218
11219 /*
11220 ** The interface to the code in fault.c used for identifying "benign"
11221 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11222 ** is not defined.
11223 */
11224 #ifndef SQLITE_OMIT_BUILTIN_TEST
11225 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
11226 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
11227 #else
11228   #define sqlite3BeginBenignMalloc()
11229   #define sqlite3EndBenignMalloc()
11230 #endif
11231
11232 #define IN_INDEX_ROWID           1
11233 #define IN_INDEX_EPH             2
11234 #define IN_INDEX_INDEX           3
11235 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11236
11237 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11238 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11239 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
11240 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
11241 #else
11242   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11243 #endif
11244
11245 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11246 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11247 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11248
11249 #if SQLITE_MAX_EXPR_DEPTH>0
11250 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11251 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
11252 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
11253 #else
11254   #define sqlite3ExprSetHeight(x,y)
11255   #define sqlite3SelectExprHeight(x) 0
11256   #define sqlite3ExprCheckHeight(x,y)
11257 #endif
11258
11259 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11260 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11261
11262 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11263 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11264 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
11265 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
11266 #else
11267   #define sqlite3ConnectionBlocked(x,y)
11268   #define sqlite3ConnectionUnlocked(x)
11269   #define sqlite3ConnectionClosed(x)
11270 #endif
11271
11272 #ifdef SQLITE_DEBUG
11273 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
11274 #endif
11275
11276 /*
11277 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11278 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11279 ** print I/O tracing messages. 
11280 */
11281 #ifdef SQLITE_ENABLE_IOTRACE
11282 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11283 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
11284 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11285 #else
11286 # define IOTRACE(A)
11287 # define sqlite3VdbeIOTraceSql(X)
11288 #endif
11289
11290 /*
11291 ** These routines are available for the mem2.c debugging memory allocator
11292 ** only.  They are used to verify that different "types" of memory
11293 ** allocations are properly tracked by the system.
11294 **
11295 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11296 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
11297 ** a single bit set.
11298 **
11299 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
11300 ** argument match the type set by the previous sqlite3MemdebugSetType().
11301 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11302 **
11303 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
11304 ** argument match the type set by the previous sqlite3MemdebugSetType().
11305 **
11306 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11307 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
11308 ** it might have been allocated by lookaside, except the allocation was
11309 ** too large or lookaside was already full.  It is important to verify
11310 ** that allocations that might have been satisfied by lookaside are not
11311 ** passed back to non-lookaside free() routines.  Asserts such as the
11312 ** example above are placed on the non-lookaside free() routines to verify
11313 ** this constraint. 
11314 **
11315 ** All of this is no-op for a production build.  It only comes into
11316 ** play when the SQLITE_MEMDEBUG compile-time option is used.
11317 */
11318 #ifdef SQLITE_MEMDEBUG
11319 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
11320 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
11321 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
11322 #else
11323 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
11324 # define sqlite3MemdebugHasType(X,Y)  1
11325 # define sqlite3MemdebugNoType(X,Y)   1
11326 #endif
11327 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
11328 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
11329 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
11330 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
11331 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
11332
11333 #endif /* _SQLITEINT_H_ */
11334
11335 /************** End of sqliteInt.h *******************************************/
11336 /************** Begin file global.c ******************************************/
11337 /*
11338 ** 2008 June 13
11339 **
11340 ** The author disclaims copyright to this source code.  In place of
11341 ** a legal notice, here is a blessing:
11342 **
11343 **    May you do good and not evil.
11344 **    May you find forgiveness for yourself and forgive others.
11345 **    May you share freely, never taking more than you give.
11346 **
11347 *************************************************************************
11348 **
11349 ** This file contains definitions of global variables and contants.
11350 */
11351
11352 /* An array to map all upper-case characters into their corresponding
11353 ** lower-case character. 
11354 **
11355 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11356 ** handle case conversions for the UTF character set since the tables
11357 ** involved are nearly as big or bigger than SQLite itself.
11358 */
11359 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11360 #ifdef SQLITE_ASCII
11361       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11362      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11363      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11364      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11365     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11366     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11367     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11368     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11369     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11370     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11371     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11372     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11373     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11374     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11375     252,253,254,255
11376 #endif
11377 #ifdef SQLITE_EBCDIC
11378       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11379      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11380      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11381      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11382      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11383      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11384      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11385     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11386     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11387     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11388     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11389     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11390     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11391     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11392     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11393     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11394 #endif
11395 };
11396
11397 /*
11398 ** The following 256 byte lookup table is used to support SQLites built-in
11399 ** equivalents to the following standard library functions:
11400 **
11401 **   isspace()                        0x01
11402 **   isalpha()                        0x02
11403 **   isdigit()                        0x04
11404 **   isalnum()                        0x06
11405 **   isxdigit()                       0x08
11406 **   toupper()                        0x20
11407 **   SQLite identifier character      0x40
11408 **
11409 ** Bit 0x20 is set if the mapped character requires translation to upper
11410 ** case. i.e. if the character is a lower-case ASCII character.
11411 ** If x is a lower-case ASCII character, then its upper-case equivalent
11412 ** is (x - 0x20). Therefore toupper() can be implemented as:
11413 **
11414 **   (x & ~(map[x]&0x20))
11415 **
11416 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11417 ** array. tolower() is used more often than toupper() by SQLite.
11418 **
11419 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
11420 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11421 ** non-ASCII UTF character. Hence the test for whether or not a character is
11422 ** part of an identifier is 0x46.
11423 **
11424 ** SQLite's versions are identical to the standard versions assuming a
11425 ** locale of "C". They are implemented as macros in sqliteInt.h.
11426 */
11427 #ifdef SQLITE_ASCII
11428 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11429   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11430   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11431   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11432   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11433   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11434   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11435   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11436   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11437
11438   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
11439   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
11440   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
11441   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
11442   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
11443   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
11444   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
11445   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
11446
11447   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
11448   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
11449   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
11450   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
11451   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
11452   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
11453   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
11454   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
11455
11456   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
11457   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
11458   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
11459   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
11460   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
11461   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
11462   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
11463   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
11464 };
11465 #endif
11466
11467
11468
11469 /*
11470 ** The following singleton contains the global configuration for
11471 ** the SQLite library.
11472 */
11473 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
11474    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11475    1,                         /* bCoreMutex */
11476    SQLITE_THREADSAFE==1,      /* bFullMutex */
11477    0x7ffffffe,                /* mxStrlen */
11478    100,                       /* szLookaside */
11479    500,                       /* nLookaside */
11480    {0,0,0,0,0,0,0,0},         /* m */
11481    {0,0,0,0,0,0,0,0,0},       /* mutex */
11482    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
11483    (void*)0,                  /* pHeap */
11484    0,                         /* nHeap */
11485    0, 0,                      /* mnHeap, mxHeap */
11486    (void*)0,                  /* pScratch */
11487    0,                         /* szScratch */
11488    0,                         /* nScratch */
11489    (void*)0,                  /* pPage */
11490    0,                         /* szPage */
11491    0,                         /* nPage */
11492    0,                         /* mxParserStack */
11493    0,                         /* sharedCacheEnabled */
11494    /* All the rest should always be initialized to zero */
11495    0,                         /* isInit */
11496    0,                         /* inProgress */
11497    0,                         /* isMutexInit */
11498    0,                         /* isMallocInit */
11499    0,                         /* isPCacheInit */
11500    0,                         /* pInitMutex */
11501    0,                         /* nRefInitMutex */
11502    0,                         /* xLog */
11503    0,                         /* pLogArg */
11504 };
11505
11506
11507 /*
11508 ** Hash table for global functions - functions common to all
11509 ** database connections.  After initialization, this table is
11510 ** read-only.
11511 */
11512 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11513
11514 /*
11515 ** Constant tokens for values 0 and 1.
11516 */
11517 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
11518    { "0", 1 },
11519    { "1", 1 }
11520 };
11521
11522
11523 /*
11524 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
11525 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
11526 ** the database page that contains the pending byte.  It never attempts
11527 ** to read or write that page.  The pending byte page is set assign
11528 ** for use by the VFS layers as space for managing file locks.
11529 **
11530 ** During testing, it is often desirable to move the pending byte to
11531 ** a different position in the file.  This allows code that has to
11532 ** deal with the pending byte to run on files that are much smaller
11533 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
11534 ** move the pending byte.
11535 **
11536 ** IMPORTANT:  Changing the pending byte to any value other than
11537 ** 0x40000000 results in an incompatible database file format!
11538 ** Changing the pending byte during operating results in undefined
11539 ** and dileterious behavior.
11540 */
11541 #ifndef SQLITE_OMIT_WSD
11542 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
11543 #endif
11544
11545 /*
11546 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
11547 ** created by mkopcodeh.awk during compilation.  Data is obtained
11548 ** from the comments following the "case OP_xxxx:" statements in
11549 ** the vdbe.c file.  
11550 */
11551 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
11552
11553 /************** End of global.c **********************************************/
11554 /************** Begin file ctime.c *******************************************/
11555 /*
11556 ** 2010 February 23
11557 **
11558 ** The author disclaims copyright to this source code.  In place of
11559 ** a legal notice, here is a blessing:
11560 **
11561 **    May you do good and not evil.
11562 **    May you find forgiveness for yourself and forgive others.
11563 **    May you share freely, never taking more than you give.
11564 **
11565 *************************************************************************
11566 **
11567 ** This file implements routines used to report what compile-time options
11568 ** SQLite was built with.
11569 */
11570
11571 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
11572
11573
11574 /*
11575 ** An array of names of all compile-time options.  This array should 
11576 ** be sorted A-Z.
11577 **
11578 ** This array looks large, but in a typical installation actually uses
11579 ** only a handful of compile-time options, so most times this array is usually
11580 ** rather short and uses little memory space.
11581 */
11582 static const char * const azCompileOpt[] = {
11583
11584 /* These macros are provided to "stringify" the value of the define
11585 ** for those options in which the value is meaningful. */
11586 #define CTIMEOPT_VAL_(opt) #opt
11587 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
11588
11589 #ifdef SQLITE_32BIT_ROWID
11590   "32BIT_ROWID",
11591 #endif
11592 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11593   "4_BYTE_ALIGNED_MALLOC",
11594 #endif
11595 #ifdef SQLITE_CASE_SENSITIVE_LIKE
11596   "CASE_SENSITIVE_LIKE",
11597 #endif
11598 #ifdef SQLITE_CHECK_PAGES
11599   "CHECK_PAGES",
11600 #endif
11601 #ifdef SQLITE_COVERAGE_TEST
11602   "COVERAGE_TEST",
11603 #endif
11604 #ifdef SQLITE_DEBUG
11605   "DEBUG",
11606 #endif
11607 #ifdef SQLITE_DEFAULT_LOCKING_MODE
11608   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
11609 #endif
11610 #ifdef SQLITE_DISABLE_DIRSYNC
11611   "DISABLE_DIRSYNC",
11612 #endif
11613 #ifdef SQLITE_DISABLE_LFS
11614   "DISABLE_LFS",
11615 #endif
11616 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11617   "ENABLE_ATOMIC_WRITE",
11618 #endif
11619 #ifdef SQLITE_ENABLE_CEROD
11620   "ENABLE_CEROD",
11621 #endif
11622 #ifdef SQLITE_ENABLE_COLUMN_METADATA
11623   "ENABLE_COLUMN_METADATA",
11624 #endif
11625 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
11626   "ENABLE_EXPENSIVE_ASSERT",
11627 #endif
11628 #ifdef SQLITE_ENABLE_FTS1
11629   "ENABLE_FTS1",
11630 #endif
11631 #ifdef SQLITE_ENABLE_FTS2
11632   "ENABLE_FTS2",
11633 #endif
11634 #ifdef SQLITE_ENABLE_FTS3
11635   "ENABLE_FTS3",
11636 #endif
11637 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
11638   "ENABLE_FTS3_PARENTHESIS",
11639 #endif
11640 #ifdef SQLITE_ENABLE_FTS4
11641   "ENABLE_FTS4",
11642 #endif
11643 #ifdef SQLITE_ENABLE_ICU
11644   "ENABLE_ICU",
11645 #endif
11646 #ifdef SQLITE_ENABLE_IOTRACE
11647   "ENABLE_IOTRACE",
11648 #endif
11649 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
11650   "ENABLE_LOAD_EXTENSION",
11651 #endif
11652 #ifdef SQLITE_ENABLE_LOCKING_STYLE
11653   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
11654 #endif
11655 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
11656   "ENABLE_MEMORY_MANAGEMENT",
11657 #endif
11658 #ifdef SQLITE_ENABLE_MEMSYS3
11659   "ENABLE_MEMSYS3",
11660 #endif
11661 #ifdef SQLITE_ENABLE_MEMSYS5
11662   "ENABLE_MEMSYS5",
11663 #endif
11664 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
11665   "ENABLE_OVERSIZE_CELL_CHECK",
11666 #endif
11667 #ifdef SQLITE_ENABLE_RTREE
11668   "ENABLE_RTREE",
11669 #endif
11670 #ifdef SQLITE_ENABLE_STAT2
11671   "ENABLE_STAT2",
11672 #endif
11673 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11674   "ENABLE_UNLOCK_NOTIFY",
11675 #endif
11676 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
11677   "ENABLE_UPDATE_DELETE_LIMIT",
11678 #endif
11679 #ifdef SQLITE_HAS_CODEC
11680   "HAS_CODEC",
11681 #endif
11682 #ifdef SQLITE_HAVE_ISNAN
11683   "HAVE_ISNAN",
11684 #endif
11685 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11686   "HOMEGROWN_RECURSIVE_MUTEX",
11687 #endif
11688 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11689   "IGNORE_AFP_LOCK_ERRORS",
11690 #endif
11691 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11692   "IGNORE_FLOCK_LOCK_ERRORS",
11693 #endif
11694 #ifdef SQLITE_INT64_TYPE
11695   "INT64_TYPE",
11696 #endif
11697 #ifdef SQLITE_LOCK_TRACE
11698   "LOCK_TRACE",
11699 #endif
11700 #ifdef SQLITE_MEMDEBUG
11701   "MEMDEBUG",
11702 #endif
11703 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11704   "MIXED_ENDIAN_64BIT_FLOAT",
11705 #endif
11706 #ifdef SQLITE_NO_SYNC
11707   "NO_SYNC",
11708 #endif
11709 #ifdef SQLITE_OMIT_ALTERTABLE
11710   "OMIT_ALTERTABLE",
11711 #endif
11712 #ifdef SQLITE_OMIT_ANALYZE
11713   "OMIT_ANALYZE",
11714 #endif
11715 #ifdef SQLITE_OMIT_ATTACH
11716   "OMIT_ATTACH",
11717 #endif
11718 #ifdef SQLITE_OMIT_AUTHORIZATION
11719   "OMIT_AUTHORIZATION",
11720 #endif
11721 #ifdef SQLITE_OMIT_AUTOINCREMENT
11722   "OMIT_AUTOINCREMENT",
11723 #endif
11724 #ifdef SQLITE_OMIT_AUTOINIT
11725   "OMIT_AUTOINIT",
11726 #endif
11727 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
11728   "OMIT_AUTOMATIC_INDEX",
11729 #endif
11730 #ifdef SQLITE_OMIT_AUTOVACUUM
11731   "OMIT_AUTOVACUUM",
11732 #endif
11733 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11734   "OMIT_BETWEEN_OPTIMIZATION",
11735 #endif
11736 #ifdef SQLITE_OMIT_BLOB_LITERAL
11737   "OMIT_BLOB_LITERAL",
11738 #endif
11739 #ifdef SQLITE_OMIT_BTREECOUNT
11740   "OMIT_BTREECOUNT",
11741 #endif
11742 #ifdef SQLITE_OMIT_BUILTIN_TEST
11743   "OMIT_BUILTIN_TEST",
11744 #endif
11745 #ifdef SQLITE_OMIT_CAST
11746   "OMIT_CAST",
11747 #endif
11748 #ifdef SQLITE_OMIT_CHECK
11749   "OMIT_CHECK",
11750 #endif
11751 /* // redundant
11752 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11753 **   "OMIT_COMPILEOPTION_DIAGS",
11754 ** #endif
11755 */
11756 #ifdef SQLITE_OMIT_COMPLETE
11757   "OMIT_COMPLETE",
11758 #endif
11759 #ifdef SQLITE_OMIT_COMPOUND_SELECT
11760   "OMIT_COMPOUND_SELECT",
11761 #endif
11762 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11763   "OMIT_DATETIME_FUNCS",
11764 #endif
11765 #ifdef SQLITE_OMIT_DECLTYPE
11766   "OMIT_DECLTYPE",
11767 #endif
11768 #ifdef SQLITE_OMIT_DEPRECATED
11769   "OMIT_DEPRECATED",
11770 #endif
11771 #ifdef SQLITE_OMIT_DISKIO
11772   "OMIT_DISKIO",
11773 #endif
11774 #ifdef SQLITE_OMIT_EXPLAIN
11775   "OMIT_EXPLAIN",
11776 #endif
11777 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
11778   "OMIT_FLAG_PRAGMAS",
11779 #endif
11780 #ifdef SQLITE_OMIT_FLOATING_POINT
11781   "OMIT_FLOATING_POINT",
11782 #endif
11783 #ifdef SQLITE_OMIT_FOREIGN_KEY
11784   "OMIT_FOREIGN_KEY",
11785 #endif
11786 #ifdef SQLITE_OMIT_GET_TABLE
11787   "OMIT_GET_TABLE",
11788 #endif
11789 #ifdef SQLITE_OMIT_INCRBLOB
11790   "OMIT_INCRBLOB",
11791 #endif
11792 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
11793   "OMIT_INTEGRITY_CHECK",
11794 #endif
11795 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
11796   "OMIT_LIKE_OPTIMIZATION",
11797 #endif
11798 #ifdef SQLITE_OMIT_LOAD_EXTENSION
11799   "OMIT_LOAD_EXTENSION",
11800 #endif
11801 #ifdef SQLITE_OMIT_LOCALTIME
11802   "OMIT_LOCALTIME",
11803 #endif
11804 #ifdef SQLITE_OMIT_LOOKASIDE
11805   "OMIT_LOOKASIDE",
11806 #endif
11807 #ifdef SQLITE_OMIT_MEMORYDB
11808   "OMIT_MEMORYDB",
11809 #endif
11810 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
11811   "OMIT_OR_OPTIMIZATION",
11812 #endif
11813 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
11814   "OMIT_PAGER_PRAGMAS",
11815 #endif
11816 #ifdef SQLITE_OMIT_PRAGMA
11817   "OMIT_PRAGMA",
11818 #endif
11819 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
11820   "OMIT_PROGRESS_CALLBACK",
11821 #endif
11822 #ifdef SQLITE_OMIT_QUICKBALANCE
11823   "OMIT_QUICKBALANCE",
11824 #endif
11825 #ifdef SQLITE_OMIT_REINDEX
11826   "OMIT_REINDEX",
11827 #endif
11828 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
11829   "OMIT_SCHEMA_PRAGMAS",
11830 #endif
11831 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
11832   "OMIT_SCHEMA_VERSION_PRAGMAS",
11833 #endif
11834 #ifdef SQLITE_OMIT_SHARED_CACHE
11835   "OMIT_SHARED_CACHE",
11836 #endif
11837 #ifdef SQLITE_OMIT_SUBQUERY
11838   "OMIT_SUBQUERY",
11839 #endif
11840 #ifdef SQLITE_OMIT_TCL_VARIABLE
11841   "OMIT_TCL_VARIABLE",
11842 #endif
11843 #ifdef SQLITE_OMIT_TEMPDB
11844   "OMIT_TEMPDB",
11845 #endif
11846 #ifdef SQLITE_OMIT_TRACE
11847   "OMIT_TRACE",
11848 #endif
11849 #ifdef SQLITE_OMIT_TRIGGER
11850   "OMIT_TRIGGER",
11851 #endif
11852 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
11853   "OMIT_TRUNCATE_OPTIMIZATION",
11854 #endif
11855 #ifdef SQLITE_OMIT_UTF16
11856   "OMIT_UTF16",
11857 #endif
11858 #ifdef SQLITE_OMIT_VACUUM
11859   "OMIT_VACUUM",
11860 #endif
11861 #ifdef SQLITE_OMIT_VIEW
11862   "OMIT_VIEW",
11863 #endif
11864 #ifdef SQLITE_OMIT_VIRTUALTABLE
11865   "OMIT_VIRTUALTABLE",
11866 #endif
11867 #ifdef SQLITE_OMIT_WAL
11868   "OMIT_WAL",
11869 #endif
11870 #ifdef SQLITE_OMIT_WSD
11871   "OMIT_WSD",
11872 #endif
11873 #ifdef SQLITE_OMIT_XFER_OPT
11874   "OMIT_XFER_OPT",
11875 #endif
11876 #ifdef SQLITE_PERFORMANCE_TRACE
11877   "PERFORMANCE_TRACE",
11878 #endif
11879 #ifdef SQLITE_PROXY_DEBUG
11880   "PROXY_DEBUG",
11881 #endif
11882 #ifdef SQLITE_SECURE_DELETE
11883   "SECURE_DELETE",
11884 #endif
11885 #ifdef SQLITE_SMALL_STACK
11886   "SMALL_STACK",
11887 #endif
11888 #ifdef SQLITE_SOUNDEX
11889   "SOUNDEX",
11890 #endif
11891 #ifdef SQLITE_TCL
11892   "TCL",
11893 #endif
11894 #ifdef SQLITE_TEMP_STORE
11895   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
11896 #endif
11897 #ifdef SQLITE_TEST
11898   "TEST",
11899 #endif
11900 #ifdef SQLITE_THREADSAFE
11901   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
11902 #endif
11903 #ifdef SQLITE_USE_ALLOCA
11904   "USE_ALLOCA",
11905 #endif
11906 #ifdef SQLITE_ZERO_MALLOC
11907   "ZERO_MALLOC"
11908 #endif
11909 };
11910
11911 /*
11912 ** Given the name of a compile-time option, return true if that option
11913 ** was used and false if not.
11914 **
11915 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
11916 ** is not required for a match.
11917 */
11918 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
11919   int i, n;
11920   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
11921   n = sqlite3Strlen30(zOptName);
11922
11923   /* Since ArraySize(azCompileOpt) is normally in single digits, a
11924   ** linear search is adequate.  No need for a binary search. */
11925   for(i=0; i<ArraySize(azCompileOpt); i++){
11926     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
11927        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
11928   }
11929   return 0;
11930 }
11931
11932 /*
11933 ** Return the N-th compile-time option string.  If N is out of range,
11934 ** return a NULL pointer.
11935 */
11936 SQLITE_API const char *sqlite3_compileoption_get(int N){
11937   if( N>=0 && N<ArraySize(azCompileOpt) ){
11938     return azCompileOpt[N];
11939   }
11940   return 0;
11941 }
11942
11943 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
11944
11945 /************** End of ctime.c ***********************************************/
11946 /************** Begin file status.c ******************************************/
11947 /*
11948 ** 2008 June 18
11949 **
11950 ** The author disclaims copyright to this source code.  In place of
11951 ** a legal notice, here is a blessing:
11952 **
11953 **    May you do good and not evil.
11954 **    May you find forgiveness for yourself and forgive others.
11955 **    May you share freely, never taking more than you give.
11956 **
11957 *************************************************************************
11958 **
11959 ** This module implements the sqlite3_status() interface and related
11960 ** functionality.
11961 */
11962 /************** Include vdbeInt.h in the middle of status.c ******************/
11963 /************** Begin file vdbeInt.h *****************************************/
11964 /*
11965 ** 2003 September 6
11966 **
11967 ** The author disclaims copyright to this source code.  In place of
11968 ** a legal notice, here is a blessing:
11969 **
11970 **    May you do good and not evil.
11971 **    May you find forgiveness for yourself and forgive others.
11972 **    May you share freely, never taking more than you give.
11973 **
11974 *************************************************************************
11975 ** This is the header file for information that is private to the
11976 ** VDBE.  This information used to all be at the top of the single
11977 ** source code file "vdbe.c".  When that file became too big (over
11978 ** 6000 lines long) it was split up into several smaller files and
11979 ** this header information was factored out.
11980 */
11981 #ifndef _VDBEINT_H_
11982 #define _VDBEINT_H_
11983
11984 /*
11985 ** SQL is translated into a sequence of instructions to be
11986 ** executed by a virtual machine.  Each instruction is an instance
11987 ** of the following structure.
11988 */
11989 typedef struct VdbeOp Op;
11990
11991 /*
11992 ** Boolean values
11993 */
11994 typedef unsigned char Bool;
11995
11996 /*
11997 ** A cursor is a pointer into a single BTree within a database file.
11998 ** The cursor can seek to a BTree entry with a particular key, or
11999 ** loop over all entries of the Btree.  You can also insert new BTree
12000 ** entries or retrieve the key or data from the entry that the cursor
12001 ** is currently pointing to.
12002 ** 
12003 ** Every cursor that the virtual machine has open is represented by an
12004 ** instance of the following structure.
12005 **
12006 ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
12007 ** really a single row that represents the NEW or OLD pseudo-table of
12008 ** a row trigger.  The data for the row is stored in VdbeCursor.pData and
12009 ** the rowid is in VdbeCursor.iKey.
12010 */
12011 struct VdbeCursor {
12012   BtCursor *pCursor;    /* The cursor structure of the backend */
12013   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12014   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12015   Bool zeroed;          /* True if zeroed out and ready for reuse */
12016   Bool rowidIsValid;    /* True if lastRowid is valid */
12017   Bool atFirst;         /* True if pointing to first entry */
12018   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12019   Bool nullRow;         /* True if pointing to a row with no data */
12020   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12021   Bool isTable;         /* True if a table requiring integer keys */
12022   Bool isIndex;         /* True if an index containing keys only - no data */
12023   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
12024   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12025   Btree *pBt;           /* Separate file holding temporary table */
12026   int pseudoTableReg;   /* Register holding pseudotable content. */
12027   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12028   int nField;           /* Number of fields in the header */
12029   i64 seqCount;         /* Sequence counter */
12030   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12031   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12032
12033   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
12034   ** OP_IsUnique opcode on this cursor. */
12035   int seekResult;
12036
12037   /* Cached information about the header for the data record that the
12038   ** cursor is currently pointing to.  Only valid if cacheStatus matches
12039   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
12040   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12041   ** the cache is out of date.
12042   **
12043   ** aRow might point to (ephemeral) data for the current row, or it might
12044   ** be NULL.
12045   */
12046   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
12047   int payloadSize;      /* Total number of bytes in the record */
12048   u32 *aType;           /* Type values for all entries in the record */
12049   u32 *aOffset;         /* Cached offsets to the start of each columns data */
12050   u8 *aRow;             /* Data for the current row, if all on one page */
12051 };
12052 typedef struct VdbeCursor VdbeCursor;
12053
12054 /*
12055 ** When a sub-program is executed (OP_Program), a structure of this type
12056 ** is allocated to store the current value of the program counter, as
12057 ** well as the current memory cell array and various other frame specific
12058 ** values stored in the Vdbe struct. When the sub-program is finished, 
12059 ** these values are copied back to the Vdbe from the VdbeFrame structure,
12060 ** restoring the state of the VM to as it was before the sub-program
12061 ** began executing.
12062 **
12063 ** The memory for a VdbeFrame object is allocated and managed by a memory
12064 ** cell in the parent (calling) frame. When the memory cell is deleted or
12065 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12066 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12067 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12068 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
12069 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12070 ** child frame are released.
12071 **
12072 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12073 ** set to NULL if the currently executing frame is the main program.
12074 */
12075 typedef struct VdbeFrame VdbeFrame;
12076 struct VdbeFrame {
12077   Vdbe *v;                /* VM this frame belongs to */
12078   int pc;                 /* Program Counter in parent (calling) frame */
12079   Op *aOp;                /* Program instructions for parent frame */
12080   int nOp;                /* Size of aOp array */
12081   Mem *aMem;              /* Array of memory cells for parent frame */
12082   int nMem;               /* Number of entries in aMem */
12083   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
12084   u16 nCursor;            /* Number of entries in apCsr */
12085   void *token;            /* Copy of SubProgram.token */
12086   int nChildMem;          /* Number of memory cells for child frame */
12087   int nChildCsr;          /* Number of cursors for child frame */
12088   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
12089   int nChange;            /* Statement changes (Vdbe.nChanges)     */
12090   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
12091 };
12092
12093 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12094
12095 /*
12096 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12097 */
12098 #define CACHE_STALE 0
12099
12100 /*
12101 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12102 ** structures. Each Mem struct may cache multiple representations (string,
12103 ** integer etc.) of the same value.  A value (and therefore Mem structure)
12104 ** has the following properties:
12105 **
12106 ** Each value has a manifest type. The manifest type of the value stored
12107 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
12108 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
12109 ** SQLITE_BLOB.
12110 */
12111 struct Mem {
12112   union {
12113     i64 i;              /* Integer value. */
12114     int nZero;          /* Used when bit MEM_Zero is set in flags */
12115     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12116     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
12117     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
12118   } u;
12119   double r;           /* Real value */
12120   sqlite3 *db;        /* The associated database connection */
12121   char *z;            /* String or BLOB value */
12122   int n;              /* Number of characters in string value, excluding '\0' */
12123   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12124   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12125   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12126 #ifdef SQLITE_DEBUG
12127   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
12128   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
12129 #endif
12130   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12131   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
12132 };
12133
12134 /* One or more of the following flags are set to indicate the validOK
12135 ** representations of the value stored in the Mem struct.
12136 **
12137 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12138 ** No other flags may be set in this case.
12139 **
12140 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12141 ** Usually this is encoded in the same unicode encoding as the main
12142 ** database (see below for exceptions). If the MEM_Term flag is also
12143 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
12144 ** flags may coexist with the MEM_Str flag.
12145 **
12146 ** Multiple of these values can appear in Mem.flags.  But only one
12147 ** at a time can appear in Mem.type.
12148 */
12149 #define MEM_Null      0x0001   /* Value is NULL */
12150 #define MEM_Str       0x0002   /* Value is a string */
12151 #define MEM_Int       0x0004   /* Value is an integer */
12152 #define MEM_Real      0x0008   /* Value is a real number */
12153 #define MEM_Blob      0x0010   /* Value is a BLOB */
12154 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
12155 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
12156 #define MEM_Invalid   0x0080   /* Value is undefined */
12157 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
12158
12159 /* Whenever Mem contains a valid string or blob representation, one of
12160 ** the following flags must be set to determine the memory management
12161 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
12162 ** string is \000 or \u0000 terminated
12163 */
12164 #define MEM_Term      0x0200   /* String rep is nul terminated */
12165 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
12166 #define MEM_Static    0x0800   /* Mem.z points to a static string */
12167 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
12168 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
12169 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
12170 #ifdef SQLITE_OMIT_INCRBLOB
12171   #undef MEM_Zero
12172   #define MEM_Zero 0x0000
12173 #endif
12174
12175 /*
12176 ** Clear any existing type flags from a Mem and replace them with f
12177 */
12178 #define MemSetTypeFlag(p, f) \
12179    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12180
12181 /*
12182 ** Return true if a memory cell is not marked as invalid.  This macro
12183 ** is for use inside assert() statements only.
12184 */
12185 #ifdef SQLITE_DEBUG
12186 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
12187 #endif
12188
12189
12190 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12191 ** additional information about auxiliary information bound to arguments
12192 ** of the function.  This is used to implement the sqlite3_get_auxdata()
12193 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
12194 ** that can be associated with a constant argument to a function.  This
12195 ** allows functions such as "regexp" to compile their constant regular
12196 ** expression argument once and reused the compiled code for multiple
12197 ** invocations.
12198 */
12199 struct VdbeFunc {
12200   FuncDef *pFunc;               /* The definition of the function */
12201   int nAux;                     /* Number of entries allocated for apAux[] */
12202   struct AuxData {
12203     void *pAux;                   /* Aux data for the i-th argument */
12204     void (*xDelete)(void *);      /* Destructor for the aux data */
12205   } apAux[1];                   /* One slot for each function argument */
12206 };
12207
12208 /*
12209 ** The "context" argument for a installable function.  A pointer to an
12210 ** instance of this structure is the first argument to the routines used
12211 ** implement the SQL functions.
12212 **
12213 ** There is a typedef for this structure in sqlite.h.  So all routines,
12214 ** even the public interface to SQLite, can use a pointer to this structure.
12215 ** But this file is the only place where the internal details of this
12216 ** structure are known.
12217 **
12218 ** This structure is defined inside of vdbeInt.h because it uses substructures
12219 ** (Mem) which are only defined there.
12220 */
12221 struct sqlite3_context {
12222   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
12223   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
12224   Mem s;                /* The return value is stored here */
12225   Mem *pMem;            /* Memory cell used to store aggregate context */
12226   int isError;          /* Error code returned by the function. */
12227   CollSeq *pColl;       /* Collating sequence */
12228 };
12229
12230 /*
12231 ** A Set structure is used for quick testing to see if a value
12232 ** is part of a small set.  Sets are used to implement code like
12233 ** this:
12234 **            x.y IN ('hi','hoo','hum')
12235 */
12236 typedef struct Set Set;
12237 struct Set {
12238   Hash hash;             /* A set is just a hash table */
12239   HashElem *prev;        /* Previously accessed hash elemen */
12240 };
12241
12242 /*
12243 ** An instance of the virtual machine.  This structure contains the complete
12244 ** state of the virtual machine.
12245 **
12246 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
12247 ** is really a pointer to an instance of this structure.
12248 **
12249 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12250 ** any virtual table method invocations made by the vdbe program. It is
12251 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12252 ** variable is used for two purposes: to allow xDestroy methods to execute
12253 ** "DROP TABLE" statements and to prevent some nasty side effects of
12254 ** malloc failure when SQLite is invoked recursively by a virtual table 
12255 ** method function.
12256 */
12257 struct Vdbe {
12258   sqlite3 *db;            /* The database connection that owns this statement */
12259   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
12260   int nOp;                /* Number of instructions in the program */
12261   int nOpAlloc;           /* Number of slots allocated for aOp[] */
12262   Op *aOp;                /* Space to hold the virtual machine's program */
12263   int nLabel;             /* Number of labels used */
12264   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
12265   int *aLabel;            /* Space to hold the labels */
12266   Mem **apArg;            /* Arguments to currently executing user function */
12267   Mem *aColName;          /* Column names to return */
12268   Mem *pResultSet;        /* Pointer to an array of results */
12269   u16 nResColumn;         /* Number of columns in one row of the result set */
12270   u16 nCursor;            /* Number of slots in apCsr[] */
12271   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
12272   u8 errorAction;         /* Recovery action to do in case of an error */
12273   u8 okVar;               /* True if azVar[] has been initialized */
12274   ynVar nVar;             /* Number of entries in aVar[] */
12275   Mem *aVar;              /* Values for the OP_Variable opcode. */
12276   char **azVar;           /* Name of variables */
12277   u32 magic;              /* Magic number for sanity checking */
12278   int nMem;               /* Number of memory locations currently allocated */
12279   Mem *aMem;              /* The memory locations */
12280   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
12281   int pc;                 /* The program counter */
12282   int rc;                 /* Value to return */
12283   char *zErrMsg;          /* Error message written here */
12284   u8 explain;             /* True if EXPLAIN present on SQL command */
12285   u8 changeCntOn;         /* True to update the change-counter */
12286   u8 expired;             /* True if the VM needs to be recompiled */
12287   u8 runOnlyOnce;         /* Automatically expire on reset */
12288   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
12289   u8 inVtabMethod;        /* See comments above */
12290   u8 usesStmtJournal;     /* True if uses a statement journal */
12291   u8 readOnly;            /* True for read-only statements */
12292   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
12293   int nChange;            /* Number of db changes made since last reset */
12294   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
12295   i64 startTime;          /* Time when query started - used for profiling */
12296   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
12297   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
12298   char *zSql;             /* Text of the SQL statement that generated this */
12299   void *pFree;            /* Free this when deleting the vdbe */
12300   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
12301   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
12302   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
12303 #ifdef SQLITE_DEBUG
12304   FILE *trace;            /* Write an execution trace here, if not NULL */
12305 #endif
12306   VdbeFrame *pFrame;      /* Parent frame */
12307   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
12308   int nFrame;             /* Number of frames in pFrame list */
12309   u32 expmask;            /* Binding to these vars invalidates VM */
12310   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
12311 };
12312
12313 /*
12314 ** The following are allowed values for Vdbe.magic
12315 */
12316 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
12317 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
12318 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
12319 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
12320
12321 /*
12322 ** Function prototypes
12323 */
12324 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12325 void sqliteVdbePopStack(Vdbe*,int);
12326 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12327 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12328 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12329 #endif
12330 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12331 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12332 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12333 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12334 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12335
12336 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12337 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12338 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12339 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12340 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12341 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12342 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12343 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12344 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12345 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12346 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12347 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12348 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12349 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12350 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12351 #ifdef SQLITE_OMIT_FLOATING_POINT
12352 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12353 #else
12354 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
12355 #endif
12356 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12357 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12358 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12359 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12360 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12361 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12362 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12363 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12364 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12365 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12366 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12367 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12368 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12369 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12370 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12371 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12372 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12373 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12374 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12375 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12376 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12377
12378 #ifdef SQLITE_DEBUG
12379 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12380 #endif
12381
12382 #ifndef SQLITE_OMIT_FOREIGN_KEY
12383 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12384 #else
12385 # define sqlite3VdbeCheckFk(p,i) 0
12386 #endif
12387
12388 #ifndef SQLITE_OMIT_SHARED_CACHE
12389 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
12390 #else
12391 # define sqlite3VdbeMutexArrayEnter(p)
12392 #endif
12393
12394 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12395 #ifdef SQLITE_DEBUG
12396 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
12397 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12398 #endif
12399 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12400
12401 #ifndef SQLITE_OMIT_INCRBLOB
12402 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
12403 #else
12404   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12405 #endif
12406
12407 #endif /* !defined(_VDBEINT_H_) */
12408
12409 /************** End of vdbeInt.h *********************************************/
12410 /************** Continuing where we left off in status.c *********************/
12411
12412 /*
12413 ** Variables in which to record status information.
12414 */
12415 typedef struct sqlite3StatType sqlite3StatType;
12416 static SQLITE_WSD struct sqlite3StatType {
12417   int nowValue[10];         /* Current value */
12418   int mxValue[10];          /* Maximum value */
12419 } sqlite3Stat = { {0,}, {0,} };
12420
12421
12422 /* The "wsdStat" macro will resolve to the status information
12423 ** state vector.  If writable static data is unsupported on the target,
12424 ** we have to locate the state vector at run-time.  In the more common
12425 ** case where writable static data is supported, wsdStat can refer directly
12426 ** to the "sqlite3Stat" state vector declared above.
12427 */
12428 #ifdef SQLITE_OMIT_WSD
12429 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
12430 # define wsdStat x[0]
12431 #else
12432 # define wsdStatInit
12433 # define wsdStat sqlite3Stat
12434 #endif
12435
12436 /*
12437 ** Return the current value of a status parameter.
12438 */
12439 SQLITE_PRIVATE int sqlite3StatusValue(int op){
12440   wsdStatInit;
12441   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12442   return wsdStat.nowValue[op];
12443 }
12444
12445 /*
12446 ** Add N to the value of a status record.  It is assumed that the
12447 ** caller holds appropriate locks.
12448 */
12449 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
12450   wsdStatInit;
12451   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12452   wsdStat.nowValue[op] += N;
12453   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12454     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12455   }
12456 }
12457
12458 /*
12459 ** Set the value of a status to X.
12460 */
12461 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
12462   wsdStatInit;
12463   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
12464   wsdStat.nowValue[op] = X;
12465   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
12466     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12467   }
12468 }
12469
12470 /*
12471 ** Query status information.
12472 **
12473 ** This implementation assumes that reading or writing an aligned
12474 ** 32-bit integer is an atomic operation.  If that assumption is not true,
12475 ** then this routine is not threadsafe.
12476 */
12477 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
12478   wsdStatInit;
12479   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
12480     return SQLITE_MISUSE_BKPT;
12481   }
12482   *pCurrent = wsdStat.nowValue[op];
12483   *pHighwater = wsdStat.mxValue[op];
12484   if( resetFlag ){
12485     wsdStat.mxValue[op] = wsdStat.nowValue[op];
12486   }
12487   return SQLITE_OK;
12488 }
12489
12490 /*
12491 ** Query status information for a single database connection
12492 */
12493 SQLITE_API int sqlite3_db_status(
12494   sqlite3 *db,          /* The database connection whose status is desired */
12495   int op,               /* Status verb */
12496   int *pCurrent,        /* Write current value here */
12497   int *pHighwater,      /* Write high-water mark here */
12498   int resetFlag         /* Reset high-water mark if true */
12499 ){
12500   int rc = SQLITE_OK;   /* Return code */
12501   sqlite3_mutex_enter(db->mutex);
12502   switch( op ){
12503     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
12504       *pCurrent = db->lookaside.nOut;
12505       *pHighwater = db->lookaside.mxOut;
12506       if( resetFlag ){
12507         db->lookaside.mxOut = db->lookaside.nOut;
12508       }
12509       break;
12510     }
12511
12512     /* 
12513     ** Return an approximation for the amount of memory currently used
12514     ** by all pagers associated with the given database connection.  The
12515     ** highwater mark is meaningless and is returned as zero.
12516     */
12517     case SQLITE_DBSTATUS_CACHE_USED: {
12518       int totalUsed = 0;
12519       int i;
12520       sqlite3BtreeEnterAll(db);
12521       for(i=0; i<db->nDb; i++){
12522         Btree *pBt = db->aDb[i].pBt;
12523         if( pBt ){
12524           Pager *pPager = sqlite3BtreePager(pBt);
12525           totalUsed += sqlite3PagerMemUsed(pPager);
12526         }
12527       }
12528       sqlite3BtreeLeaveAll(db);
12529       *pCurrent = totalUsed;
12530       *pHighwater = 0;
12531       break;
12532     }
12533
12534     /*
12535     ** *pCurrent gets an accurate estimate of the amount of memory used
12536     ** to store the schema for all databases (main, temp, and any ATTACHed
12537     ** databases.  *pHighwater is set to zero.
12538     */
12539     case SQLITE_DBSTATUS_SCHEMA_USED: {
12540       int i;                      /* Used to iterate through schemas */
12541       int nByte = 0;              /* Used to accumulate return value */
12542
12543       db->pnBytesFreed = &nByte;
12544       for(i=0; i<db->nDb; i++){
12545         Schema *pSchema = db->aDb[i].pSchema;
12546         if( ALWAYS(pSchema!=0) ){
12547           HashElem *p;
12548
12549           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
12550               pSchema->tblHash.count 
12551             + pSchema->trigHash.count
12552             + pSchema->idxHash.count
12553             + pSchema->fkeyHash.count
12554           );
12555           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
12556           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
12557           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
12558           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
12559
12560           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
12561             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
12562           }
12563           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
12564             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
12565           }
12566         }
12567       }
12568       db->pnBytesFreed = 0;
12569
12570       *pHighwater = 0;
12571       *pCurrent = nByte;
12572       break;
12573     }
12574
12575     /*
12576     ** *pCurrent gets an accurate estimate of the amount of memory used
12577     ** to store all prepared statements.
12578     ** *pHighwater is set to zero.
12579     */
12580     case SQLITE_DBSTATUS_STMT_USED: {
12581       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
12582       int nByte = 0;              /* Used to accumulate return value */
12583
12584       db->pnBytesFreed = &nByte;
12585       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
12586         sqlite3VdbeDeleteObject(db, pVdbe);
12587       }
12588       db->pnBytesFreed = 0;
12589
12590       *pHighwater = 0;
12591       *pCurrent = nByte;
12592
12593       break;
12594     }
12595
12596     default: {
12597       rc = SQLITE_ERROR;
12598     }
12599   }
12600   sqlite3_mutex_leave(db->mutex);
12601   return rc;
12602 }
12603
12604 /************** End of status.c **********************************************/
12605 /************** Begin file date.c ********************************************/
12606 /*
12607 ** 2003 October 31
12608 **
12609 ** The author disclaims copyright to this source code.  In place of
12610 ** a legal notice, here is a blessing:
12611 **
12612 **    May you do good and not evil.
12613 **    May you find forgiveness for yourself and forgive others.
12614 **    May you share freely, never taking more than you give.
12615 **
12616 *************************************************************************
12617 ** This file contains the C functions that implement date and time
12618 ** functions for SQLite.  
12619 **
12620 ** There is only one exported symbol in this file - the function
12621 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
12622 ** All other code has file scope.
12623 **
12624 ** SQLite processes all times and dates as Julian Day numbers.  The
12625 ** dates and times are stored as the number of days since noon
12626 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
12627 ** calendar system. 
12628 **
12629 ** 1970-01-01 00:00:00 is JD 2440587.5
12630 ** 2000-01-01 00:00:00 is JD 2451544.5
12631 **
12632 ** This implemention requires years to be expressed as a 4-digit number
12633 ** which means that only dates between 0000-01-01 and 9999-12-31 can
12634 ** be represented, even though julian day numbers allow a much wider
12635 ** range of dates.
12636 **
12637 ** The Gregorian calendar system is used for all dates and times,
12638 ** even those that predate the Gregorian calendar.  Historians usually
12639 ** use the Julian calendar for dates prior to 1582-10-15 and for some
12640 ** dates afterwards, depending on locale.  Beware of this difference.
12641 **
12642 ** The conversion algorithms are implemented based on descriptions
12643 ** in the following text:
12644 **
12645 **      Jean Meeus
12646 **      Astronomical Algorithms, 2nd Edition, 1998
12647 **      ISBM 0-943396-61-1
12648 **      Willmann-Bell, Inc
12649 **      Richmond, Virginia (USA)
12650 */
12651 #include <time.h>
12652
12653 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12654
12655 /*
12656 ** On recent Windows platforms, the localtime_s() function is available
12657 ** as part of the "Secure CRT". It is essentially equivalent to 
12658 ** localtime_r() available under most POSIX platforms, except that the 
12659 ** order of the parameters is reversed.
12660 **
12661 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
12662 **
12663 ** If the user has not indicated to use localtime_r() or localtime_s()
12664 ** already, check for an MSVC build environment that provides 
12665 ** localtime_s().
12666 */
12667 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
12668      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
12669 #define HAVE_LOCALTIME_S 1
12670 #endif
12671
12672 /*
12673 ** A structure for holding a single date and time.
12674 */
12675 typedef struct DateTime DateTime;
12676 struct DateTime {
12677   sqlite3_int64 iJD; /* The julian day number times 86400000 */
12678   int Y, M, D;       /* Year, month, and day */
12679   int h, m;          /* Hour and minutes */
12680   int tz;            /* Timezone offset in minutes */
12681   double s;          /* Seconds */
12682   char validYMD;     /* True (1) if Y,M,D are valid */
12683   char validHMS;     /* True (1) if h,m,s are valid */
12684   char validJD;      /* True (1) if iJD is valid */
12685   char validTZ;      /* True (1) if tz is valid */
12686 };
12687
12688
12689 /*
12690 ** Convert zDate into one or more integers.  Additional arguments
12691 ** come in groups of 5 as follows:
12692 **
12693 **       N       number of digits in the integer
12694 **       min     minimum allowed value of the integer
12695 **       max     maximum allowed value of the integer
12696 **       nextC   first character after the integer
12697 **       pVal    where to write the integers value.
12698 **
12699 ** Conversions continue until one with nextC==0 is encountered.
12700 ** The function returns the number of successful conversions.
12701 */
12702 static int getDigits(const char *zDate, ...){
12703   va_list ap;
12704   int val;
12705   int N;
12706   int min;
12707   int max;
12708   int nextC;
12709   int *pVal;
12710   int cnt = 0;
12711   va_start(ap, zDate);
12712   do{
12713     N = va_arg(ap, int);
12714     min = va_arg(ap, int);
12715     max = va_arg(ap, int);
12716     nextC = va_arg(ap, int);
12717     pVal = va_arg(ap, int*);
12718     val = 0;
12719     while( N-- ){
12720       if( !sqlite3Isdigit(*zDate) ){
12721         goto end_getDigits;
12722       }
12723       val = val*10 + *zDate - '0';
12724       zDate++;
12725     }
12726     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
12727       goto end_getDigits;
12728     }
12729     *pVal = val;
12730     zDate++;
12731     cnt++;
12732   }while( nextC );
12733 end_getDigits:
12734   va_end(ap);
12735   return cnt;
12736 }
12737
12738 /*
12739 ** Parse a timezone extension on the end of a date-time.
12740 ** The extension is of the form:
12741 **
12742 **        (+/-)HH:MM
12743 **
12744 ** Or the "zulu" notation:
12745 **
12746 **        Z
12747 **
12748 ** If the parse is successful, write the number of minutes
12749 ** of change in p->tz and return 0.  If a parser error occurs,
12750 ** return non-zero.
12751 **
12752 ** A missing specifier is not considered an error.
12753 */
12754 static int parseTimezone(const char *zDate, DateTime *p){
12755   int sgn = 0;
12756   int nHr, nMn;
12757   int c;
12758   while( sqlite3Isspace(*zDate) ){ zDate++; }
12759   p->tz = 0;
12760   c = *zDate;
12761   if( c=='-' ){
12762     sgn = -1;
12763   }else if( c=='+' ){
12764     sgn = +1;
12765   }else if( c=='Z' || c=='z' ){
12766     zDate++;
12767     goto zulu_time;
12768   }else{
12769     return c!=0;
12770   }
12771   zDate++;
12772   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
12773     return 1;
12774   }
12775   zDate += 5;
12776   p->tz = sgn*(nMn + nHr*60);
12777 zulu_time:
12778   while( sqlite3Isspace(*zDate) ){ zDate++; }
12779   return *zDate!=0;
12780 }
12781
12782 /*
12783 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
12784 ** The HH, MM, and SS must each be exactly 2 digits.  The
12785 ** fractional seconds FFFF can be one or more digits.
12786 **
12787 ** Return 1 if there is a parsing error and 0 on success.
12788 */
12789 static int parseHhMmSs(const char *zDate, DateTime *p){
12790   int h, m, s;
12791   double ms = 0.0;
12792   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
12793     return 1;
12794   }
12795   zDate += 5;
12796   if( *zDate==':' ){
12797     zDate++;
12798     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
12799       return 1;
12800     }
12801     zDate += 2;
12802     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
12803       double rScale = 1.0;
12804       zDate++;
12805       while( sqlite3Isdigit(*zDate) ){
12806         ms = ms*10.0 + *zDate - '0';
12807         rScale *= 10.0;
12808         zDate++;
12809       }
12810       ms /= rScale;
12811     }
12812   }else{
12813     s = 0;
12814   }
12815   p->validJD = 0;
12816   p->validHMS = 1;
12817   p->h = h;
12818   p->m = m;
12819   p->s = s + ms;
12820   if( parseTimezone(zDate, p) ) return 1;
12821   p->validTZ = (p->tz!=0)?1:0;
12822   return 0;
12823 }
12824
12825 /*
12826 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
12827 ** that the YYYY-MM-DD is according to the Gregorian calendar.
12828 **
12829 ** Reference:  Meeus page 61
12830 */
12831 static void computeJD(DateTime *p){
12832   int Y, M, D, A, B, X1, X2;
12833
12834   if( p->validJD ) return;
12835   if( p->validYMD ){
12836     Y = p->Y;
12837     M = p->M;
12838     D = p->D;
12839   }else{
12840     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
12841     M = 1;
12842     D = 1;
12843   }
12844   if( M<=2 ){
12845     Y--;
12846     M += 12;
12847   }
12848   A = Y/100;
12849   B = 2 - A + (A/4);
12850   X1 = 36525*(Y+4716)/100;
12851   X2 = 306001*(M+1)/10000;
12852   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
12853   p->validJD = 1;
12854   if( p->validHMS ){
12855     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
12856     if( p->validTZ ){
12857       p->iJD -= p->tz*60000;
12858       p->validYMD = 0;
12859       p->validHMS = 0;
12860       p->validTZ = 0;
12861     }
12862   }
12863 }
12864
12865 /*
12866 ** Parse dates of the form
12867 **
12868 **     YYYY-MM-DD HH:MM:SS.FFF
12869 **     YYYY-MM-DD HH:MM:SS
12870 **     YYYY-MM-DD HH:MM
12871 **     YYYY-MM-DD
12872 **
12873 ** Write the result into the DateTime structure and return 0
12874 ** on success and 1 if the input string is not a well-formed
12875 ** date.
12876 */
12877 static int parseYyyyMmDd(const char *zDate, DateTime *p){
12878   int Y, M, D, neg;
12879
12880   if( zDate[0]=='-' ){
12881     zDate++;
12882     neg = 1;
12883   }else{
12884     neg = 0;
12885   }
12886   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
12887     return 1;
12888   }
12889   zDate += 10;
12890   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
12891   if( parseHhMmSs(zDate, p)==0 ){
12892     /* We got the time */
12893   }else if( *zDate==0 ){
12894     p->validHMS = 0;
12895   }else{
12896     return 1;
12897   }
12898   p->validJD = 0;
12899   p->validYMD = 1;
12900   p->Y = neg ? -Y : Y;
12901   p->M = M;
12902   p->D = D;
12903   if( p->validTZ ){
12904     computeJD(p);
12905   }
12906   return 0;
12907 }
12908
12909 /*
12910 ** Set the time to the current time reported by the VFS
12911 */
12912 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
12913   sqlite3 *db = sqlite3_context_db_handle(context);
12914   sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
12915   p->validJD = 1;
12916 }
12917
12918 /*
12919 ** Attempt to parse the given string into a Julian Day Number.  Return
12920 ** the number of errors.
12921 **
12922 ** The following are acceptable forms for the input string:
12923 **
12924 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
12925 **      DDDD.DD 
12926 **      now
12927 **
12928 ** In the first form, the +/-HH:MM is always optional.  The fractional
12929 ** seconds extension (the ".FFF") is optional.  The seconds portion
12930 ** (":SS.FFF") is option.  The year and date can be omitted as long
12931 ** as there is a time string.  The time string can be omitted as long
12932 ** as there is a year and date.
12933 */
12934 static int parseDateOrTime(
12935   sqlite3_context *context, 
12936   const char *zDate, 
12937   DateTime *p
12938 ){
12939   double r;
12940   if( parseYyyyMmDd(zDate,p)==0 ){
12941     return 0;
12942   }else if( parseHhMmSs(zDate, p)==0 ){
12943     return 0;
12944   }else if( sqlite3StrICmp(zDate,"now")==0){
12945     setDateTimeToCurrent(context, p);
12946     return 0;
12947   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
12948     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
12949     p->validJD = 1;
12950     return 0;
12951   }
12952   return 1;
12953 }
12954
12955 /*
12956 ** Compute the Year, Month, and Day from the julian day number.
12957 */
12958 static void computeYMD(DateTime *p){
12959   int Z, A, B, C, D, E, X1;
12960   if( p->validYMD ) return;
12961   if( !p->validJD ){
12962     p->Y = 2000;
12963     p->M = 1;
12964     p->D = 1;
12965   }else{
12966     Z = (int)((p->iJD + 43200000)/86400000);
12967     A = (int)((Z - 1867216.25)/36524.25);
12968     A = Z + 1 + A - (A/4);
12969     B = A + 1524;
12970     C = (int)((B - 122.1)/365.25);
12971     D = (36525*C)/100;
12972     E = (int)((B-D)/30.6001);
12973     X1 = (int)(30.6001*E);
12974     p->D = B - D - X1;
12975     p->M = E<14 ? E-1 : E-13;
12976     p->Y = p->M>2 ? C - 4716 : C - 4715;
12977   }
12978   p->validYMD = 1;
12979 }
12980
12981 /*
12982 ** Compute the Hour, Minute, and Seconds from the julian day number.
12983 */
12984 static void computeHMS(DateTime *p){
12985   int s;
12986   if( p->validHMS ) return;
12987   computeJD(p);
12988   s = (int)((p->iJD + 43200000) % 86400000);
12989   p->s = s/1000.0;
12990   s = (int)p->s;
12991   p->s -= s;
12992   p->h = s/3600;
12993   s -= p->h*3600;
12994   p->m = s/60;
12995   p->s += s - p->m*60;
12996   p->validHMS = 1;
12997 }
12998
12999 /*
13000 ** Compute both YMD and HMS
13001 */
13002 static void computeYMD_HMS(DateTime *p){
13003   computeYMD(p);
13004   computeHMS(p);
13005 }
13006
13007 /*
13008 ** Clear the YMD and HMS and the TZ
13009 */
13010 static void clearYMD_HMS_TZ(DateTime *p){
13011   p->validYMD = 0;
13012   p->validHMS = 0;
13013   p->validTZ = 0;
13014 }
13015
13016 #ifndef SQLITE_OMIT_LOCALTIME
13017 /*
13018 ** Compute the difference (in milliseconds)
13019 ** between localtime and UTC (a.k.a. GMT)
13020 ** for the time value p where p is in UTC.
13021 */
13022 static sqlite3_int64 localtimeOffset(DateTime *p){
13023   DateTime x, y;
13024   time_t t;
13025   x = *p;
13026   computeYMD_HMS(&x);
13027   if( x.Y<1971 || x.Y>=2038 ){
13028     x.Y = 2000;
13029     x.M = 1;
13030     x.D = 1;
13031     x.h = 0;
13032     x.m = 0;
13033     x.s = 0.0;
13034   } else {
13035     int s = (int)(x.s + 0.5);
13036     x.s = s;
13037   }
13038   x.tz = 0;
13039   x.validJD = 0;
13040   computeJD(&x);
13041   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
13042 #ifdef HAVE_LOCALTIME_R
13043   {
13044     struct tm sLocal;
13045     localtime_r(&t, &sLocal);
13046     y.Y = sLocal.tm_year + 1900;
13047     y.M = sLocal.tm_mon + 1;
13048     y.D = sLocal.tm_mday;
13049     y.h = sLocal.tm_hour;
13050     y.m = sLocal.tm_min;
13051     y.s = sLocal.tm_sec;
13052   }
13053 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
13054   {
13055     struct tm sLocal;
13056     localtime_s(&sLocal, &t);
13057     y.Y = sLocal.tm_year + 1900;
13058     y.M = sLocal.tm_mon + 1;
13059     y.D = sLocal.tm_mday;
13060     y.h = sLocal.tm_hour;
13061     y.m = sLocal.tm_min;
13062     y.s = sLocal.tm_sec;
13063   }
13064 #else
13065   {
13066     struct tm *pTm;
13067     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13068     pTm = localtime(&t);
13069     y.Y = pTm->tm_year + 1900;
13070     y.M = pTm->tm_mon + 1;
13071     y.D = pTm->tm_mday;
13072     y.h = pTm->tm_hour;
13073     y.m = pTm->tm_min;
13074     y.s = pTm->tm_sec;
13075     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13076   }
13077 #endif
13078   y.validYMD = 1;
13079   y.validHMS = 1;
13080   y.validJD = 0;
13081   y.validTZ = 0;
13082   computeJD(&y);
13083   return y.iJD - x.iJD;
13084 }
13085 #endif /* SQLITE_OMIT_LOCALTIME */
13086
13087 /*
13088 ** Process a modifier to a date-time stamp.  The modifiers are
13089 ** as follows:
13090 **
13091 **     NNN days
13092 **     NNN hours
13093 **     NNN minutes
13094 **     NNN.NNNN seconds
13095 **     NNN months
13096 **     NNN years
13097 **     start of month
13098 **     start of year
13099 **     start of week
13100 **     start of day
13101 **     weekday N
13102 **     unixepoch
13103 **     localtime
13104 **     utc
13105 **
13106 ** Return 0 on success and 1 if there is any kind of error.
13107 */
13108 static int parseModifier(const char *zMod, DateTime *p){
13109   int rc = 1;
13110   int n;
13111   double r;
13112   char *z, zBuf[30];
13113   z = zBuf;
13114   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13115     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13116   }
13117   z[n] = 0;
13118   switch( z[0] ){
13119 #ifndef SQLITE_OMIT_LOCALTIME
13120     case 'l': {
13121       /*    localtime
13122       **
13123       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13124       ** show local time.
13125       */
13126       if( strcmp(z, "localtime")==0 ){
13127         computeJD(p);
13128         p->iJD += localtimeOffset(p);
13129         clearYMD_HMS_TZ(p);
13130         rc = 0;
13131       }
13132       break;
13133     }
13134 #endif
13135     case 'u': {
13136       /*
13137       **    unixepoch
13138       **
13139       ** Treat the current value of p->iJD as the number of
13140       ** seconds since 1970.  Convert to a real julian day number.
13141       */
13142       if( strcmp(z, "unixepoch")==0 && p->validJD ){
13143         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13144         clearYMD_HMS_TZ(p);
13145         rc = 0;
13146       }
13147 #ifndef SQLITE_OMIT_LOCALTIME
13148       else if( strcmp(z, "utc")==0 ){
13149         sqlite3_int64 c1;
13150         computeJD(p);
13151         c1 = localtimeOffset(p);
13152         p->iJD -= c1;
13153         clearYMD_HMS_TZ(p);
13154         p->iJD += c1 - localtimeOffset(p);
13155         rc = 0;
13156       }
13157 #endif
13158       break;
13159     }
13160     case 'w': {
13161       /*
13162       **    weekday N
13163       **
13164       ** Move the date to the same time on the next occurrence of
13165       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
13166       ** date is already on the appropriate weekday, this is a no-op.
13167       */
13168       if( strncmp(z, "weekday ", 8)==0
13169                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13170                && (n=(int)r)==r && n>=0 && r<7 ){
13171         sqlite3_int64 Z;
13172         computeYMD_HMS(p);
13173         p->validTZ = 0;
13174         p->validJD = 0;
13175         computeJD(p);
13176         Z = ((p->iJD + 129600000)/86400000) % 7;
13177         if( Z>n ) Z -= 7;
13178         p->iJD += (n - Z)*86400000;
13179         clearYMD_HMS_TZ(p);
13180         rc = 0;
13181       }
13182       break;
13183     }
13184     case 's': {
13185       /*
13186       **    start of TTTTT
13187       **
13188       ** Move the date backwards to the beginning of the current day,
13189       ** or month or year.
13190       */
13191       if( strncmp(z, "start of ", 9)!=0 ) break;
13192       z += 9;
13193       computeYMD(p);
13194       p->validHMS = 1;
13195       p->h = p->m = 0;
13196       p->s = 0.0;
13197       p->validTZ = 0;
13198       p->validJD = 0;
13199       if( strcmp(z,"month")==0 ){
13200         p->D = 1;
13201         rc = 0;
13202       }else if( strcmp(z,"year")==0 ){
13203         computeYMD(p);
13204         p->M = 1;
13205         p->D = 1;
13206         rc = 0;
13207       }else if( strcmp(z,"day")==0 ){
13208         rc = 0;
13209       }
13210       break;
13211     }
13212     case '+':
13213     case '-':
13214     case '0':
13215     case '1':
13216     case '2':
13217     case '3':
13218     case '4':
13219     case '5':
13220     case '6':
13221     case '7':
13222     case '8':
13223     case '9': {
13224       double rRounder;
13225       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13226       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13227         rc = 1;
13228         break;
13229       }
13230       if( z[n]==':' ){
13231         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13232         ** specified number of hours, minutes, seconds, and fractional seconds
13233         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
13234         ** omitted.
13235         */
13236         const char *z2 = z;
13237         DateTime tx;
13238         sqlite3_int64 day;
13239         if( !sqlite3Isdigit(*z2) ) z2++;
13240         memset(&tx, 0, sizeof(tx));
13241         if( parseHhMmSs(z2, &tx) ) break;
13242         computeJD(&tx);
13243         tx.iJD -= 43200000;
13244         day = tx.iJD/86400000;
13245         tx.iJD -= day*86400000;
13246         if( z[0]=='-' ) tx.iJD = -tx.iJD;
13247         computeJD(p);
13248         clearYMD_HMS_TZ(p);
13249         p->iJD += tx.iJD;
13250         rc = 0;
13251         break;
13252       }
13253       z += n;
13254       while( sqlite3Isspace(*z) ) z++;
13255       n = sqlite3Strlen30(z);
13256       if( n>10 || n<3 ) break;
13257       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13258       computeJD(p);
13259       rc = 0;
13260       rRounder = r<0 ? -0.5 : +0.5;
13261       if( n==3 && strcmp(z,"day")==0 ){
13262         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13263       }else if( n==4 && strcmp(z,"hour")==0 ){
13264         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13265       }else if( n==6 && strcmp(z,"minute")==0 ){
13266         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13267       }else if( n==6 && strcmp(z,"second")==0 ){
13268         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13269       }else if( n==5 && strcmp(z,"month")==0 ){
13270         int x, y;
13271         computeYMD_HMS(p);
13272         p->M += (int)r;
13273         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13274         p->Y += x;
13275         p->M -= x*12;
13276         p->validJD = 0;
13277         computeJD(p);
13278         y = (int)r;
13279         if( y!=r ){
13280           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13281         }
13282       }else if( n==4 && strcmp(z,"year")==0 ){
13283         int y = (int)r;
13284         computeYMD_HMS(p);
13285         p->Y += y;
13286         p->validJD = 0;
13287         computeJD(p);
13288         if( y!=r ){
13289           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
13290         }
13291       }else{
13292         rc = 1;
13293       }
13294       clearYMD_HMS_TZ(p);
13295       break;
13296     }
13297     default: {
13298       break;
13299     }
13300   }
13301   return rc;
13302 }
13303
13304 /*
13305 ** Process time function arguments.  argv[0] is a date-time stamp.
13306 ** argv[1] and following are modifiers.  Parse them all and write
13307 ** the resulting time into the DateTime structure p.  Return 0
13308 ** on success and 1 if there are any errors.
13309 **
13310 ** If there are zero parameters (if even argv[0] is undefined)
13311 ** then assume a default value of "now" for argv[0].
13312 */
13313 static int isDate(
13314   sqlite3_context *context, 
13315   int argc, 
13316   sqlite3_value **argv, 
13317   DateTime *p
13318 ){
13319   int i;
13320   const unsigned char *z;
13321   int eType;
13322   memset(p, 0, sizeof(*p));
13323   if( argc==0 ){
13324     setDateTimeToCurrent(context, p);
13325   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
13326                    || eType==SQLITE_INTEGER ){
13327     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
13328     p->validJD = 1;
13329   }else{
13330     z = sqlite3_value_text(argv[0]);
13331     if( !z || parseDateOrTime(context, (char*)z, p) ){
13332       return 1;
13333     }
13334   }
13335   for(i=1; i<argc; i++){
13336     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
13337       return 1;
13338     }
13339   }
13340   return 0;
13341 }
13342
13343
13344 /*
13345 ** The following routines implement the various date and time functions
13346 ** of SQLite.
13347 */
13348
13349 /*
13350 **    julianday( TIMESTRING, MOD, MOD, ...)
13351 **
13352 ** Return the julian day number of the date specified in the arguments
13353 */
13354 static void juliandayFunc(
13355   sqlite3_context *context,
13356   int argc,
13357   sqlite3_value **argv
13358 ){
13359   DateTime x;
13360   if( isDate(context, argc, argv, &x)==0 ){
13361     computeJD(&x);
13362     sqlite3_result_double(context, x.iJD/86400000.0);
13363   }
13364 }
13365
13366 /*
13367 **    datetime( TIMESTRING, MOD, MOD, ...)
13368 **
13369 ** Return YYYY-MM-DD HH:MM:SS
13370 */
13371 static void datetimeFunc(
13372   sqlite3_context *context,
13373   int argc,
13374   sqlite3_value **argv
13375 ){
13376   DateTime x;
13377   if( isDate(context, argc, argv, &x)==0 ){
13378     char zBuf[100];
13379     computeYMD_HMS(&x);
13380     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
13381                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
13382     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13383   }
13384 }
13385
13386 /*
13387 **    time( TIMESTRING, MOD, MOD, ...)
13388 **
13389 ** Return HH:MM:SS
13390 */
13391 static void timeFunc(
13392   sqlite3_context *context,
13393   int argc,
13394   sqlite3_value **argv
13395 ){
13396   DateTime x;
13397   if( isDate(context, argc, argv, &x)==0 ){
13398     char zBuf[100];
13399     computeHMS(&x);
13400     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
13401     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13402   }
13403 }
13404
13405 /*
13406 **    date( TIMESTRING, MOD, MOD, ...)
13407 **
13408 ** Return YYYY-MM-DD
13409 */
13410 static void dateFunc(
13411   sqlite3_context *context,
13412   int argc,
13413   sqlite3_value **argv
13414 ){
13415   DateTime x;
13416   if( isDate(context, argc, argv, &x)==0 ){
13417     char zBuf[100];
13418     computeYMD(&x);
13419     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
13420     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13421   }
13422 }
13423
13424 /*
13425 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
13426 **
13427 ** Return a string described by FORMAT.  Conversions as follows:
13428 **
13429 **   %d  day of month
13430 **   %f  ** fractional seconds  SS.SSS
13431 **   %H  hour 00-24
13432 **   %j  day of year 000-366
13433 **   %J  ** Julian day number
13434 **   %m  month 01-12
13435 **   %M  minute 00-59
13436 **   %s  seconds since 1970-01-01
13437 **   %S  seconds 00-59
13438 **   %w  day of week 0-6  sunday==0
13439 **   %W  week of year 00-53
13440 **   %Y  year 0000-9999
13441 **   %%  %
13442 */
13443 static void strftimeFunc(
13444   sqlite3_context *context,
13445   int argc,
13446   sqlite3_value **argv
13447 ){
13448   DateTime x;
13449   u64 n;
13450   size_t i,j;
13451   char *z;
13452   sqlite3 *db;
13453   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
13454   char zBuf[100];
13455   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
13456   db = sqlite3_context_db_handle(context);
13457   for(i=0, n=1; zFmt[i]; i++, n++){
13458     if( zFmt[i]=='%' ){
13459       switch( zFmt[i+1] ){
13460         case 'd':
13461         case 'H':
13462         case 'm':
13463         case 'M':
13464         case 'S':
13465         case 'W':
13466           n++;
13467           /* fall thru */
13468         case 'w':
13469         case '%':
13470           break;
13471         case 'f':
13472           n += 8;
13473           break;
13474         case 'j':
13475           n += 3;
13476           break;
13477         case 'Y':
13478           n += 8;
13479           break;
13480         case 's':
13481         case 'J':
13482           n += 50;
13483           break;
13484         default:
13485           return;  /* ERROR.  return a NULL */
13486       }
13487       i++;
13488     }
13489   }
13490   testcase( n==sizeof(zBuf)-1 );
13491   testcase( n==sizeof(zBuf) );
13492   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
13493   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
13494   if( n<sizeof(zBuf) ){
13495     z = zBuf;
13496   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
13497     sqlite3_result_error_toobig(context);
13498     return;
13499   }else{
13500     z = sqlite3DbMallocRaw(db, (int)n);
13501     if( z==0 ){
13502       sqlite3_result_error_nomem(context);
13503       return;
13504     }
13505   }
13506   computeJD(&x);
13507   computeYMD_HMS(&x);
13508   for(i=j=0; zFmt[i]; i++){
13509     if( zFmt[i]!='%' ){
13510       z[j++] = zFmt[i];
13511     }else{
13512       i++;
13513       switch( zFmt[i] ){
13514         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
13515         case 'f': {
13516           double s = x.s;
13517           if( s>59.999 ) s = 59.999;
13518           sqlite3_snprintf(7, &z[j],"%06.3f", s);
13519           j += sqlite3Strlen30(&z[j]);
13520           break;
13521         }
13522         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
13523         case 'W': /* Fall thru */
13524         case 'j': {
13525           int nDay;             /* Number of days since 1st day of year */
13526           DateTime y = x;
13527           y.validJD = 0;
13528           y.M = 1;
13529           y.D = 1;
13530           computeJD(&y);
13531           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
13532           if( zFmt[i]=='W' ){
13533             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
13534             wd = (int)(((x.iJD+43200000)/86400000)%7);
13535             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
13536             j += 2;
13537           }else{
13538             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
13539             j += 3;
13540           }
13541           break;
13542         }
13543         case 'J': {
13544           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
13545           j+=sqlite3Strlen30(&z[j]);
13546           break;
13547         }
13548         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
13549         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
13550         case 's': {
13551           sqlite3_snprintf(30,&z[j],"%lld",
13552                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
13553           j += sqlite3Strlen30(&z[j]);
13554           break;
13555         }
13556         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
13557         case 'w': {
13558           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
13559           break;
13560         }
13561         case 'Y': {
13562           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
13563           break;
13564         }
13565         default:   z[j++] = '%'; break;
13566       }
13567     }
13568   }
13569   z[j] = 0;
13570   sqlite3_result_text(context, z, -1,
13571                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
13572 }
13573
13574 /*
13575 ** current_time()
13576 **
13577 ** This function returns the same value as time('now').
13578 */
13579 static void ctimeFunc(
13580   sqlite3_context *context,
13581   int NotUsed,
13582   sqlite3_value **NotUsed2
13583 ){
13584   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13585   timeFunc(context, 0, 0);
13586 }
13587
13588 /*
13589 ** current_date()
13590 **
13591 ** This function returns the same value as date('now').
13592 */
13593 static void cdateFunc(
13594   sqlite3_context *context,
13595   int NotUsed,
13596   sqlite3_value **NotUsed2
13597 ){
13598   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13599   dateFunc(context, 0, 0);
13600 }
13601
13602 /*
13603 ** current_timestamp()
13604 **
13605 ** This function returns the same value as datetime('now').
13606 */
13607 static void ctimestampFunc(
13608   sqlite3_context *context,
13609   int NotUsed,
13610   sqlite3_value **NotUsed2
13611 ){
13612   UNUSED_PARAMETER2(NotUsed, NotUsed2);
13613   datetimeFunc(context, 0, 0);
13614 }
13615 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
13616
13617 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13618 /*
13619 ** If the library is compiled to omit the full-scale date and time
13620 ** handling (to get a smaller binary), the following minimal version
13621 ** of the functions current_time(), current_date() and current_timestamp()
13622 ** are included instead. This is to support column declarations that
13623 ** include "DEFAULT CURRENT_TIME" etc.
13624 **
13625 ** This function uses the C-library functions time(), gmtime()
13626 ** and strftime(). The format string to pass to strftime() is supplied
13627 ** as the user-data for the function.
13628 */
13629 static void currentTimeFunc(
13630   sqlite3_context *context,
13631   int argc,
13632   sqlite3_value **argv
13633 ){
13634   time_t t;
13635   char *zFormat = (char *)sqlite3_user_data(context);
13636   sqlite3 *db;
13637   sqlite3_int64 iT;
13638   char zBuf[20];
13639
13640   UNUSED_PARAMETER(argc);
13641   UNUSED_PARAMETER(argv);
13642
13643   db = sqlite3_context_db_handle(context);
13644   sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
13645   t = iT/1000 - 10000*(sqlite3_int64)21086676;
13646 #ifdef HAVE_GMTIME_R
13647   {
13648     struct tm sNow;
13649     gmtime_r(&t, &sNow);
13650     strftime(zBuf, 20, zFormat, &sNow);
13651   }
13652 #else
13653   {
13654     struct tm *pTm;
13655     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13656     pTm = gmtime(&t);
13657     strftime(zBuf, 20, zFormat, pTm);
13658     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
13659   }
13660 #endif
13661
13662   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
13663 }
13664 #endif
13665
13666 /*
13667 ** This function registered all of the above C functions as SQL
13668 ** functions.  This should be the only routine in this file with
13669 ** external linkage.
13670 */
13671 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
13672   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
13673 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13674     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
13675     FUNCTION(date,             -1, 0, 0, dateFunc      ),
13676     FUNCTION(time,             -1, 0, 0, timeFunc      ),
13677     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
13678     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
13679     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
13680     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
13681     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
13682 #else
13683     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
13684     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
13685     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
13686 #endif
13687   };
13688   int i;
13689   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
13690   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
13691
13692   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
13693     sqlite3FuncDefInsert(pHash, &aFunc[i]);
13694   }
13695 }
13696
13697 /************** End of date.c ************************************************/
13698 /************** Begin file os.c **********************************************/
13699 /*
13700 ** 2005 November 29
13701 **
13702 ** The author disclaims copyright to this source code.  In place of
13703 ** a legal notice, here is a blessing:
13704 **
13705 **    May you do good and not evil.
13706 **    May you find forgiveness for yourself and forgive others.
13707 **    May you share freely, never taking more than you give.
13708 **
13709 ******************************************************************************
13710 **
13711 ** This file contains OS interface code that is common to all
13712 ** architectures.
13713 */
13714 #define _SQLITE_OS_C_ 1
13715 #undef _SQLITE_OS_C_
13716
13717 /*
13718 ** The default SQLite sqlite3_vfs implementations do not allocate
13719 ** memory (actually, os_unix.c allocates a small amount of memory
13720 ** from within OsOpen()), but some third-party implementations may.
13721 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
13722 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
13723 **
13724 ** The following functions are instrumented for malloc() failure 
13725 ** testing:
13726 **
13727 **     sqlite3OsOpen()
13728 **     sqlite3OsRead()
13729 **     sqlite3OsWrite()
13730 **     sqlite3OsSync()
13731 **     sqlite3OsLock()
13732 **
13733 */
13734 #if defined(SQLITE_TEST)
13735 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
13736   #define DO_OS_MALLOC_TEST(x)                                       \
13737   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
13738     void *pTstAlloc = sqlite3Malloc(10);                             \
13739     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
13740     sqlite3_free(pTstAlloc);                                         \
13741   }
13742 #else
13743   #define DO_OS_MALLOC_TEST(x)
13744 #endif
13745
13746 /*
13747 ** The following routines are convenience wrappers around methods
13748 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
13749 ** of this would be completely automatic if SQLite were coded using
13750 ** C++ instead of plain old C.
13751 */
13752 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
13753   int rc = SQLITE_OK;
13754   if( pId->pMethods ){
13755     rc = pId->pMethods->xClose(pId);
13756     pId->pMethods = 0;
13757   }
13758   return rc;
13759 }
13760 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
13761   DO_OS_MALLOC_TEST(id);
13762   return id->pMethods->xRead(id, pBuf, amt, offset);
13763 }
13764 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
13765   DO_OS_MALLOC_TEST(id);
13766   return id->pMethods->xWrite(id, pBuf, amt, offset);
13767 }
13768 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
13769   return id->pMethods->xTruncate(id, size);
13770 }
13771 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
13772   DO_OS_MALLOC_TEST(id);
13773   return id->pMethods->xSync(id, flags);
13774 }
13775 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
13776   DO_OS_MALLOC_TEST(id);
13777   return id->pMethods->xFileSize(id, pSize);
13778 }
13779 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
13780   DO_OS_MALLOC_TEST(id);
13781   return id->pMethods->xLock(id, lockType);
13782 }
13783 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
13784   return id->pMethods->xUnlock(id, lockType);
13785 }
13786 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
13787   DO_OS_MALLOC_TEST(id);
13788   return id->pMethods->xCheckReservedLock(id, pResOut);
13789 }
13790 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
13791   return id->pMethods->xFileControl(id, op, pArg);
13792 }
13793 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
13794   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
13795   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
13796 }
13797 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
13798   return id->pMethods->xDeviceCharacteristics(id);
13799 }
13800 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
13801   return id->pMethods->xShmLock(id, offset, n, flags);
13802 }
13803 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
13804   id->pMethods->xShmBarrier(id);
13805 }
13806 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
13807   return id->pMethods->xShmUnmap(id, deleteFlag);
13808 }
13809 SQLITE_PRIVATE int sqlite3OsShmMap(
13810   sqlite3_file *id,               /* Database file handle */
13811   int iPage,
13812   int pgsz,
13813   int bExtend,                    /* True to extend file if necessary */
13814   void volatile **pp              /* OUT: Pointer to mapping */
13815 ){
13816   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
13817 }
13818
13819 /*
13820 ** The next group of routines are convenience wrappers around the
13821 ** VFS methods.
13822 */
13823 SQLITE_PRIVATE int sqlite3OsOpen(
13824   sqlite3_vfs *pVfs, 
13825   const char *zPath, 
13826   sqlite3_file *pFile, 
13827   int flags, 
13828   int *pFlagsOut
13829 ){
13830   int rc;
13831   DO_OS_MALLOC_TEST(0);
13832   /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
13833   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
13834   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
13835   ** reaching the VFS. */
13836   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f3f, pFlagsOut);
13837   assert( rc==SQLITE_OK || pFile->pMethods==0 );
13838   return rc;
13839 }
13840 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
13841   return pVfs->xDelete(pVfs, zPath, dirSync);
13842 }
13843 SQLITE_PRIVATE int sqlite3OsAccess(
13844   sqlite3_vfs *pVfs, 
13845   const char *zPath, 
13846   int flags, 
13847   int *pResOut
13848 ){
13849   DO_OS_MALLOC_TEST(0);
13850   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
13851 }
13852 SQLITE_PRIVATE int sqlite3OsFullPathname(
13853   sqlite3_vfs *pVfs, 
13854   const char *zPath, 
13855   int nPathOut, 
13856   char *zPathOut
13857 ){
13858   zPathOut[0] = 0;
13859   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
13860 }
13861 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13862 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
13863   return pVfs->xDlOpen(pVfs, zPath);
13864 }
13865 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13866   pVfs->xDlError(pVfs, nByte, zBufOut);
13867 }
13868 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
13869   return pVfs->xDlSym(pVfs, pHdle, zSym);
13870 }
13871 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
13872   pVfs->xDlClose(pVfs, pHandle);
13873 }
13874 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
13875 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
13876   return pVfs->xRandomness(pVfs, nByte, zBufOut);
13877 }
13878 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
13879   return pVfs->xSleep(pVfs, nMicro);
13880 }
13881 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
13882   int rc;
13883   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
13884   ** method to get the current date and time if that method is available
13885   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
13886   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
13887   ** unavailable.
13888   */
13889   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
13890     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
13891   }else{
13892     double r;
13893     rc = pVfs->xCurrentTime(pVfs, &r);
13894     *pTimeOut = (sqlite3_int64)(r*86400000.0);
13895   }
13896   return rc;
13897 }
13898
13899 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
13900   sqlite3_vfs *pVfs, 
13901   const char *zFile, 
13902   sqlite3_file **ppFile, 
13903   int flags,
13904   int *pOutFlags
13905 ){
13906   int rc = SQLITE_NOMEM;
13907   sqlite3_file *pFile;
13908   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
13909   if( pFile ){
13910     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
13911     if( rc!=SQLITE_OK ){
13912       sqlite3_free(pFile);
13913     }else{
13914       *ppFile = pFile;
13915     }
13916   }
13917   return rc;
13918 }
13919 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
13920   int rc = SQLITE_OK;
13921   assert( pFile );
13922   rc = sqlite3OsClose(pFile);
13923   sqlite3_free(pFile);
13924   return rc;
13925 }
13926
13927 /*
13928 ** This function is a wrapper around the OS specific implementation of
13929 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
13930 ** ability to simulate a malloc failure, so that the handling of an
13931 ** error in sqlite3_os_init() by the upper layers can be tested.
13932 */
13933 SQLITE_PRIVATE int sqlite3OsInit(void){
13934   void *p = sqlite3_malloc(10);
13935   if( p==0 ) return SQLITE_NOMEM;
13936   sqlite3_free(p);
13937   return sqlite3_os_init();
13938 }
13939
13940 /*
13941 ** The list of all registered VFS implementations.
13942 */
13943 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
13944 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
13945
13946 /*
13947 ** Locate a VFS by name.  If no name is given, simply return the
13948 ** first VFS on the list.
13949 */
13950 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
13951   sqlite3_vfs *pVfs = 0;
13952 #if SQLITE_THREADSAFE
13953   sqlite3_mutex *mutex;
13954 #endif
13955 #ifndef SQLITE_OMIT_AUTOINIT
13956   int rc = sqlite3_initialize();
13957   if( rc ) return 0;
13958 #endif
13959 #if SQLITE_THREADSAFE
13960   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13961 #endif
13962   sqlite3_mutex_enter(mutex);
13963   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
13964     if( zVfs==0 ) break;
13965     if( strcmp(zVfs, pVfs->zName)==0 ) break;
13966   }
13967   sqlite3_mutex_leave(mutex);
13968   return pVfs;
13969 }
13970
13971 /*
13972 ** Unlink a VFS from the linked list
13973 */
13974 static void vfsUnlink(sqlite3_vfs *pVfs){
13975   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
13976   if( pVfs==0 ){
13977     /* No-op */
13978   }else if( vfsList==pVfs ){
13979     vfsList = pVfs->pNext;
13980   }else if( vfsList ){
13981     sqlite3_vfs *p = vfsList;
13982     while( p->pNext && p->pNext!=pVfs ){
13983       p = p->pNext;
13984     }
13985     if( p->pNext==pVfs ){
13986       p->pNext = pVfs->pNext;
13987     }
13988   }
13989 }
13990
13991 /*
13992 ** Register a VFS with the system.  It is harmless to register the same
13993 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
13994 ** true.
13995 */
13996 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
13997   sqlite3_mutex *mutex = 0;
13998 #ifndef SQLITE_OMIT_AUTOINIT
13999   int rc = sqlite3_initialize();
14000   if( rc ) return rc;
14001 #endif
14002   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14003   sqlite3_mutex_enter(mutex);
14004   vfsUnlink(pVfs);
14005   if( makeDflt || vfsList==0 ){
14006     pVfs->pNext = vfsList;
14007     vfsList = pVfs;
14008   }else{
14009     pVfs->pNext = vfsList->pNext;
14010     vfsList->pNext = pVfs;
14011   }
14012   assert(vfsList);
14013   sqlite3_mutex_leave(mutex);
14014   return SQLITE_OK;
14015 }
14016
14017 /*
14018 ** Unregister a VFS so that it is no longer accessible.
14019 */
14020 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
14021 #if SQLITE_THREADSAFE
14022   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14023 #endif
14024   sqlite3_mutex_enter(mutex);
14025   vfsUnlink(pVfs);
14026   sqlite3_mutex_leave(mutex);
14027   return SQLITE_OK;
14028 }
14029
14030 /************** End of os.c **************************************************/
14031 /************** Begin file fault.c *******************************************/
14032 /*
14033 ** 2008 Jan 22
14034 **
14035 ** The author disclaims copyright to this source code.  In place of
14036 ** a legal notice, here is a blessing:
14037 **
14038 **    May you do good and not evil.
14039 **    May you find forgiveness for yourself and forgive others.
14040 **    May you share freely, never taking more than you give.
14041 **
14042 *************************************************************************
14043 **
14044 ** This file contains code to support the concept of "benign" 
14045 ** malloc failures (when the xMalloc() or xRealloc() method of the
14046 ** sqlite3_mem_methods structure fails to allocate a block of memory
14047 ** and returns 0). 
14048 **
14049 ** Most malloc failures are non-benign. After they occur, SQLite
14050 ** abandons the current operation and returns an error code (usually
14051 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
14052 ** fatal. For example, if a malloc fails while resizing a hash table, this 
14053 ** is completely recoverable simply by not carrying out the resize. The 
14054 ** hash table will continue to function normally.  So a malloc failure 
14055 ** during a hash table resize is a benign fault.
14056 */
14057
14058
14059 #ifndef SQLITE_OMIT_BUILTIN_TEST
14060
14061 /*
14062 ** Global variables.
14063 */
14064 typedef struct BenignMallocHooks BenignMallocHooks;
14065 static SQLITE_WSD struct BenignMallocHooks {
14066   void (*xBenignBegin)(void);
14067   void (*xBenignEnd)(void);
14068 } sqlite3Hooks = { 0, 0 };
14069
14070 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
14071 ** structure.  If writable static data is unsupported on the target,
14072 ** we have to locate the state vector at run-time.  In the more common
14073 ** case where writable static data is supported, wsdHooks can refer directly
14074 ** to the "sqlite3Hooks" state vector declared above.
14075 */
14076 #ifdef SQLITE_OMIT_WSD
14077 # define wsdHooksInit \
14078   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
14079 # define wsdHooks x[0]
14080 #else
14081 # define wsdHooksInit
14082 # define wsdHooks sqlite3Hooks
14083 #endif
14084
14085
14086 /*
14087 ** Register hooks to call when sqlite3BeginBenignMalloc() and
14088 ** sqlite3EndBenignMalloc() are called, respectively.
14089 */
14090 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
14091   void (*xBenignBegin)(void),
14092   void (*xBenignEnd)(void)
14093 ){
14094   wsdHooksInit;
14095   wsdHooks.xBenignBegin = xBenignBegin;
14096   wsdHooks.xBenignEnd = xBenignEnd;
14097 }
14098
14099 /*
14100 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14101 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14102 ** indicates that subsequent malloc failures are non-benign.
14103 */
14104 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14105   wsdHooksInit;
14106   if( wsdHooks.xBenignBegin ){
14107     wsdHooks.xBenignBegin();
14108   }
14109 }
14110 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14111   wsdHooksInit;
14112   if( wsdHooks.xBenignEnd ){
14113     wsdHooks.xBenignEnd();
14114   }
14115 }
14116
14117 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14118
14119 /************** End of fault.c ***********************************************/
14120 /************** Begin file mem0.c ********************************************/
14121 /*
14122 ** 2008 October 28
14123 **
14124 ** The author disclaims copyright to this source code.  In place of
14125 ** a legal notice, here is a blessing:
14126 **
14127 **    May you do good and not evil.
14128 **    May you find forgiveness for yourself and forgive others.
14129 **    May you share freely, never taking more than you give.
14130 **
14131 *************************************************************************
14132 **
14133 ** This file contains a no-op memory allocation drivers for use when
14134 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
14135 ** here always fail.  SQLite will not operate with these drivers.  These
14136 ** are merely placeholders.  Real drivers must be substituted using
14137 ** sqlite3_config() before SQLite will operate.
14138 */
14139
14140 /*
14141 ** This version of the memory allocator is the default.  It is
14142 ** used when no other memory allocator is specified using compile-time
14143 ** macros.
14144 */
14145 #ifdef SQLITE_ZERO_MALLOC
14146
14147 /*
14148 ** No-op versions of all memory allocation routines
14149 */
14150 static void *sqlite3MemMalloc(int nByte){ return 0; }
14151 static void sqlite3MemFree(void *pPrior){ return; }
14152 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
14153 static int sqlite3MemSize(void *pPrior){ return 0; }
14154 static int sqlite3MemRoundup(int n){ return n; }
14155 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
14156 static void sqlite3MemShutdown(void *NotUsed){ return; }
14157
14158 /*
14159 ** This routine is the only routine in this file with external linkage.
14160 **
14161 ** Populate the low-level memory allocation function pointers in
14162 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14163 */
14164 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14165   static const sqlite3_mem_methods defaultMethods = {
14166      sqlite3MemMalloc,
14167      sqlite3MemFree,
14168      sqlite3MemRealloc,
14169      sqlite3MemSize,
14170      sqlite3MemRoundup,
14171      sqlite3MemInit,
14172      sqlite3MemShutdown,
14173      0
14174   };
14175   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14176 }
14177
14178 #endif /* SQLITE_ZERO_MALLOC */
14179
14180 /************** End of mem0.c ************************************************/
14181 /************** Begin file mem1.c ********************************************/
14182 /*
14183 ** 2007 August 14
14184 **
14185 ** The author disclaims copyright to this source code.  In place of
14186 ** a legal notice, here is a blessing:
14187 **
14188 **    May you do good and not evil.
14189 **    May you find forgiveness for yourself and forgive others.
14190 **    May you share freely, never taking more than you give.
14191 **
14192 *************************************************************************
14193 **
14194 ** This file contains low-level memory allocation drivers for when
14195 ** SQLite will use the standard C-library malloc/realloc/free interface
14196 ** to obtain the memory it needs.
14197 **
14198 ** This file contains implementations of the low-level memory allocation
14199 ** routines specified in the sqlite3_mem_methods object.
14200 */
14201
14202 /*
14203 ** This version of the memory allocator is the default.  It is
14204 ** used when no other memory allocator is specified using compile-time
14205 ** macros.
14206 */
14207 #ifdef SQLITE_SYSTEM_MALLOC
14208
14209 /*
14210 ** Like malloc(), but remember the size of the allocation
14211 ** so that we can find it later using sqlite3MemSize().
14212 **
14213 ** For this low-level routine, we are guaranteed that nByte>0 because
14214 ** cases of nByte<=0 will be intercepted and dealt with by higher level
14215 ** routines.
14216 */
14217 static void *sqlite3MemMalloc(int nByte){
14218   sqlite3_int64 *p;
14219   assert( nByte>0 );
14220   nByte = ROUND8(nByte);
14221   p = malloc( nByte+8 );
14222   if( p ){
14223     p[0] = nByte;
14224     p++;
14225   }else{
14226     testcase( sqlite3GlobalConfig.xLog!=0 );
14227     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14228   }
14229   return (void *)p;
14230 }
14231
14232 /*
14233 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
14234 ** or sqlite3MemRealloc().
14235 **
14236 ** For this low-level routine, we already know that pPrior!=0 since
14237 ** cases where pPrior==0 will have been intecepted and dealt with
14238 ** by higher-level routines.
14239 */
14240 static void sqlite3MemFree(void *pPrior){
14241   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14242   assert( pPrior!=0 );
14243   p--;
14244   free(p);
14245 }
14246
14247 /*
14248 ** Report the allocated size of a prior return from xMalloc()
14249 ** or xRealloc().
14250 */
14251 static int sqlite3MemSize(void *pPrior){
14252   sqlite3_int64 *p;
14253   if( pPrior==0 ) return 0;
14254   p = (sqlite3_int64*)pPrior;
14255   p--;
14256   return (int)p[0];
14257 }
14258
14259 /*
14260 ** Like realloc().  Resize an allocation previously obtained from
14261 ** sqlite3MemMalloc().
14262 **
14263 ** For this low-level interface, we know that pPrior!=0.  Cases where
14264 ** pPrior==0 while have been intercepted by higher-level routine and
14265 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
14266 ** cases where nByte<=0 will have been intercepted by higher-level
14267 ** routines and redirected to xFree.
14268 */
14269 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14270   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14271   assert( pPrior!=0 && nByte>0 );
14272   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14273   p--;
14274   p = realloc(p, nByte+8 );
14275   if( p ){
14276     p[0] = nByte;
14277     p++;
14278   }else{
14279     testcase( sqlite3GlobalConfig.xLog!=0 );
14280     sqlite3_log(SQLITE_NOMEM,
14281       "failed memory resize %u to %u bytes",
14282       sqlite3MemSize(pPrior), nByte);
14283   }
14284   return (void*)p;
14285 }
14286
14287 /*
14288 ** Round up a request size to the next valid allocation size.
14289 */
14290 static int sqlite3MemRoundup(int n){
14291   return ROUND8(n);
14292 }
14293
14294 /*
14295 ** Initialize this module.
14296 */
14297 static int sqlite3MemInit(void *NotUsed){
14298   UNUSED_PARAMETER(NotUsed);
14299   return SQLITE_OK;
14300 }
14301
14302 /*
14303 ** Deinitialize this module.
14304 */
14305 static void sqlite3MemShutdown(void *NotUsed){
14306   UNUSED_PARAMETER(NotUsed);
14307   return;
14308 }
14309
14310 /*
14311 ** This routine is the only routine in this file with external linkage.
14312 **
14313 ** Populate the low-level memory allocation function pointers in
14314 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14315 */
14316 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14317   static const sqlite3_mem_methods defaultMethods = {
14318      sqlite3MemMalloc,
14319      sqlite3MemFree,
14320      sqlite3MemRealloc,
14321      sqlite3MemSize,
14322      sqlite3MemRoundup,
14323      sqlite3MemInit,
14324      sqlite3MemShutdown,
14325      0
14326   };
14327   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14328 }
14329
14330 #endif /* SQLITE_SYSTEM_MALLOC */
14331
14332 /************** End of mem1.c ************************************************/
14333 /************** Begin file mem2.c ********************************************/
14334 /*
14335 ** 2007 August 15
14336 **
14337 ** The author disclaims copyright to this source code.  In place of
14338 ** a legal notice, here is a blessing:
14339 **
14340 **    May you do good and not evil.
14341 **    May you find forgiveness for yourself and forgive others.
14342 **    May you share freely, never taking more than you give.
14343 **
14344 *************************************************************************
14345 **
14346 ** This file contains low-level memory allocation drivers for when
14347 ** SQLite will use the standard C-library malloc/realloc/free interface
14348 ** to obtain the memory it needs while adding lots of additional debugging
14349 ** information to each allocation in order to help detect and fix memory
14350 ** leaks and memory usage errors.
14351 **
14352 ** This file contains implementations of the low-level memory allocation
14353 ** routines specified in the sqlite3_mem_methods object.
14354 */
14355
14356 /*
14357 ** This version of the memory allocator is used only if the
14358 ** SQLITE_MEMDEBUG macro is defined
14359 */
14360 #ifdef SQLITE_MEMDEBUG
14361
14362 /*
14363 ** The backtrace functionality is only available with GLIBC
14364 */
14365 #ifdef __GLIBC__
14366   extern int backtrace(void**,int);
14367   extern void backtrace_symbols_fd(void*const*,int,int);
14368 #else
14369 # define backtrace(A,B) 1
14370 # define backtrace_symbols_fd(A,B,C)
14371 #endif
14372
14373 /*
14374 ** Each memory allocation looks like this:
14375 **
14376 **  ------------------------------------------------------------------------
14377 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
14378 **  ------------------------------------------------------------------------
14379 **
14380 ** The application code sees only a pointer to the allocation.  We have
14381 ** to back up from the allocation pointer to find the MemBlockHdr.  The
14382 ** MemBlockHdr tells us the size of the allocation and the number of
14383 ** backtrace pointers.  There is also a guard word at the end of the
14384 ** MemBlockHdr.
14385 */
14386 struct MemBlockHdr {
14387   i64 iSize;                          /* Size of this allocation */
14388   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
14389   char nBacktrace;                    /* Number of backtraces on this alloc */
14390   char nBacktraceSlots;               /* Available backtrace slots */
14391   u8 nTitle;                          /* Bytes of title; includes '\0' */
14392   u8 eType;                           /* Allocation type code */
14393   int iForeGuard;                     /* Guard word for sanity */
14394 };
14395
14396 /*
14397 ** Guard words
14398 */
14399 #define FOREGUARD 0x80F5E153
14400 #define REARGUARD 0xE4676B53
14401
14402 /*
14403 ** Number of malloc size increments to track.
14404 */
14405 #define NCSIZE  1000
14406
14407 /*
14408 ** All of the static variables used by this module are collected
14409 ** into a single structure named "mem".  This is to keep the
14410 ** static variables organized and to reduce namespace pollution
14411 ** when this module is combined with other in the amalgamation.
14412 */
14413 static struct {
14414   
14415   /*
14416   ** Mutex to control access to the memory allocation subsystem.
14417   */
14418   sqlite3_mutex *mutex;
14419
14420   /*
14421   ** Head and tail of a linked list of all outstanding allocations
14422   */
14423   struct MemBlockHdr *pFirst;
14424   struct MemBlockHdr *pLast;
14425   
14426   /*
14427   ** The number of levels of backtrace to save in new allocations.
14428   */
14429   int nBacktrace;
14430   void (*xBacktrace)(int, int, void **);
14431
14432   /*
14433   ** Title text to insert in front of each block
14434   */
14435   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
14436   char zTitle[100];  /* The title text */
14437
14438   /* 
14439   ** sqlite3MallocDisallow() increments the following counter.
14440   ** sqlite3MallocAllow() decrements it.
14441   */
14442   int disallow; /* Do not allow memory allocation */
14443
14444   /*
14445   ** Gather statistics on the sizes of memory allocations.
14446   ** nAlloc[i] is the number of allocation attempts of i*8
14447   ** bytes.  i==NCSIZE is the number of allocation attempts for
14448   ** sizes more than NCSIZE*8 bytes.
14449   */
14450   int nAlloc[NCSIZE];      /* Total number of allocations */
14451   int nCurrent[NCSIZE];    /* Current number of allocations */
14452   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
14453
14454 } mem;
14455
14456
14457 /*
14458 ** Adjust memory usage statistics
14459 */
14460 static void adjustStats(int iSize, int increment){
14461   int i = ROUND8(iSize)/8;
14462   if( i>NCSIZE-1 ){
14463     i = NCSIZE - 1;
14464   }
14465   if( increment>0 ){
14466     mem.nAlloc[i]++;
14467     mem.nCurrent[i]++;
14468     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
14469       mem.mxCurrent[i] = mem.nCurrent[i];
14470     }
14471   }else{
14472     mem.nCurrent[i]--;
14473     assert( mem.nCurrent[i]>=0 );
14474   }
14475 }
14476
14477 /*
14478 ** Given an allocation, find the MemBlockHdr for that allocation.
14479 **
14480 ** This routine checks the guards at either end of the allocation and
14481 ** if they are incorrect it asserts.
14482 */
14483 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
14484   struct MemBlockHdr *p;
14485   int *pInt;
14486   u8 *pU8;
14487   int nReserve;
14488
14489   p = (struct MemBlockHdr*)pAllocation;
14490   p--;
14491   assert( p->iForeGuard==(int)FOREGUARD );
14492   nReserve = ROUND8(p->iSize);
14493   pInt = (int*)pAllocation;
14494   pU8 = (u8*)pAllocation;
14495   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
14496   /* This checks any of the "extra" bytes allocated due
14497   ** to rounding up to an 8 byte boundary to ensure 
14498   ** they haven't been overwritten.
14499   */
14500   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
14501   return p;
14502 }
14503
14504 /*
14505 ** Return the number of bytes currently allocated at address p.
14506 */
14507 static int sqlite3MemSize(void *p){
14508   struct MemBlockHdr *pHdr;
14509   if( !p ){
14510     return 0;
14511   }
14512   pHdr = sqlite3MemsysGetHeader(p);
14513   return pHdr->iSize;
14514 }
14515
14516 /*
14517 ** Initialize the memory allocation subsystem.
14518 */
14519 static int sqlite3MemInit(void *NotUsed){
14520   UNUSED_PARAMETER(NotUsed);
14521   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
14522   if( !sqlite3GlobalConfig.bMemstat ){
14523     /* If memory status is enabled, then the malloc.c wrapper will already
14524     ** hold the STATIC_MEM mutex when the routines here are invoked. */
14525     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14526   }
14527   return SQLITE_OK;
14528 }
14529
14530 /*
14531 ** Deinitialize the memory allocation subsystem.
14532 */
14533 static void sqlite3MemShutdown(void *NotUsed){
14534   UNUSED_PARAMETER(NotUsed);
14535   mem.mutex = 0;
14536 }
14537
14538 /*
14539 ** Round up a request size to the next valid allocation size.
14540 */
14541 static int sqlite3MemRoundup(int n){
14542   return ROUND8(n);
14543 }
14544
14545 /*
14546 ** Fill a buffer with pseudo-random bytes.  This is used to preset
14547 ** the content of a new memory allocation to unpredictable values and
14548 ** to clear the content of a freed allocation to unpredictable values.
14549 */
14550 static void randomFill(char *pBuf, int nByte){
14551   unsigned int x, y, r;
14552   x = SQLITE_PTR_TO_INT(pBuf);
14553   y = nByte | 1;
14554   while( nByte >= 4 ){
14555     x = (x>>1) ^ (-(x&1) & 0xd0000001);
14556     y = y*1103515245 + 12345;
14557     r = x ^ y;
14558     *(int*)pBuf = r;
14559     pBuf += 4;
14560     nByte -= 4;
14561   }
14562   while( nByte-- > 0 ){
14563     x = (x>>1) ^ (-(x&1) & 0xd0000001);
14564     y = y*1103515245 + 12345;
14565     r = x ^ y;
14566     *(pBuf++) = r & 0xff;
14567   }
14568 }
14569
14570 /*
14571 ** Allocate nByte bytes of memory.
14572 */
14573 static void *sqlite3MemMalloc(int nByte){
14574   struct MemBlockHdr *pHdr;
14575   void **pBt;
14576   char *z;
14577   int *pInt;
14578   void *p = 0;
14579   int totalSize;
14580   int nReserve;
14581   sqlite3_mutex_enter(mem.mutex);
14582   assert( mem.disallow==0 );
14583   nReserve = ROUND8(nByte);
14584   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
14585                mem.nBacktrace*sizeof(void*) + mem.nTitle;
14586   p = malloc(totalSize);
14587   if( p ){
14588     z = p;
14589     pBt = (void**)&z[mem.nTitle];
14590     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
14591     pHdr->pNext = 0;
14592     pHdr->pPrev = mem.pLast;
14593     if( mem.pLast ){
14594       mem.pLast->pNext = pHdr;
14595     }else{
14596       mem.pFirst = pHdr;
14597     }
14598     mem.pLast = pHdr;
14599     pHdr->iForeGuard = FOREGUARD;
14600     pHdr->eType = MEMTYPE_HEAP;
14601     pHdr->nBacktraceSlots = mem.nBacktrace;
14602     pHdr->nTitle = mem.nTitle;
14603     if( mem.nBacktrace ){
14604       void *aAddr[40];
14605       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
14606       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
14607       assert(pBt[0]);
14608       if( mem.xBacktrace ){
14609         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
14610       }
14611     }else{
14612       pHdr->nBacktrace = 0;
14613     }
14614     if( mem.nTitle ){
14615       memcpy(z, mem.zTitle, mem.nTitle);
14616     }
14617     pHdr->iSize = nByte;
14618     adjustStats(nByte, +1);
14619     pInt = (int*)&pHdr[1];
14620     pInt[nReserve/sizeof(int)] = REARGUARD;
14621     randomFill((char*)pInt, nByte);
14622     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
14623     p = (void*)pInt;
14624   }
14625   sqlite3_mutex_leave(mem.mutex);
14626   return p; 
14627 }
14628
14629 /*
14630 ** Free memory.
14631 */
14632 static void sqlite3MemFree(void *pPrior){
14633   struct MemBlockHdr *pHdr;
14634   void **pBt;
14635   char *z;
14636   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
14637        || mem.mutex!=0 );
14638   pHdr = sqlite3MemsysGetHeader(pPrior);
14639   pBt = (void**)pHdr;
14640   pBt -= pHdr->nBacktraceSlots;
14641   sqlite3_mutex_enter(mem.mutex);
14642   if( pHdr->pPrev ){
14643     assert( pHdr->pPrev->pNext==pHdr );
14644     pHdr->pPrev->pNext = pHdr->pNext;
14645   }else{
14646     assert( mem.pFirst==pHdr );
14647     mem.pFirst = pHdr->pNext;
14648   }
14649   if( pHdr->pNext ){
14650     assert( pHdr->pNext->pPrev==pHdr );
14651     pHdr->pNext->pPrev = pHdr->pPrev;
14652   }else{
14653     assert( mem.pLast==pHdr );
14654     mem.pLast = pHdr->pPrev;
14655   }
14656   z = (char*)pBt;
14657   z -= pHdr->nTitle;
14658   adjustStats(pHdr->iSize, -1);
14659   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
14660                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
14661   free(z);
14662   sqlite3_mutex_leave(mem.mutex);  
14663 }
14664
14665 /*
14666 ** Change the size of an existing memory allocation.
14667 **
14668 ** For this debugging implementation, we *always* make a copy of the
14669 ** allocation into a new place in memory.  In this way, if the 
14670 ** higher level code is using pointer to the old allocation, it is 
14671 ** much more likely to break and we are much more liking to find
14672 ** the error.
14673 */
14674 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14675   struct MemBlockHdr *pOldHdr;
14676   void *pNew;
14677   assert( mem.disallow==0 );
14678   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
14679   pOldHdr = sqlite3MemsysGetHeader(pPrior);
14680   pNew = sqlite3MemMalloc(nByte);
14681   if( pNew ){
14682     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
14683     if( nByte>pOldHdr->iSize ){
14684       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
14685     }
14686     sqlite3MemFree(pPrior);
14687   }
14688   return pNew;
14689 }
14690
14691 /*
14692 ** Populate the low-level memory allocation function pointers in
14693 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14694 */
14695 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14696   static const sqlite3_mem_methods defaultMethods = {
14697      sqlite3MemMalloc,
14698      sqlite3MemFree,
14699      sqlite3MemRealloc,
14700      sqlite3MemSize,
14701      sqlite3MemRoundup,
14702      sqlite3MemInit,
14703      sqlite3MemShutdown,
14704      0
14705   };
14706   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14707 }
14708
14709 /*
14710 ** Set the "type" of an allocation.
14711 */
14712 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
14713   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14714     struct MemBlockHdr *pHdr;
14715     pHdr = sqlite3MemsysGetHeader(p);
14716     assert( pHdr->iForeGuard==FOREGUARD );
14717     pHdr->eType = eType;
14718   }
14719 }
14720
14721 /*
14722 ** Return TRUE if the mask of type in eType matches the type of the
14723 ** allocation p.  Also return true if p==NULL.
14724 **
14725 ** This routine is designed for use within an assert() statement, to
14726 ** verify the type of an allocation.  For example:
14727 **
14728 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
14729 */
14730 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
14731   int rc = 1;
14732   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14733     struct MemBlockHdr *pHdr;
14734     pHdr = sqlite3MemsysGetHeader(p);
14735     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14736     if( (pHdr->eType&eType)==0 ){
14737       rc = 0;
14738     }
14739   }
14740   return rc;
14741 }
14742
14743 /*
14744 ** Return TRUE if the mask of type in eType matches no bits of the type of the
14745 ** allocation p.  Also return true if p==NULL.
14746 **
14747 ** This routine is designed for use within an assert() statement, to
14748 ** verify the type of an allocation.  For example:
14749 **
14750 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
14751 */
14752 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
14753   int rc = 1;
14754   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
14755     struct MemBlockHdr *pHdr;
14756     pHdr = sqlite3MemsysGetHeader(p);
14757     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
14758     if( (pHdr->eType&eType)!=0 ){
14759       rc = 0;
14760     }
14761   }
14762   return rc;
14763 }
14764
14765 /*
14766 ** Set the number of backtrace levels kept for each allocation.
14767 ** A value of zero turns off backtracing.  The number is always rounded
14768 ** up to a multiple of 2.
14769 */
14770 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
14771   if( depth<0 ){ depth = 0; }
14772   if( depth>20 ){ depth = 20; }
14773   depth = (depth+1)&0xfe;
14774   mem.nBacktrace = depth;
14775 }
14776
14777 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
14778   mem.xBacktrace = xBacktrace;
14779 }
14780
14781 /*
14782 ** Set the title string for subsequent allocations.
14783 */
14784 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
14785   unsigned int n = sqlite3Strlen30(zTitle) + 1;
14786   sqlite3_mutex_enter(mem.mutex);
14787   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
14788   memcpy(mem.zTitle, zTitle, n);
14789   mem.zTitle[n] = 0;
14790   mem.nTitle = ROUND8(n);
14791   sqlite3_mutex_leave(mem.mutex);
14792 }
14793
14794 SQLITE_PRIVATE void sqlite3MemdebugSync(){
14795   struct MemBlockHdr *pHdr;
14796   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
14797     void **pBt = (void**)pHdr;
14798     pBt -= pHdr->nBacktraceSlots;
14799     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
14800   }
14801 }
14802
14803 /*
14804 ** Open the file indicated and write a log of all unfreed memory 
14805 ** allocations into that log.
14806 */
14807 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
14808   FILE *out;
14809   struct MemBlockHdr *pHdr;
14810   void **pBt;
14811   int i;
14812   out = fopen(zFilename, "w");
14813   if( out==0 ){
14814     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14815                     zFilename);
14816     return;
14817   }
14818   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
14819     char *z = (char*)pHdr;
14820     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
14821     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
14822             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
14823     if( pHdr->nBacktrace ){
14824       fflush(out);
14825       pBt = (void**)pHdr;
14826       pBt -= pHdr->nBacktraceSlots;
14827       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
14828       fprintf(out, "\n");
14829     }
14830   }
14831   fprintf(out, "COUNTS:\n");
14832   for(i=0; i<NCSIZE-1; i++){
14833     if( mem.nAlloc[i] ){
14834       fprintf(out, "   %5d: %10d %10d %10d\n", 
14835             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
14836     }
14837   }
14838   if( mem.nAlloc[NCSIZE-1] ){
14839     fprintf(out, "   %5d: %10d %10d %10d\n",
14840              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
14841              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
14842   }
14843   fclose(out);
14844 }
14845
14846 /*
14847 ** Return the number of times sqlite3MemMalloc() has been called.
14848 */
14849 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
14850   int i;
14851   int nTotal = 0;
14852   for(i=0; i<NCSIZE; i++){
14853     nTotal += mem.nAlloc[i];
14854   }
14855   return nTotal;
14856 }
14857
14858
14859 #endif /* SQLITE_MEMDEBUG */
14860
14861 /************** End of mem2.c ************************************************/
14862 /************** Begin file mem3.c ********************************************/
14863 /*
14864 ** 2007 October 14
14865 **
14866 ** The author disclaims copyright to this source code.  In place of
14867 ** a legal notice, here is a blessing:
14868 **
14869 **    May you do good and not evil.
14870 **    May you find forgiveness for yourself and forgive others.
14871 **    May you share freely, never taking more than you give.
14872 **
14873 *************************************************************************
14874 ** This file contains the C functions that implement a memory
14875 ** allocation subsystem for use by SQLite. 
14876 **
14877 ** This version of the memory allocation subsystem omits all
14878 ** use of malloc(). The SQLite user supplies a block of memory
14879 ** before calling sqlite3_initialize() from which allocations
14880 ** are made and returned by the xMalloc() and xRealloc() 
14881 ** implementations. Once sqlite3_initialize() has been called,
14882 ** the amount of memory available to SQLite is fixed and cannot
14883 ** be changed.
14884 **
14885 ** This version of the memory allocation subsystem is included
14886 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
14887 */
14888
14889 /*
14890 ** This version of the memory allocator is only built into the library
14891 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
14892 ** mean that the library will use a memory-pool by default, just that
14893 ** it is available. The mempool allocator is activated by calling
14894 ** sqlite3_config().
14895 */
14896 #ifdef SQLITE_ENABLE_MEMSYS3
14897
14898 /*
14899 ** Maximum size (in Mem3Blocks) of a "small" chunk.
14900 */
14901 #define MX_SMALL 10
14902
14903
14904 /*
14905 ** Number of freelist hash slots
14906 */
14907 #define N_HASH  61
14908
14909 /*
14910 ** A memory allocation (also called a "chunk") consists of two or 
14911 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
14912 ** a header that is not returned to the user.
14913 **
14914 ** A chunk is two or more blocks that is either checked out or
14915 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
14916 ** size of the allocation in blocks if the allocation is free.
14917 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
14918 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
14919 ** is true if the previous chunk is checked out and false if the
14920 ** previous chunk is free.  The u.hdr.prevSize field is the size of
14921 ** the previous chunk in blocks if the previous chunk is on the
14922 ** freelist. If the previous chunk is checked out, then
14923 ** u.hdr.prevSize can be part of the data for that chunk and should
14924 ** not be read or written.
14925 **
14926 ** We often identify a chunk by its index in mem3.aPool[].  When
14927 ** this is done, the chunk index refers to the second block of
14928 ** the chunk.  In this way, the first chunk has an index of 1.
14929 ** A chunk index of 0 means "no such chunk" and is the equivalent
14930 ** of a NULL pointer.
14931 **
14932 ** The second block of free chunks is of the form u.list.  The
14933 ** two fields form a double-linked list of chunks of related sizes.
14934 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
14935 ** for smaller chunks and mem3.aiHash[] for larger chunks.
14936 **
14937 ** The second block of a chunk is user data if the chunk is checked 
14938 ** out.  If a chunk is checked out, the user data may extend into
14939 ** the u.hdr.prevSize value of the following chunk.
14940 */
14941 typedef struct Mem3Block Mem3Block;
14942 struct Mem3Block {
14943   union {
14944     struct {
14945       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
14946       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
14947     } hdr;
14948     struct {
14949       u32 next;       /* Index in mem3.aPool[] of next free chunk */
14950       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
14951     } list;
14952   } u;
14953 };
14954
14955 /*
14956 ** All of the static variables used by this module are collected
14957 ** into a single structure named "mem3".  This is to keep the
14958 ** static variables organized and to reduce namespace pollution
14959 ** when this module is combined with other in the amalgamation.
14960 */
14961 static SQLITE_WSD struct Mem3Global {
14962   /*
14963   ** Memory available for allocation. nPool is the size of the array
14964   ** (in Mem3Blocks) pointed to by aPool less 2.
14965   */
14966   u32 nPool;
14967   Mem3Block *aPool;
14968
14969   /*
14970   ** True if we are evaluating an out-of-memory callback.
14971   */
14972   int alarmBusy;
14973   
14974   /*
14975   ** Mutex to control access to the memory allocation subsystem.
14976   */
14977   sqlite3_mutex *mutex;
14978   
14979   /*
14980   ** The minimum amount of free space that we have seen.
14981   */
14982   u32 mnMaster;
14983
14984   /*
14985   ** iMaster is the index of the master chunk.  Most new allocations
14986   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
14987   ** of the current master.  iMaster is 0 if there is not master chunk.
14988   ** The master chunk is not in either the aiHash[] or aiSmall[].
14989   */
14990   u32 iMaster;
14991   u32 szMaster;
14992
14993   /*
14994   ** Array of lists of free blocks according to the block size 
14995   ** for smaller chunks, or a hash on the block size for larger
14996   ** chunks.
14997   */
14998   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
14999   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
15000 } mem3 = { 97535575 };
15001
15002 #define mem3 GLOBAL(struct Mem3Global, mem3)
15003
15004 /*
15005 ** Unlink the chunk at mem3.aPool[i] from list it is currently
15006 ** on.  *pRoot is the list that i is a member of.
15007 */
15008 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
15009   u32 next = mem3.aPool[i].u.list.next;
15010   u32 prev = mem3.aPool[i].u.list.prev;
15011   assert( sqlite3_mutex_held(mem3.mutex) );
15012   if( prev==0 ){
15013     *pRoot = next;
15014   }else{
15015     mem3.aPool[prev].u.list.next = next;
15016   }
15017   if( next ){
15018     mem3.aPool[next].u.list.prev = prev;
15019   }
15020   mem3.aPool[i].u.list.next = 0;
15021   mem3.aPool[i].u.list.prev = 0;
15022 }
15023
15024 /*
15025 ** Unlink the chunk at index i from 
15026 ** whatever list is currently a member of.
15027 */
15028 static void memsys3Unlink(u32 i){
15029   u32 size, hash;
15030   assert( sqlite3_mutex_held(mem3.mutex) );
15031   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15032   assert( i>=1 );
15033   size = mem3.aPool[i-1].u.hdr.size4x/4;
15034   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15035   assert( size>=2 );
15036   if( size <= MX_SMALL ){
15037     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
15038   }else{
15039     hash = size % N_HASH;
15040     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15041   }
15042 }
15043
15044 /*
15045 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
15046 ** at *pRoot.
15047 */
15048 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
15049   assert( sqlite3_mutex_held(mem3.mutex) );
15050   mem3.aPool[i].u.list.next = *pRoot;
15051   mem3.aPool[i].u.list.prev = 0;
15052   if( *pRoot ){
15053     mem3.aPool[*pRoot].u.list.prev = i;
15054   }
15055   *pRoot = i;
15056 }
15057
15058 /*
15059 ** Link the chunk at index i into either the appropriate
15060 ** small chunk list, or into the large chunk hash table.
15061 */
15062 static void memsys3Link(u32 i){
15063   u32 size, hash;
15064   assert( sqlite3_mutex_held(mem3.mutex) );
15065   assert( i>=1 );
15066   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15067   size = mem3.aPool[i-1].u.hdr.size4x/4;
15068   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15069   assert( size>=2 );
15070   if( size <= MX_SMALL ){
15071     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
15072   }else{
15073     hash = size % N_HASH;
15074     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
15075   }
15076 }
15077
15078 /*
15079 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15080 ** will already be held (obtained by code in malloc.c) if
15081 ** sqlite3GlobalConfig.bMemStat is true.
15082 */
15083 static void memsys3Enter(void){
15084   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
15085     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15086   }
15087   sqlite3_mutex_enter(mem3.mutex);
15088 }
15089 static void memsys3Leave(void){
15090   sqlite3_mutex_leave(mem3.mutex);
15091 }
15092
15093 /*
15094 ** Called when we are unable to satisfy an allocation of nBytes.
15095 */
15096 static void memsys3OutOfMemory(int nByte){
15097   if( !mem3.alarmBusy ){
15098     mem3.alarmBusy = 1;
15099     assert( sqlite3_mutex_held(mem3.mutex) );
15100     sqlite3_mutex_leave(mem3.mutex);
15101     sqlite3_release_memory(nByte);
15102     sqlite3_mutex_enter(mem3.mutex);
15103     mem3.alarmBusy = 0;
15104   }
15105 }
15106
15107
15108 /*
15109 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
15110 ** size parameters for check-out and return a pointer to the 
15111 ** user portion of the chunk.
15112 */
15113 static void *memsys3Checkout(u32 i, u32 nBlock){
15114   u32 x;
15115   assert( sqlite3_mutex_held(mem3.mutex) );
15116   assert( i>=1 );
15117   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15118   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15119   x = mem3.aPool[i-1].u.hdr.size4x;
15120   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15121   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15122   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15123   return &mem3.aPool[i];
15124 }
15125
15126 /*
15127 ** Carve a piece off of the end of the mem3.iMaster free chunk.
15128 ** Return a pointer to the new allocation.  Or, if the master chunk
15129 ** is not large enough, return 0.
15130 */
15131 static void *memsys3FromMaster(u32 nBlock){
15132   assert( sqlite3_mutex_held(mem3.mutex) );
15133   assert( mem3.szMaster>=nBlock );
15134   if( nBlock>=mem3.szMaster-1 ){
15135     /* Use the entire master */
15136     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15137     mem3.iMaster = 0;
15138     mem3.szMaster = 0;
15139     mem3.mnMaster = 0;
15140     return p;
15141   }else{
15142     /* Split the master block.  Return the tail. */
15143     u32 newi, x;
15144     newi = mem3.iMaster + mem3.szMaster - nBlock;
15145     assert( newi > mem3.iMaster+1 );
15146     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15147     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15148     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15149     mem3.szMaster -= nBlock;
15150     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15151     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15152     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15153     if( mem3.szMaster < mem3.mnMaster ){
15154       mem3.mnMaster = mem3.szMaster;
15155     }
15156     return (void*)&mem3.aPool[newi];
15157   }
15158 }
15159
15160 /*
15161 ** *pRoot is the head of a list of free chunks of the same size
15162 ** or same size hash.  In other words, *pRoot is an entry in either
15163 ** mem3.aiSmall[] or mem3.aiHash[].  
15164 **
15165 ** This routine examines all entries on the given list and tries
15166 ** to coalesce each entries with adjacent free chunks.  
15167 **
15168 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
15169 ** the current mem3.iMaster with the new larger chunk.  In order for
15170 ** this mem3.iMaster replacement to work, the master chunk must be
15171 ** linked into the hash tables.  That is not the normal state of
15172 ** affairs, of course.  The calling routine must link the master
15173 ** chunk before invoking this routine, then must unlink the (possibly
15174 ** changed) master chunk once this routine has finished.
15175 */
15176 static void memsys3Merge(u32 *pRoot){
15177   u32 iNext, prev, size, i, x;
15178
15179   assert( sqlite3_mutex_held(mem3.mutex) );
15180   for(i=*pRoot; i>0; i=iNext){
15181     iNext = mem3.aPool[i].u.list.next;
15182     size = mem3.aPool[i-1].u.hdr.size4x;
15183     assert( (size&1)==0 );
15184     if( (size&2)==0 ){
15185       memsys3UnlinkFromList(i, pRoot);
15186       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15187       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15188       if( prev==iNext ){
15189         iNext = mem3.aPool[prev].u.list.next;
15190       }
15191       memsys3Unlink(prev);
15192       size = i + size/4 - prev;
15193       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15194       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15195       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15196       memsys3Link(prev);
15197       i = prev;
15198     }else{
15199       size /= 4;
15200     }
15201     if( size>mem3.szMaster ){
15202       mem3.iMaster = i;
15203       mem3.szMaster = size;
15204     }
15205   }
15206 }
15207
15208 /*
15209 ** Return a block of memory of at least nBytes in size.
15210 ** Return NULL if unable.
15211 **
15212 ** This function assumes that the necessary mutexes, if any, are
15213 ** already held by the caller. Hence "Unsafe".
15214 */
15215 static void *memsys3MallocUnsafe(int nByte){
15216   u32 i;
15217   u32 nBlock;
15218   u32 toFree;
15219
15220   assert( sqlite3_mutex_held(mem3.mutex) );
15221   assert( sizeof(Mem3Block)==8 );
15222   if( nByte<=12 ){
15223     nBlock = 2;
15224   }else{
15225     nBlock = (nByte + 11)/8;
15226   }
15227   assert( nBlock>=2 );
15228
15229   /* STEP 1:
15230   ** Look for an entry of the correct size in either the small
15231   ** chunk table or in the large chunk hash table.  This is
15232   ** successful most of the time (about 9 times out of 10).
15233   */
15234   if( nBlock <= MX_SMALL ){
15235     i = mem3.aiSmall[nBlock-2];
15236     if( i>0 ){
15237       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15238       return memsys3Checkout(i, nBlock);
15239     }
15240   }else{
15241     int hash = nBlock % N_HASH;
15242     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15243       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15244         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15245         return memsys3Checkout(i, nBlock);
15246       }
15247     }
15248   }
15249
15250   /* STEP 2:
15251   ** Try to satisfy the allocation by carving a piece off of the end
15252   ** of the master chunk.  This step usually works if step 1 fails.
15253   */
15254   if( mem3.szMaster>=nBlock ){
15255     return memsys3FromMaster(nBlock);
15256   }
15257
15258
15259   /* STEP 3:  
15260   ** Loop through the entire memory pool.  Coalesce adjacent free
15261   ** chunks.  Recompute the master chunk as the largest free chunk.
15262   ** Then try again to satisfy the allocation by carving a piece off
15263   ** of the end of the master chunk.  This step happens very
15264   ** rarely (we hope!)
15265   */
15266   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15267     memsys3OutOfMemory(toFree);
15268     if( mem3.iMaster ){
15269       memsys3Link(mem3.iMaster);
15270       mem3.iMaster = 0;
15271       mem3.szMaster = 0;
15272     }
15273     for(i=0; i<N_HASH; i++){
15274       memsys3Merge(&mem3.aiHash[i]);
15275     }
15276     for(i=0; i<MX_SMALL-1; i++){
15277       memsys3Merge(&mem3.aiSmall[i]);
15278     }
15279     if( mem3.szMaster ){
15280       memsys3Unlink(mem3.iMaster);
15281       if( mem3.szMaster>=nBlock ){
15282         return memsys3FromMaster(nBlock);
15283       }
15284     }
15285   }
15286
15287   /* If none of the above worked, then we fail. */
15288   return 0;
15289 }
15290
15291 /*
15292 ** Free an outstanding memory allocation.
15293 **
15294 ** This function assumes that the necessary mutexes, if any, are
15295 ** already held by the caller. Hence "Unsafe".
15296 */
15297 void memsys3FreeUnsafe(void *pOld){
15298   Mem3Block *p = (Mem3Block*)pOld;
15299   int i;
15300   u32 size, x;
15301   assert( sqlite3_mutex_held(mem3.mutex) );
15302   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
15303   i = p - mem3.aPool;
15304   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
15305   size = mem3.aPool[i-1].u.hdr.size4x/4;
15306   assert( i+size<=mem3.nPool+1 );
15307   mem3.aPool[i-1].u.hdr.size4x &= ~1;
15308   mem3.aPool[i+size-1].u.hdr.prevSize = size;
15309   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
15310   memsys3Link(i);
15311
15312   /* Try to expand the master using the newly freed chunk */
15313   if( mem3.iMaster ){
15314     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
15315       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
15316       mem3.iMaster -= size;
15317       mem3.szMaster += size;
15318       memsys3Unlink(mem3.iMaster);
15319       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15320       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15321       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15322     }
15323     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15324     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
15325       memsys3Unlink(mem3.iMaster+mem3.szMaster);
15326       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
15327       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15328       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15329     }
15330   }
15331 }
15332
15333 /*
15334 ** Return the size of an outstanding allocation, in bytes.  The
15335 ** size returned omits the 8-byte header overhead.  This only
15336 ** works for chunks that are currently checked out.
15337 */
15338 static int memsys3Size(void *p){
15339   Mem3Block *pBlock;
15340   if( p==0 ) return 0;
15341   pBlock = (Mem3Block*)p;
15342   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
15343   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
15344 }
15345
15346 /*
15347 ** Round up a request size to the next valid allocation size.
15348 */
15349 static int memsys3Roundup(int n){
15350   if( n<=12 ){
15351     return 12;
15352   }else{
15353     return ((n+11)&~7) - 4;
15354   }
15355 }
15356
15357 /*
15358 ** Allocate nBytes of memory.
15359 */
15360 static void *memsys3Malloc(int nBytes){
15361   sqlite3_int64 *p;
15362   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
15363   memsys3Enter();
15364   p = memsys3MallocUnsafe(nBytes);
15365   memsys3Leave();
15366   return (void*)p; 
15367 }
15368
15369 /*
15370 ** Free memory.
15371 */
15372 void memsys3Free(void *pPrior){
15373   assert( pPrior );
15374   memsys3Enter();
15375   memsys3FreeUnsafe(pPrior);
15376   memsys3Leave();
15377 }
15378
15379 /*
15380 ** Change the size of an existing memory allocation
15381 */
15382 void *memsys3Realloc(void *pPrior, int nBytes){
15383   int nOld;
15384   void *p;
15385   if( pPrior==0 ){
15386     return sqlite3_malloc(nBytes);
15387   }
15388   if( nBytes<=0 ){
15389     sqlite3_free(pPrior);
15390     return 0;
15391   }
15392   nOld = memsys3Size(pPrior);
15393   if( nBytes<=nOld && nBytes>=nOld-128 ){
15394     return pPrior;
15395   }
15396   memsys3Enter();
15397   p = memsys3MallocUnsafe(nBytes);
15398   if( p ){
15399     if( nOld<nBytes ){
15400       memcpy(p, pPrior, nOld);
15401     }else{
15402       memcpy(p, pPrior, nBytes);
15403     }
15404     memsys3FreeUnsafe(pPrior);
15405   }
15406   memsys3Leave();
15407   return p;
15408 }
15409
15410 /*
15411 ** Initialize this module.
15412 */
15413 static int memsys3Init(void *NotUsed){
15414   UNUSED_PARAMETER(NotUsed);
15415   if( !sqlite3GlobalConfig.pHeap ){
15416     return SQLITE_ERROR;
15417   }
15418
15419   /* Store a pointer to the memory block in global structure mem3. */
15420   assert( sizeof(Mem3Block)==8 );
15421   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
15422   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
15423
15424   /* Initialize the master block. */
15425   mem3.szMaster = mem3.nPool;
15426   mem3.mnMaster = mem3.szMaster;
15427   mem3.iMaster = 1;
15428   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
15429   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
15430   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
15431
15432   return SQLITE_OK;
15433 }
15434
15435 /*
15436 ** Deinitialize this module.
15437 */
15438 static void memsys3Shutdown(void *NotUsed){
15439   UNUSED_PARAMETER(NotUsed);
15440   mem3.mutex = 0;
15441   return;
15442 }
15443
15444
15445
15446 /*
15447 ** Open the file indicated and write a log of all unfreed memory 
15448 ** allocations into that log.
15449 */
15450 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
15451 #ifdef SQLITE_DEBUG
15452   FILE *out;
15453   u32 i, j;
15454   u32 size;
15455   if( zFilename==0 || zFilename[0]==0 ){
15456     out = stdout;
15457   }else{
15458     out = fopen(zFilename, "w");
15459     if( out==0 ){
15460       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15461                       zFilename);
15462       return;
15463     }
15464   }
15465   memsys3Enter();
15466   fprintf(out, "CHUNKS:\n");
15467   for(i=1; i<=mem3.nPool; i+=size/4){
15468     size = mem3.aPool[i-1].u.hdr.size4x;
15469     if( size/4<=1 ){
15470       fprintf(out, "%p size error\n", &mem3.aPool[i]);
15471       assert( 0 );
15472       break;
15473     }
15474     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
15475       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
15476       assert( 0 );
15477       break;
15478     }
15479     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
15480       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
15481       assert( 0 );
15482       break;
15483     }
15484     if( size&1 ){
15485       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
15486     }else{
15487       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
15488                   i==mem3.iMaster ? " **master**" : "");
15489     }
15490   }
15491   for(i=0; i<MX_SMALL-1; i++){
15492     if( mem3.aiSmall[i]==0 ) continue;
15493     fprintf(out, "small(%2d):", i);
15494     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
15495       fprintf(out, " %p(%d)", &mem3.aPool[j],
15496               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15497     }
15498     fprintf(out, "\n"); 
15499   }
15500   for(i=0; i<N_HASH; i++){
15501     if( mem3.aiHash[i]==0 ) continue;
15502     fprintf(out, "hash(%2d):", i);
15503     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
15504       fprintf(out, " %p(%d)", &mem3.aPool[j],
15505               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
15506     }
15507     fprintf(out, "\n"); 
15508   }
15509   fprintf(out, "master=%d\n", mem3.iMaster);
15510   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
15511   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
15512   sqlite3_mutex_leave(mem3.mutex);
15513   if( out==stdout ){
15514     fflush(stdout);
15515   }else{
15516     fclose(out);
15517   }
15518 #else
15519   UNUSED_PARAMETER(zFilename);
15520 #endif
15521 }
15522
15523 /*
15524 ** This routine is the only routine in this file with external 
15525 ** linkage.
15526 **
15527 ** Populate the low-level memory allocation function pointers in
15528 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
15529 ** arguments specify the block of memory to manage.
15530 **
15531 ** This routine is only called by sqlite3_config(), and therefore
15532 ** is not required to be threadsafe (it is not).
15533 */
15534 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
15535   static const sqlite3_mem_methods mempoolMethods = {
15536      memsys3Malloc,
15537      memsys3Free,
15538      memsys3Realloc,
15539      memsys3Size,
15540      memsys3Roundup,
15541      memsys3Init,
15542      memsys3Shutdown,
15543      0
15544   };
15545   return &mempoolMethods;
15546 }
15547
15548 #endif /* SQLITE_ENABLE_MEMSYS3 */
15549
15550 /************** End of mem3.c ************************************************/
15551 /************** Begin file mem5.c ********************************************/
15552 /*
15553 ** 2007 October 14
15554 **
15555 ** The author disclaims copyright to this source code.  In place of
15556 ** a legal notice, here is a blessing:
15557 **
15558 **    May you do good and not evil.
15559 **    May you find forgiveness for yourself and forgive others.
15560 **    May you share freely, never taking more than you give.
15561 **
15562 *************************************************************************
15563 ** This file contains the C functions that implement a memory
15564 ** allocation subsystem for use by SQLite. 
15565 **
15566 ** This version of the memory allocation subsystem omits all
15567 ** use of malloc(). The application gives SQLite a block of memory
15568 ** before calling sqlite3_initialize() from which allocations
15569 ** are made and returned by the xMalloc() and xRealloc() 
15570 ** implementations. Once sqlite3_initialize() has been called,
15571 ** the amount of memory available to SQLite is fixed and cannot
15572 ** be changed.
15573 **
15574 ** This version of the memory allocation subsystem is included
15575 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
15576 **
15577 ** This memory allocator uses the following algorithm:
15578 **
15579 **   1.  All memory allocations sizes are rounded up to a power of 2.
15580 **
15581 **   2.  If two adjacent free blocks are the halves of a larger block,
15582 **       then the two blocks are coalesed into the single larger block.
15583 **
15584 **   3.  New memory is allocated from the first available free block.
15585 **
15586 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
15587 ** Concerning Dynamic Storage Allocation". Journal of the Association for
15588 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
15589 ** 
15590 ** Let n be the size of the largest allocation divided by the minimum
15591 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
15592 ** be the maximum amount of memory ever outstanding at one time.  Let
15593 ** N be the total amount of memory available for allocation.  Robson
15594 ** proved that this memory allocator will never breakdown due to 
15595 ** fragmentation as long as the following constraint holds:
15596 **
15597 **      N >=  M*(1 + log2(n)/2) - n + 1
15598 **
15599 ** The sqlite3_status() logic tracks the maximum values of n and M so
15600 ** that an application can, at any time, verify this constraint.
15601 */
15602
15603 /*
15604 ** This version of the memory allocator is used only when 
15605 ** SQLITE_ENABLE_MEMSYS5 is defined.
15606 */
15607 #ifdef SQLITE_ENABLE_MEMSYS5
15608
15609 /*
15610 ** A minimum allocation is an instance of the following structure.
15611 ** Larger allocations are an array of these structures where the
15612 ** size of the array is a power of 2.
15613 **
15614 ** The size of this object must be a power of two.  That fact is
15615 ** verified in memsys5Init().
15616 */
15617 typedef struct Mem5Link Mem5Link;
15618 struct Mem5Link {
15619   int next;       /* Index of next free chunk */
15620   int prev;       /* Index of previous free chunk */
15621 };
15622
15623 /*
15624 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
15625 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
15626 ** it is not actually possible to reach this limit.
15627 */
15628 #define LOGMAX 30
15629
15630 /*
15631 ** Masks used for mem5.aCtrl[] elements.
15632 */
15633 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
15634 #define CTRL_FREE     0x20    /* True if not checked out */
15635
15636 /*
15637 ** All of the static variables used by this module are collected
15638 ** into a single structure named "mem5".  This is to keep the
15639 ** static variables organized and to reduce namespace pollution
15640 ** when this module is combined with other in the amalgamation.
15641 */
15642 static SQLITE_WSD struct Mem5Global {
15643   /*
15644   ** Memory available for allocation
15645   */
15646   int szAtom;      /* Smallest possible allocation in bytes */
15647   int nBlock;      /* Number of szAtom sized blocks in zPool */
15648   u8 *zPool;       /* Memory available to be allocated */
15649   
15650   /*
15651   ** Mutex to control access to the memory allocation subsystem.
15652   */
15653   sqlite3_mutex *mutex;
15654
15655   /*
15656   ** Performance statistics
15657   */
15658   u64 nAlloc;         /* Total number of calls to malloc */
15659   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
15660   u64 totalExcess;    /* Total internal fragmentation */
15661   u32 currentOut;     /* Current checkout, including internal fragmentation */
15662   u32 currentCount;   /* Current number of distinct checkouts */
15663   u32 maxOut;         /* Maximum instantaneous currentOut */
15664   u32 maxCount;       /* Maximum instantaneous currentCount */
15665   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
15666   
15667   /*
15668   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
15669   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
15670   ** and so forth.
15671   */
15672   int aiFreelist[LOGMAX+1];
15673
15674   /*
15675   ** Space for tracking which blocks are checked out and the size
15676   ** of each block.  One byte per block.
15677   */
15678   u8 *aCtrl;
15679
15680 } mem5 = { 0 };
15681
15682 /*
15683 ** Access the static variable through a macro for SQLITE_OMIT_WSD
15684 */
15685 #define mem5 GLOBAL(struct Mem5Global, mem5)
15686
15687 /*
15688 ** Assuming mem5.zPool is divided up into an array of Mem5Link
15689 ** structures, return a pointer to the idx-th such lik.
15690 */
15691 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
15692
15693 /*
15694 ** Unlink the chunk at mem5.aPool[i] from list it is currently
15695 ** on.  It should be found on mem5.aiFreelist[iLogsize].
15696 */
15697 static void memsys5Unlink(int i, int iLogsize){
15698   int next, prev;
15699   assert( i>=0 && i<mem5.nBlock );
15700   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15701   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15702
15703   next = MEM5LINK(i)->next;
15704   prev = MEM5LINK(i)->prev;
15705   if( prev<0 ){
15706     mem5.aiFreelist[iLogsize] = next;
15707   }else{
15708     MEM5LINK(prev)->next = next;
15709   }
15710   if( next>=0 ){
15711     MEM5LINK(next)->prev = prev;
15712   }
15713 }
15714
15715 /*
15716 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
15717 ** free list.
15718 */
15719 static void memsys5Link(int i, int iLogsize){
15720   int x;
15721   assert( sqlite3_mutex_held(mem5.mutex) );
15722   assert( i>=0 && i<mem5.nBlock );
15723   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15724   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
15725
15726   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
15727   MEM5LINK(i)->prev = -1;
15728   if( x>=0 ){
15729     assert( x<mem5.nBlock );
15730     MEM5LINK(x)->prev = i;
15731   }
15732   mem5.aiFreelist[iLogsize] = i;
15733 }
15734
15735 /*
15736 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15737 ** will already be held (obtained by code in malloc.c) if
15738 ** sqlite3GlobalConfig.bMemStat is true.
15739 */
15740 static void memsys5Enter(void){
15741   sqlite3_mutex_enter(mem5.mutex);
15742 }
15743 static void memsys5Leave(void){
15744   sqlite3_mutex_leave(mem5.mutex);
15745 }
15746
15747 /*
15748 ** Return the size of an outstanding allocation, in bytes.  The
15749 ** size returned omits the 8-byte header overhead.  This only
15750 ** works for chunks that are currently checked out.
15751 */
15752 static int memsys5Size(void *p){
15753   int iSize = 0;
15754   if( p ){
15755     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
15756     assert( i>=0 && i<mem5.nBlock );
15757     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
15758   }
15759   return iSize;
15760 }
15761
15762 /*
15763 ** Find the first entry on the freelist iLogsize.  Unlink that
15764 ** entry and return its index. 
15765 */
15766 static int memsys5UnlinkFirst(int iLogsize){
15767   int i;
15768   int iFirst;
15769
15770   assert( iLogsize>=0 && iLogsize<=LOGMAX );
15771   i = iFirst = mem5.aiFreelist[iLogsize];
15772   assert( iFirst>=0 );
15773   while( i>0 ){
15774     if( i<iFirst ) iFirst = i;
15775     i = MEM5LINK(i)->next;
15776   }
15777   memsys5Unlink(iFirst, iLogsize);
15778   return iFirst;
15779 }
15780
15781 /*
15782 ** Return a block of memory of at least nBytes in size.
15783 ** Return NULL if unable.  Return NULL if nBytes==0.
15784 **
15785 ** The caller guarantees that nByte positive.
15786 **
15787 ** The caller has obtained a mutex prior to invoking this
15788 ** routine so there is never any chance that two or more
15789 ** threads can be in this routine at the same time.
15790 */
15791 static void *memsys5MallocUnsafe(int nByte){
15792   int i;           /* Index of a mem5.aPool[] slot */
15793   int iBin;        /* Index into mem5.aiFreelist[] */
15794   int iFullSz;     /* Size of allocation rounded up to power of 2 */
15795   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
15796
15797   /* nByte must be a positive */
15798   assert( nByte>0 );
15799
15800   /* Keep track of the maximum allocation request.  Even unfulfilled
15801   ** requests are counted */
15802   if( (u32)nByte>mem5.maxRequest ){
15803     mem5.maxRequest = nByte;
15804   }
15805
15806   /* Abort if the requested allocation size is larger than the largest
15807   ** power of two that we can represent using 32-bit signed integers.
15808   */
15809   if( nByte > 0x40000000 ){
15810     return 0;
15811   }
15812
15813   /* Round nByte up to the next valid power of two */
15814   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
15815
15816   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
15817   ** block.  If not, then split a block of the next larger power of
15818   ** two in order to create a new free block of size iLogsize.
15819   */
15820   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
15821   if( iBin>LOGMAX ){
15822     testcase( sqlite3GlobalConfig.xLog!=0 );
15823     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
15824     return 0;
15825   }
15826   i = memsys5UnlinkFirst(iBin);
15827   while( iBin>iLogsize ){
15828     int newSize;
15829
15830     iBin--;
15831     newSize = 1 << iBin;
15832     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
15833     memsys5Link(i+newSize, iBin);
15834   }
15835   mem5.aCtrl[i] = iLogsize;
15836
15837   /* Update allocator performance statistics. */
15838   mem5.nAlloc++;
15839   mem5.totalAlloc += iFullSz;
15840   mem5.totalExcess += iFullSz - nByte;
15841   mem5.currentCount++;
15842   mem5.currentOut += iFullSz;
15843   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
15844   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
15845
15846   /* Return a pointer to the allocated memory. */
15847   return (void*)&mem5.zPool[i*mem5.szAtom];
15848 }
15849
15850 /*
15851 ** Free an outstanding memory allocation.
15852 */
15853 static void memsys5FreeUnsafe(void *pOld){
15854   u32 size, iLogsize;
15855   int iBlock;
15856
15857   /* Set iBlock to the index of the block pointed to by pOld in 
15858   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
15859   */
15860   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
15861
15862   /* Check that the pointer pOld points to a valid, non-free block. */
15863   assert( iBlock>=0 && iBlock<mem5.nBlock );
15864   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
15865   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
15866
15867   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
15868   size = 1<<iLogsize;
15869   assert( iBlock+size-1<(u32)mem5.nBlock );
15870
15871   mem5.aCtrl[iBlock] |= CTRL_FREE;
15872   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
15873   assert( mem5.currentCount>0 );
15874   assert( mem5.currentOut>=(size*mem5.szAtom) );
15875   mem5.currentCount--;
15876   mem5.currentOut -= size*mem5.szAtom;
15877   assert( mem5.currentOut>0 || mem5.currentCount==0 );
15878   assert( mem5.currentCount>0 || mem5.currentOut==0 );
15879
15880   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
15881   while( ALWAYS(iLogsize<LOGMAX) ){
15882     int iBuddy;
15883     if( (iBlock>>iLogsize) & 1 ){
15884       iBuddy = iBlock - size;
15885     }else{
15886       iBuddy = iBlock + size;
15887     }
15888     assert( iBuddy>=0 );
15889     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
15890     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
15891     memsys5Unlink(iBuddy, iLogsize);
15892     iLogsize++;
15893     if( iBuddy<iBlock ){
15894       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
15895       mem5.aCtrl[iBlock] = 0;
15896       iBlock = iBuddy;
15897     }else{
15898       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
15899       mem5.aCtrl[iBuddy] = 0;
15900     }
15901     size *= 2;
15902   }
15903   memsys5Link(iBlock, iLogsize);
15904 }
15905
15906 /*
15907 ** Allocate nBytes of memory
15908 */
15909 static void *memsys5Malloc(int nBytes){
15910   sqlite3_int64 *p = 0;
15911   if( nBytes>0 ){
15912     memsys5Enter();
15913     p = memsys5MallocUnsafe(nBytes);
15914     memsys5Leave();
15915   }
15916   return (void*)p; 
15917 }
15918
15919 /*
15920 ** Free memory.
15921 **
15922 ** The outer layer memory allocator prevents this routine from
15923 ** being called with pPrior==0.
15924 */
15925 static void memsys5Free(void *pPrior){
15926   assert( pPrior!=0 );
15927   memsys5Enter();
15928   memsys5FreeUnsafe(pPrior);
15929   memsys5Leave();  
15930 }
15931
15932 /*
15933 ** Change the size of an existing memory allocation.
15934 **
15935 ** The outer layer memory allocator prevents this routine from
15936 ** being called with pPrior==0.  
15937 **
15938 ** nBytes is always a value obtained from a prior call to
15939 ** memsys5Round().  Hence nBytes is always a non-negative power
15940 ** of two.  If nBytes==0 that means that an oversize allocation
15941 ** (an allocation larger than 0x40000000) was requested and this
15942 ** routine should return 0 without freeing pPrior.
15943 */
15944 static void *memsys5Realloc(void *pPrior, int nBytes){
15945   int nOld;
15946   void *p;
15947   assert( pPrior!=0 );
15948   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
15949   assert( nBytes>=0 );
15950   if( nBytes==0 ){
15951     return 0;
15952   }
15953   nOld = memsys5Size(pPrior);
15954   if( nBytes<=nOld ){
15955     return pPrior;
15956   }
15957   memsys5Enter();
15958   p = memsys5MallocUnsafe(nBytes);
15959   if( p ){
15960     memcpy(p, pPrior, nOld);
15961     memsys5FreeUnsafe(pPrior);
15962   }
15963   memsys5Leave();
15964   return p;
15965 }
15966
15967 /*
15968 ** Round up a request size to the next valid allocation size.  If
15969 ** the allocation is too large to be handled by this allocation system,
15970 ** return 0.
15971 **
15972 ** All allocations must be a power of two and must be expressed by a
15973 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
15974 ** or 1073741824 bytes.
15975 */
15976 static int memsys5Roundup(int n){
15977   int iFullSz;
15978   if( n > 0x40000000 ) return 0;
15979   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
15980   return iFullSz;
15981 }
15982
15983 /*
15984 ** Return the ceiling of the logarithm base 2 of iValue.
15985 **
15986 ** Examples:   memsys5Log(1) -> 0
15987 **             memsys5Log(2) -> 1
15988 **             memsys5Log(4) -> 2
15989 **             memsys5Log(5) -> 3
15990 **             memsys5Log(8) -> 3
15991 **             memsys5Log(9) -> 4
15992 */
15993 static int memsys5Log(int iValue){
15994   int iLog;
15995   for(iLog=0; (1<<iLog)<iValue; iLog++);
15996   return iLog;
15997 }
15998
15999 /*
16000 ** Initialize the memory allocator.
16001 **
16002 ** This routine is not threadsafe.  The caller must be holding a mutex
16003 ** to prevent multiple threads from entering at the same time.
16004 */
16005 static int memsys5Init(void *NotUsed){
16006   int ii;            /* Loop counter */
16007   int nByte;         /* Number of bytes of memory available to this allocator */
16008   u8 *zByte;         /* Memory usable by this allocator */
16009   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
16010   int iOffset;       /* An offset into mem5.aCtrl[] */
16011
16012   UNUSED_PARAMETER(NotUsed);
16013
16014   /* For the purposes of this routine, disable the mutex */
16015   mem5.mutex = 0;
16016
16017   /* The size of a Mem5Link object must be a power of two.  Verify that
16018   ** this is case.
16019   */
16020   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
16021
16022   nByte = sqlite3GlobalConfig.nHeap;
16023   zByte = (u8*)sqlite3GlobalConfig.pHeap;
16024   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
16025
16026   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
16027   mem5.szAtom = (1<<nMinLog);
16028   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
16029     mem5.szAtom = mem5.szAtom << 1;
16030   }
16031
16032   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
16033   mem5.zPool = zByte;
16034   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
16035
16036   for(ii=0; ii<=LOGMAX; ii++){
16037     mem5.aiFreelist[ii] = -1;
16038   }
16039
16040   iOffset = 0;
16041   for(ii=LOGMAX; ii>=0; ii--){
16042     int nAlloc = (1<<ii);
16043     if( (iOffset+nAlloc)<=mem5.nBlock ){
16044       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
16045       memsys5Link(iOffset, ii);
16046       iOffset += nAlloc;
16047     }
16048     assert((iOffset+nAlloc)>mem5.nBlock);
16049   }
16050
16051   /* If a mutex is required for normal operation, allocate one */
16052   if( sqlite3GlobalConfig.bMemstat==0 ){
16053     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16054   }
16055
16056   return SQLITE_OK;
16057 }
16058
16059 /*
16060 ** Deinitialize this module.
16061 */
16062 static void memsys5Shutdown(void *NotUsed){
16063   UNUSED_PARAMETER(NotUsed);
16064   mem5.mutex = 0;
16065   return;
16066 }
16067
16068 #ifdef SQLITE_TEST
16069 /*
16070 ** Open the file indicated and write a log of all unfreed memory 
16071 ** allocations into that log.
16072 */
16073 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
16074   FILE *out;
16075   int i, j, n;
16076   int nMinLog;
16077
16078   if( zFilename==0 || zFilename[0]==0 ){
16079     out = stdout;
16080   }else{
16081     out = fopen(zFilename, "w");
16082     if( out==0 ){
16083       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16084                       zFilename);
16085       return;
16086     }
16087   }
16088   memsys5Enter();
16089   nMinLog = memsys5Log(mem5.szAtom);
16090   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
16091     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
16092     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
16093   }
16094   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
16095   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
16096   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
16097   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
16098   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16099   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
16100   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
16101   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
16102   memsys5Leave();
16103   if( out==stdout ){
16104     fflush(stdout);
16105   }else{
16106     fclose(out);
16107   }
16108 }
16109 #endif
16110
16111 /*
16112 ** This routine is the only routine in this file with external 
16113 ** linkage. It returns a pointer to a static sqlite3_mem_methods
16114 ** struct populated with the memsys5 methods.
16115 */
16116 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16117   static const sqlite3_mem_methods memsys5Methods = {
16118      memsys5Malloc,
16119      memsys5Free,
16120      memsys5Realloc,
16121      memsys5Size,
16122      memsys5Roundup,
16123      memsys5Init,
16124      memsys5Shutdown,
16125      0
16126   };
16127   return &memsys5Methods;
16128 }
16129
16130 #endif /* SQLITE_ENABLE_MEMSYS5 */
16131
16132 /************** End of mem5.c ************************************************/
16133 /************** Begin file mutex.c *******************************************/
16134 /*
16135 ** 2007 August 14
16136 **
16137 ** The author disclaims copyright to this source code.  In place of
16138 ** a legal notice, here is a blessing:
16139 **
16140 **    May you do good and not evil.
16141 **    May you find forgiveness for yourself and forgive others.
16142 **    May you share freely, never taking more than you give.
16143 **
16144 *************************************************************************
16145 ** This file contains the C functions that implement mutexes.
16146 **
16147 ** This file contains code that is common across all mutex implementations.
16148 */
16149
16150 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16151 /*
16152 ** For debugging purposes, record when the mutex subsystem is initialized
16153 ** and uninitialized so that we can assert() if there is an attempt to
16154 ** allocate a mutex while the system is uninitialized.
16155 */
16156 static SQLITE_WSD int mutexIsInit = 0;
16157 #endif /* SQLITE_DEBUG */
16158
16159
16160 #ifndef SQLITE_MUTEX_OMIT
16161 /*
16162 ** Initialize the mutex system.
16163 */
16164 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
16165   int rc = SQLITE_OK;
16166   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16167     /* If the xMutexAlloc method has not been set, then the user did not
16168     ** install a mutex implementation via sqlite3_config() prior to 
16169     ** sqlite3_initialize() being called. This block copies pointers to
16170     ** the default implementation into the sqlite3GlobalConfig structure.
16171     */
16172     sqlite3_mutex_methods const *pFrom;
16173     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16174
16175     if( sqlite3GlobalConfig.bCoreMutex ){
16176       pFrom = sqlite3DefaultMutex();
16177     }else{
16178       pFrom = sqlite3NoopMutex();
16179     }
16180     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16181     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16182            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16183     pTo->xMutexAlloc = pFrom->xMutexAlloc;
16184   }
16185   rc = sqlite3GlobalConfig.mutex.xMutexInit();
16186
16187 #ifdef SQLITE_DEBUG
16188   GLOBAL(int, mutexIsInit) = 1;
16189 #endif
16190
16191   return rc;
16192 }
16193
16194 /*
16195 ** Shutdown the mutex system. This call frees resources allocated by
16196 ** sqlite3MutexInit().
16197 */
16198 SQLITE_PRIVATE int sqlite3MutexEnd(void){
16199   int rc = SQLITE_OK;
16200   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16201     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16202   }
16203
16204 #ifdef SQLITE_DEBUG
16205   GLOBAL(int, mutexIsInit) = 0;
16206 #endif
16207
16208   return rc;
16209 }
16210
16211 /*
16212 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16213 */
16214 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16215 #ifndef SQLITE_OMIT_AUTOINIT
16216   if( sqlite3_initialize() ) return 0;
16217 #endif
16218   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16219 }
16220
16221 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16222   if( !sqlite3GlobalConfig.bCoreMutex ){
16223     return 0;
16224   }
16225   assert( GLOBAL(int, mutexIsInit) );
16226   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16227 }
16228
16229 /*
16230 ** Free a dynamic mutex.
16231 */
16232 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16233   if( p ){
16234     sqlite3GlobalConfig.mutex.xMutexFree(p);
16235   }
16236 }
16237
16238 /*
16239 ** Obtain the mutex p. If some other thread already has the mutex, block
16240 ** until it can be obtained.
16241 */
16242 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16243   if( p ){
16244     sqlite3GlobalConfig.mutex.xMutexEnter(p);
16245   }
16246 }
16247
16248 /*
16249 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16250 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16251 */
16252 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16253   int rc = SQLITE_OK;
16254   if( p ){
16255     return sqlite3GlobalConfig.mutex.xMutexTry(p);
16256   }
16257   return rc;
16258 }
16259
16260 /*
16261 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
16262 ** entered by the same thread.  The behavior is undefined if the mutex 
16263 ** is not currently entered. If a NULL pointer is passed as an argument
16264 ** this function is a no-op.
16265 */
16266 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16267   if( p ){
16268     sqlite3GlobalConfig.mutex.xMutexLeave(p);
16269   }
16270 }
16271
16272 #ifndef NDEBUG
16273 /*
16274 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16275 ** intended for use inside assert() statements.
16276 */
16277 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16278   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16279 }
16280 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16281   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16282 }
16283 #endif
16284
16285 #endif /* SQLITE_MUTEX_OMIT */
16286
16287 /************** End of mutex.c ***********************************************/
16288 /************** Begin file mutex_noop.c **************************************/
16289 /*
16290 ** 2008 October 07
16291 **
16292 ** The author disclaims copyright to this source code.  In place of
16293 ** a legal notice, here is a blessing:
16294 **
16295 **    May you do good and not evil.
16296 **    May you find forgiveness for yourself and forgive others.
16297 **    May you share freely, never taking more than you give.
16298 **
16299 *************************************************************************
16300 ** This file contains the C functions that implement mutexes.
16301 **
16302 ** This implementation in this file does not provide any mutual
16303 ** exclusion and is thus suitable for use only in applications
16304 ** that use SQLite in a single thread.  The routines defined
16305 ** here are place-holders.  Applications can substitute working
16306 ** mutex routines at start-time using the
16307 **
16308 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
16309 **
16310 ** interface.
16311 **
16312 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
16313 ** that does error checking on mutexes to make sure they are being
16314 ** called correctly.
16315 */
16316
16317 #ifndef SQLITE_MUTEX_OMIT
16318
16319 #ifndef SQLITE_DEBUG
16320 /*
16321 ** Stub routines for all mutex methods.
16322 **
16323 ** This routines provide no mutual exclusion or error checking.
16324 */
16325 static int noopMutexInit(void){ return SQLITE_OK; }
16326 static int noopMutexEnd(void){ return SQLITE_OK; }
16327 static sqlite3_mutex *noopMutexAlloc(int id){ 
16328   UNUSED_PARAMETER(id);
16329   return (sqlite3_mutex*)8; 
16330 }
16331 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16332 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16333 static int noopMutexTry(sqlite3_mutex *p){
16334   UNUSED_PARAMETER(p);
16335   return SQLITE_OK;
16336 }
16337 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16338
16339 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16340   static const sqlite3_mutex_methods sMutex = {
16341     noopMutexInit,
16342     noopMutexEnd,
16343     noopMutexAlloc,
16344     noopMutexFree,
16345     noopMutexEnter,
16346     noopMutexTry,
16347     noopMutexLeave,
16348
16349     0,
16350     0,
16351   };
16352
16353   return &sMutex;
16354 }
16355 #endif /* !SQLITE_DEBUG */
16356
16357 #ifdef SQLITE_DEBUG
16358 /*
16359 ** In this implementation, error checking is provided for testing
16360 ** and debugging purposes.  The mutexes still do not provide any
16361 ** mutual exclusion.
16362 */
16363
16364 /*
16365 ** The mutex object
16366 */
16367 typedef struct sqlite3_debug_mutex {
16368   int id;     /* The mutex type */
16369   int cnt;    /* Number of entries without a matching leave */
16370 } sqlite3_debug_mutex;
16371
16372 /*
16373 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16374 ** intended for use inside assert() statements.
16375 */
16376 static int debugMutexHeld(sqlite3_mutex *pX){
16377   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16378   return p==0 || p->cnt>0;
16379 }
16380 static int debugMutexNotheld(sqlite3_mutex *pX){
16381   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16382   return p==0 || p->cnt==0;
16383 }
16384
16385 /*
16386 ** Initialize and deinitialize the mutex subsystem.
16387 */
16388 static int debugMutexInit(void){ return SQLITE_OK; }
16389 static int debugMutexEnd(void){ return SQLITE_OK; }
16390
16391 /*
16392 ** The sqlite3_mutex_alloc() routine allocates a new
16393 ** mutex and returns a pointer to it.  If it returns NULL
16394 ** that means that a mutex could not be allocated. 
16395 */
16396 static sqlite3_mutex *debugMutexAlloc(int id){
16397   static sqlite3_debug_mutex aStatic[6];
16398   sqlite3_debug_mutex *pNew = 0;
16399   switch( id ){
16400     case SQLITE_MUTEX_FAST:
16401     case SQLITE_MUTEX_RECURSIVE: {
16402       pNew = sqlite3Malloc(sizeof(*pNew));
16403       if( pNew ){
16404         pNew->id = id;
16405         pNew->cnt = 0;
16406       }
16407       break;
16408     }
16409     default: {
16410       assert( id-2 >= 0 );
16411       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
16412       pNew = &aStatic[id-2];
16413       pNew->id = id;
16414       break;
16415     }
16416   }
16417   return (sqlite3_mutex*)pNew;
16418 }
16419
16420 /*
16421 ** This routine deallocates a previously allocated mutex.
16422 */
16423 static void debugMutexFree(sqlite3_mutex *pX){
16424   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16425   assert( p->cnt==0 );
16426   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16427   sqlite3_free(p);
16428 }
16429
16430 /*
16431 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16432 ** to enter a mutex.  If another thread is already within the mutex,
16433 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16434 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16435 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16436 ** be entered multiple times by the same thread.  In such cases the,
16437 ** mutex must be exited an equal number of times before another thread
16438 ** can enter.  If the same thread tries to enter any other kind of mutex
16439 ** more than once, the behavior is undefined.
16440 */
16441 static void debugMutexEnter(sqlite3_mutex *pX){
16442   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16443   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16444   p->cnt++;
16445 }
16446 static int debugMutexTry(sqlite3_mutex *pX){
16447   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16448   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16449   p->cnt++;
16450   return SQLITE_OK;
16451 }
16452
16453 /*
16454 ** The sqlite3_mutex_leave() routine exits a mutex that was
16455 ** previously entered by the same thread.  The behavior
16456 ** is undefined if the mutex is not currently entered or
16457 ** is not currently allocated.  SQLite will never do either.
16458 */
16459 static void debugMutexLeave(sqlite3_mutex *pX){
16460   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
16461   assert( debugMutexHeld(pX) );
16462   p->cnt--;
16463   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
16464 }
16465
16466 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16467   static const sqlite3_mutex_methods sMutex = {
16468     debugMutexInit,
16469     debugMutexEnd,
16470     debugMutexAlloc,
16471     debugMutexFree,
16472     debugMutexEnter,
16473     debugMutexTry,
16474     debugMutexLeave,
16475
16476     debugMutexHeld,
16477     debugMutexNotheld
16478   };
16479
16480   return &sMutex;
16481 }
16482 #endif /* SQLITE_DEBUG */
16483
16484 /*
16485 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
16486 ** is used regardless of the run-time threadsafety setting.
16487 */
16488 #ifdef SQLITE_MUTEX_NOOP
16489 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16490   return sqlite3NoopMutex();
16491 }
16492 #endif /* SQLITE_MUTEX_NOOP */
16493 #endif /* SQLITE_MUTEX_OMIT */
16494
16495 /************** End of mutex_noop.c ******************************************/
16496 /************** Begin file mutex_os2.c ***************************************/
16497 /*
16498 ** 2007 August 28
16499 **
16500 ** The author disclaims copyright to this source code.  In place of
16501 ** a legal notice, here is a blessing:
16502 **
16503 **    May you do good and not evil.
16504 **    May you find forgiveness for yourself and forgive others.
16505 **    May you share freely, never taking more than you give.
16506 **
16507 *************************************************************************
16508 ** This file contains the C functions that implement mutexes for OS/2
16509 */
16510
16511 /*
16512 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
16513 ** See the mutex.h file for details.
16514 */
16515 #ifdef SQLITE_MUTEX_OS2
16516
16517 /********************** OS/2 Mutex Implementation **********************
16518 **
16519 ** This implementation of mutexes is built using the OS/2 API.
16520 */
16521
16522 /*
16523 ** The mutex object
16524 ** Each recursive mutex is an instance of the following structure.
16525 */
16526 struct sqlite3_mutex {
16527   HMTX mutex;       /* Mutex controlling the lock */
16528   int  id;          /* Mutex type */
16529   int  nRef;        /* Number of references */
16530   TID  owner;       /* Thread holding this mutex */
16531 };
16532
16533 #define OS2_MUTEX_INITIALIZER   0,0,0,0
16534
16535 /*
16536 ** Initialize and deinitialize the mutex subsystem.
16537 */
16538 static int os2MutexInit(void){ return SQLITE_OK; }
16539 static int os2MutexEnd(void){ return SQLITE_OK; }
16540
16541 /*
16542 ** The sqlite3_mutex_alloc() routine allocates a new
16543 ** mutex and returns a pointer to it.  If it returns NULL
16544 ** that means that a mutex could not be allocated. 
16545 ** SQLite will unwind its stack and return an error.  The argument
16546 ** to sqlite3_mutex_alloc() is one of these integer constants:
16547 **
16548 ** <ul>
16549 ** <li>  SQLITE_MUTEX_FAST               0
16550 ** <li>  SQLITE_MUTEX_RECURSIVE          1
16551 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
16552 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
16553 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
16554 ** </ul>
16555 **
16556 ** The first two constants cause sqlite3_mutex_alloc() to create
16557 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16558 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16559 ** The mutex implementation does not need to make a distinction
16560 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16561 ** not want to.  But SQLite will only request a recursive mutex in
16562 ** cases where it really needs one.  If a faster non-recursive mutex
16563 ** implementation is available on the host platform, the mutex subsystem
16564 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16565 **
16566 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16567 ** a pointer to a static preexisting mutex.  Three static mutexes are
16568 ** used by the current version of SQLite.  Future versions of SQLite
16569 ** may add additional static mutexes.  Static mutexes are for internal
16570 ** use by SQLite only.  Applications that use SQLite mutexes should
16571 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16572 ** SQLITE_MUTEX_RECURSIVE.
16573 **
16574 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16575 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16576 ** returns a different mutex on every call.  But for the static
16577 ** mutex types, the same mutex is returned on every call that has
16578 ** the same type number.
16579 */
16580 static sqlite3_mutex *os2MutexAlloc(int iType){
16581   sqlite3_mutex *p = NULL;
16582   switch( iType ){
16583     case SQLITE_MUTEX_FAST:
16584     case SQLITE_MUTEX_RECURSIVE: {
16585       p = sqlite3MallocZero( sizeof(*p) );
16586       if( p ){
16587         p->id = iType;
16588         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
16589           sqlite3_free( p );
16590           p = NULL;
16591         }
16592       }
16593       break;
16594     }
16595     default: {
16596       static volatile int isInit = 0;
16597       static sqlite3_mutex staticMutexes[] = {
16598         { OS2_MUTEX_INITIALIZER, },
16599         { OS2_MUTEX_INITIALIZER, },
16600         { OS2_MUTEX_INITIALIZER, },
16601         { OS2_MUTEX_INITIALIZER, },
16602         { OS2_MUTEX_INITIALIZER, },
16603         { OS2_MUTEX_INITIALIZER, },
16604       };
16605       if ( !isInit ){
16606         APIRET rc;
16607         PTIB ptib;
16608         PPIB ppib;
16609         HMTX mutex;
16610         char name[32];
16611         DosGetInfoBlocks( &ptib, &ppib );
16612         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
16613                           ppib->pib_ulpid );
16614         while( !isInit ){
16615           mutex = 0;
16616           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
16617           if( rc == NO_ERROR ){
16618             unsigned int i;
16619             if( !isInit ){
16620               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
16621                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
16622               }
16623               isInit = 1;
16624             }
16625             DosCloseMutexSem( mutex );
16626           }else if( rc == ERROR_DUPLICATE_NAME ){
16627             DosSleep( 1 );
16628           }else{
16629             return p;
16630           }
16631         }
16632       }
16633       assert( iType-2 >= 0 );
16634       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
16635       p = &staticMutexes[iType-2];
16636       p->id = iType;
16637       break;
16638     }
16639   }
16640   return p;
16641 }
16642
16643
16644 /*
16645 ** This routine deallocates a previously allocated mutex.
16646 ** SQLite is careful to deallocate every mutex that it allocates.
16647 */
16648 static void os2MutexFree(sqlite3_mutex *p){
16649   if( p==0 ) return;
16650   assert( p->nRef==0 );
16651   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16652   DosCloseMutexSem( p->mutex );
16653   sqlite3_free( p );
16654 }
16655
16656 #ifdef SQLITE_DEBUG
16657 /*
16658 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16659 ** intended for use inside assert() statements.
16660 */
16661 static int os2MutexHeld(sqlite3_mutex *p){
16662   TID tid;
16663   PID pid;
16664   ULONG ulCount;
16665   PTIB ptib;
16666   if( p!=0 ) {
16667     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16668   } else {
16669     DosGetInfoBlocks(&ptib, NULL);
16670     tid = ptib->tib_ptib2->tib2_ultid;
16671   }
16672   return p==0 || (p->nRef!=0 && p->owner==tid);
16673 }
16674 static int os2MutexNotheld(sqlite3_mutex *p){
16675   TID tid;
16676   PID pid;
16677   ULONG ulCount;
16678   PTIB ptib;
16679   if( p!= 0 ) {
16680     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
16681   } else {
16682     DosGetInfoBlocks(&ptib, NULL);
16683     tid = ptib->tib_ptib2->tib2_ultid;
16684   }
16685   return p==0 || p->nRef==0 || p->owner!=tid;
16686 }
16687 #endif
16688
16689 /*
16690 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16691 ** to enter a mutex.  If another thread is already within the mutex,
16692 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16693 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16694 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16695 ** be entered multiple times by the same thread.  In such cases the,
16696 ** mutex must be exited an equal number of times before another thread
16697 ** can enter.  If the same thread tries to enter any other kind of mutex
16698 ** more than once, the behavior is undefined.
16699 */
16700 static void os2MutexEnter(sqlite3_mutex *p){
16701   TID tid;
16702   PID holder1;
16703   ULONG holder2;
16704   if( p==0 ) return;
16705   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16706   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
16707   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16708   p->owner = tid;
16709   p->nRef++;
16710 }
16711 static int os2MutexTry(sqlite3_mutex *p){
16712   int rc;
16713   TID tid;
16714   PID holder1;
16715   ULONG holder2;
16716   if( p==0 ) return SQLITE_OK;
16717   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
16718   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
16719     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16720     p->owner = tid;
16721     p->nRef++;
16722     rc = SQLITE_OK;
16723   } else {
16724     rc = SQLITE_BUSY;
16725   }
16726
16727   return rc;
16728 }
16729
16730 /*
16731 ** The sqlite3_mutex_leave() routine exits a mutex that was
16732 ** previously entered by the same thread.  The behavior
16733 ** is undefined if the mutex is not currently entered or
16734 ** is not currently allocated.  SQLite will never do either.
16735 */
16736 static void os2MutexLeave(sqlite3_mutex *p){
16737   TID tid;
16738   PID holder1;
16739   ULONG holder2;
16740   if( p==0 ) return;
16741   assert( p->nRef>0 );
16742   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
16743   assert( p->owner==tid );
16744   p->nRef--;
16745   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16746   DosReleaseMutexSem(p->mutex);
16747 }
16748
16749 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
16750   static const sqlite3_mutex_methods sMutex = {
16751     os2MutexInit,
16752     os2MutexEnd,
16753     os2MutexAlloc,
16754     os2MutexFree,
16755     os2MutexEnter,
16756     os2MutexTry,
16757     os2MutexLeave,
16758 #ifdef SQLITE_DEBUG
16759     os2MutexHeld,
16760     os2MutexNotheld
16761 #endif
16762   };
16763
16764   return &sMutex;
16765 }
16766 #endif /* SQLITE_MUTEX_OS2 */
16767
16768 /************** End of mutex_os2.c *******************************************/
16769 /************** Begin file mutex_unix.c **************************************/
16770 /*
16771 ** 2007 August 28
16772 **
16773 ** The author disclaims copyright to this source code.  In place of
16774 ** a legal notice, here is a blessing:
16775 **
16776 **    May you do good and not evil.
16777 **    May you find forgiveness for yourself and forgive others.
16778 **    May you share freely, never taking more than you give.
16779 **
16780 *************************************************************************
16781 ** This file contains the C functions that implement mutexes for pthreads
16782 */
16783
16784 /*
16785 ** The code in this file is only used if we are compiling threadsafe
16786 ** under unix with pthreads.
16787 **
16788 ** Note that this implementation requires a version of pthreads that
16789 ** supports recursive mutexes.
16790 */
16791 #ifdef SQLITE_MUTEX_PTHREADS
16792
16793 #include <pthread.h>
16794
16795 /*
16796 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
16797 ** are necessary under two condidtions:  (1) Debug builds and (2) using
16798 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
16799 */
16800 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
16801 # define SQLITE_MUTEX_NREF 1
16802 #else
16803 # define SQLITE_MUTEX_NREF 0
16804 #endif
16805
16806 /*
16807 ** Each recursive mutex is an instance of the following structure.
16808 */
16809 struct sqlite3_mutex {
16810   pthread_mutex_t mutex;     /* Mutex controlling the lock */
16811 #if SQLITE_MUTEX_NREF
16812   int id;                    /* Mutex type */
16813   volatile int nRef;         /* Number of entrances */
16814   volatile pthread_t owner;  /* Thread that is within this mutex */
16815   int trace;                 /* True to trace changes */
16816 #endif
16817 };
16818 #if SQLITE_MUTEX_NREF
16819 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
16820 #else
16821 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
16822 #endif
16823
16824 /*
16825 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16826 ** intended for use only inside assert() statements.  On some platforms,
16827 ** there might be race conditions that can cause these routines to
16828 ** deliver incorrect results.  In particular, if pthread_equal() is
16829 ** not an atomic operation, then these routines might delivery
16830 ** incorrect results.  On most platforms, pthread_equal() is a 
16831 ** comparison of two integers and is therefore atomic.  But we are
16832 ** told that HPUX is not such a platform.  If so, then these routines
16833 ** will not always work correctly on HPUX.
16834 **
16835 ** On those platforms where pthread_equal() is not atomic, SQLite
16836 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
16837 ** make sure no assert() statements are evaluated and hence these
16838 ** routines are never called.
16839 */
16840 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
16841 static int pthreadMutexHeld(sqlite3_mutex *p){
16842   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
16843 }
16844 static int pthreadMutexNotheld(sqlite3_mutex *p){
16845   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
16846 }
16847 #endif
16848
16849 /*
16850 ** Initialize and deinitialize the mutex subsystem.
16851 */
16852 static int pthreadMutexInit(void){ return SQLITE_OK; }
16853 static int pthreadMutexEnd(void){ return SQLITE_OK; }
16854
16855 /*
16856 ** The sqlite3_mutex_alloc() routine allocates a new
16857 ** mutex and returns a pointer to it.  If it returns NULL
16858 ** that means that a mutex could not be allocated.  SQLite
16859 ** will unwind its stack and return an error.  The argument
16860 ** to sqlite3_mutex_alloc() is one of these integer constants:
16861 **
16862 ** <ul>
16863 ** <li>  SQLITE_MUTEX_FAST
16864 ** <li>  SQLITE_MUTEX_RECURSIVE
16865 ** <li>  SQLITE_MUTEX_STATIC_MASTER
16866 ** <li>  SQLITE_MUTEX_STATIC_MEM
16867 ** <li>  SQLITE_MUTEX_STATIC_MEM2
16868 ** <li>  SQLITE_MUTEX_STATIC_PRNG
16869 ** <li>  SQLITE_MUTEX_STATIC_LRU
16870 ** <li>  SQLITE_MUTEX_STATIC_LRU2
16871 ** </ul>
16872 **
16873 ** The first two constants cause sqlite3_mutex_alloc() to create
16874 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
16875 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
16876 ** The mutex implementation does not need to make a distinction
16877 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
16878 ** not want to.  But SQLite will only request a recursive mutex in
16879 ** cases where it really needs one.  If a faster non-recursive mutex
16880 ** implementation is available on the host platform, the mutex subsystem
16881 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
16882 **
16883 ** The other allowed parameters to sqlite3_mutex_alloc() each return
16884 ** a pointer to a static preexisting mutex.  Six static mutexes are
16885 ** used by the current version of SQLite.  Future versions of SQLite
16886 ** may add additional static mutexes.  Static mutexes are for internal
16887 ** use by SQLite only.  Applications that use SQLite mutexes should
16888 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
16889 ** SQLITE_MUTEX_RECURSIVE.
16890 **
16891 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
16892 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
16893 ** returns a different mutex on every call.  But for the static 
16894 ** mutex types, the same mutex is returned on every call that has
16895 ** the same type number.
16896 */
16897 static sqlite3_mutex *pthreadMutexAlloc(int iType){
16898   static sqlite3_mutex staticMutexes[] = {
16899     SQLITE3_MUTEX_INITIALIZER,
16900     SQLITE3_MUTEX_INITIALIZER,
16901     SQLITE3_MUTEX_INITIALIZER,
16902     SQLITE3_MUTEX_INITIALIZER,
16903     SQLITE3_MUTEX_INITIALIZER,
16904     SQLITE3_MUTEX_INITIALIZER
16905   };
16906   sqlite3_mutex *p;
16907   switch( iType ){
16908     case SQLITE_MUTEX_RECURSIVE: {
16909       p = sqlite3MallocZero( sizeof(*p) );
16910       if( p ){
16911 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16912         /* If recursive mutexes are not available, we will have to
16913         ** build our own.  See below. */
16914         pthread_mutex_init(&p->mutex, 0);
16915 #else
16916         /* Use a recursive mutex if it is available */
16917         pthread_mutexattr_t recursiveAttr;
16918         pthread_mutexattr_init(&recursiveAttr);
16919         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
16920         pthread_mutex_init(&p->mutex, &recursiveAttr);
16921         pthread_mutexattr_destroy(&recursiveAttr);
16922 #endif
16923 #if SQLITE_MUTEX_NREF
16924         p->id = iType;
16925 #endif
16926       }
16927       break;
16928     }
16929     case SQLITE_MUTEX_FAST: {
16930       p = sqlite3MallocZero( sizeof(*p) );
16931       if( p ){
16932 #if SQLITE_MUTEX_NREF
16933         p->id = iType;
16934 #endif
16935         pthread_mutex_init(&p->mutex, 0);
16936       }
16937       break;
16938     }
16939     default: {
16940       assert( iType-2 >= 0 );
16941       assert( iType-2 < ArraySize(staticMutexes) );
16942       p = &staticMutexes[iType-2];
16943 #if SQLITE_MUTEX_NREF
16944       p->id = iType;
16945 #endif
16946       break;
16947     }
16948   }
16949   return p;
16950 }
16951
16952
16953 /*
16954 ** This routine deallocates a previously
16955 ** allocated mutex.  SQLite is careful to deallocate every
16956 ** mutex that it allocates.
16957 */
16958 static void pthreadMutexFree(sqlite3_mutex *p){
16959   assert( p->nRef==0 );
16960   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
16961   pthread_mutex_destroy(&p->mutex);
16962   sqlite3_free(p);
16963 }
16964
16965 /*
16966 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
16967 ** to enter a mutex.  If another thread is already within the mutex,
16968 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
16969 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
16970 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
16971 ** be entered multiple times by the same thread.  In such cases the,
16972 ** mutex must be exited an equal number of times before another thread
16973 ** can enter.  If the same thread tries to enter any other kind of mutex
16974 ** more than once, the behavior is undefined.
16975 */
16976 static void pthreadMutexEnter(sqlite3_mutex *p){
16977   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
16978
16979 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
16980   /* If recursive mutexes are not available, then we have to grow
16981   ** our own.  This implementation assumes that pthread_equal()
16982   ** is atomic - that it cannot be deceived into thinking self
16983   ** and p->owner are equal if p->owner changes between two values
16984   ** that are not equal to self while the comparison is taking place.
16985   ** This implementation also assumes a coherent cache - that 
16986   ** separate processes cannot read different values from the same
16987   ** address at the same time.  If either of these two conditions
16988   ** are not met, then the mutexes will fail and problems will result.
16989   */
16990   {
16991     pthread_t self = pthread_self();
16992     if( p->nRef>0 && pthread_equal(p->owner, self) ){
16993       p->nRef++;
16994     }else{
16995       pthread_mutex_lock(&p->mutex);
16996       assert( p->nRef==0 );
16997       p->owner = self;
16998       p->nRef = 1;
16999     }
17000   }
17001 #else
17002   /* Use the built-in recursive mutexes if they are available.
17003   */
17004   pthread_mutex_lock(&p->mutex);
17005 #if SQLITE_MUTEX_NREF
17006   assert( p->nRef>0 || p->owner==0 );
17007   p->owner = pthread_self();
17008   p->nRef++;
17009 #endif
17010 #endif
17011
17012 #ifdef SQLITE_DEBUG
17013   if( p->trace ){
17014     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17015   }
17016 #endif
17017 }
17018 static int pthreadMutexTry(sqlite3_mutex *p){
17019   int rc;
17020   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17021
17022 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17023   /* If recursive mutexes are not available, then we have to grow
17024   ** our own.  This implementation assumes that pthread_equal()
17025   ** is atomic - that it cannot be deceived into thinking self
17026   ** and p->owner are equal if p->owner changes between two values
17027   ** that are not equal to self while the comparison is taking place.
17028   ** This implementation also assumes a coherent cache - that 
17029   ** separate processes cannot read different values from the same
17030   ** address at the same time.  If either of these two conditions
17031   ** are not met, then the mutexes will fail and problems will result.
17032   */
17033   {
17034     pthread_t self = pthread_self();
17035     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17036       p->nRef++;
17037       rc = SQLITE_OK;
17038     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
17039       assert( p->nRef==0 );
17040       p->owner = self;
17041       p->nRef = 1;
17042       rc = SQLITE_OK;
17043     }else{
17044       rc = SQLITE_BUSY;
17045     }
17046   }
17047 #else
17048   /* Use the built-in recursive mutexes if they are available.
17049   */
17050   if( pthread_mutex_trylock(&p->mutex)==0 ){
17051 #if SQLITE_MUTEX_NREF
17052     p->owner = pthread_self();
17053     p->nRef++;
17054 #endif
17055     rc = SQLITE_OK;
17056   }else{
17057     rc = SQLITE_BUSY;
17058   }
17059 #endif
17060
17061 #ifdef SQLITE_DEBUG
17062   if( rc==SQLITE_OK && p->trace ){
17063     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17064   }
17065 #endif
17066   return rc;
17067 }
17068
17069 /*
17070 ** The sqlite3_mutex_leave() routine exits a mutex that was
17071 ** previously entered by the same thread.  The behavior
17072 ** is undefined if the mutex is not currently entered or
17073 ** is not currently allocated.  SQLite will never do either.
17074 */
17075 static void pthreadMutexLeave(sqlite3_mutex *p){
17076   assert( pthreadMutexHeld(p) );
17077 #if SQLITE_MUTEX_NREF
17078   p->nRef--;
17079   if( p->nRef==0 ) p->owner = 0;
17080 #endif
17081   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17082
17083 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17084   if( p->nRef==0 ){
17085     pthread_mutex_unlock(&p->mutex);
17086   }
17087 #else
17088   pthread_mutex_unlock(&p->mutex);
17089 #endif
17090
17091 #ifdef SQLITE_DEBUG
17092   if( p->trace ){
17093     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17094   }
17095 #endif
17096 }
17097
17098 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17099   static const sqlite3_mutex_methods sMutex = {
17100     pthreadMutexInit,
17101     pthreadMutexEnd,
17102     pthreadMutexAlloc,
17103     pthreadMutexFree,
17104     pthreadMutexEnter,
17105     pthreadMutexTry,
17106     pthreadMutexLeave,
17107 #ifdef SQLITE_DEBUG
17108     pthreadMutexHeld,
17109     pthreadMutexNotheld
17110 #else
17111     0,
17112     0
17113 #endif
17114   };
17115
17116   return &sMutex;
17117 }
17118
17119 #endif /* SQLITE_MUTEX_PTHREAD */
17120
17121 /************** End of mutex_unix.c ******************************************/
17122 /************** Begin file mutex_w32.c ***************************************/
17123 /*
17124 ** 2007 August 14
17125 **
17126 ** The author disclaims copyright to this source code.  In place of
17127 ** a legal notice, here is a blessing:
17128 **
17129 **    May you do good and not evil.
17130 **    May you find forgiveness for yourself and forgive others.
17131 **    May you share freely, never taking more than you give.
17132 **
17133 *************************************************************************
17134 ** This file contains the C functions that implement mutexes for win32
17135 */
17136
17137 /*
17138 ** The code in this file is only used if we are compiling multithreaded
17139 ** on a win32 system.
17140 */
17141 #ifdef SQLITE_MUTEX_W32
17142
17143 /*
17144 ** Each recursive mutex is an instance of the following structure.
17145 */
17146 struct sqlite3_mutex {
17147   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
17148   int id;                    /* Mutex type */
17149 #ifdef SQLITE_DEBUG
17150   volatile int nRef;         /* Number of enterances */
17151   volatile DWORD owner;      /* Thread holding this mutex */
17152   int trace;                 /* True to trace changes */
17153 #endif
17154 };
17155 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17156 #ifdef SQLITE_DEBUG
17157 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17158 #else
17159 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17160 #endif
17161
17162 /*
17163 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17164 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
17165 **
17166 ** Here is an interesting observation:  Win95, Win98, and WinME lack
17167 ** the LockFileEx() API.  But we can still statically link against that
17168 ** API as long as we don't call it win running Win95/98/ME.  A call to
17169 ** this routine is used to determine if the host is Win95/98/ME or
17170 ** WinNT/2K/XP so that we will know whether or not we can safely call
17171 ** the LockFileEx() API.
17172 **
17173 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17174 ** which is only available if your application was compiled with 
17175 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
17176 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
17177 ** this out as well.
17178 */
17179 #if 0
17180 #if SQLITE_OS_WINCE
17181 # define mutexIsNT()  (1)
17182 #else
17183   static int mutexIsNT(void){
17184     static int osType = 0;
17185     if( osType==0 ){
17186       OSVERSIONINFO sInfo;
17187       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17188       GetVersionEx(&sInfo);
17189       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17190     }
17191     return osType==2;
17192   }
17193 #endif /* SQLITE_OS_WINCE */
17194 #endif
17195
17196 #ifdef SQLITE_DEBUG
17197 /*
17198 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17199 ** intended for use only inside assert() statements.
17200 */
17201 static int winMutexHeld(sqlite3_mutex *p){
17202   return p->nRef!=0 && p->owner==GetCurrentThreadId();
17203 }
17204 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17205   return p->nRef==0 || p->owner!=tid;
17206 }
17207 static int winMutexNotheld(sqlite3_mutex *p){
17208   DWORD tid = GetCurrentThreadId(); 
17209   return winMutexNotheld2(p, tid);
17210 }
17211 #endif
17212
17213
17214 /*
17215 ** Initialize and deinitialize the mutex subsystem.
17216 */
17217 static sqlite3_mutex winMutex_staticMutexes[6] = {
17218   SQLITE3_MUTEX_INITIALIZER,
17219   SQLITE3_MUTEX_INITIALIZER,
17220   SQLITE3_MUTEX_INITIALIZER,
17221   SQLITE3_MUTEX_INITIALIZER,
17222   SQLITE3_MUTEX_INITIALIZER,
17223   SQLITE3_MUTEX_INITIALIZER
17224 };
17225 static int winMutex_isInit = 0;
17226 /* As winMutexInit() and winMutexEnd() are called as part
17227 ** of the sqlite3_initialize and sqlite3_shutdown()
17228 ** processing, the "interlocked" magic is probably not
17229 ** strictly necessary.
17230 */
17231 static long winMutex_lock = 0;
17232
17233 static int winMutexInit(void){ 
17234   /* The first to increment to 1 does actual initialization */
17235   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17236     int i;
17237     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17238       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17239     }
17240     winMutex_isInit = 1;
17241   }else{
17242     /* Someone else is in the process of initing the static mutexes */
17243     while( !winMutex_isInit ){
17244       Sleep(1);
17245     }
17246   }
17247   return SQLITE_OK; 
17248 }
17249
17250 static int winMutexEnd(void){ 
17251   /* The first to decrement to 0 does actual shutdown 
17252   ** (which should be the last to shutdown.) */
17253   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17254     if( winMutex_isInit==1 ){
17255       int i;
17256       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17257         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17258       }
17259       winMutex_isInit = 0;
17260     }
17261   }
17262   return SQLITE_OK; 
17263 }
17264
17265 /*
17266 ** The sqlite3_mutex_alloc() routine allocates a new
17267 ** mutex and returns a pointer to it.  If it returns NULL
17268 ** that means that a mutex could not be allocated.  SQLite
17269 ** will unwind its stack and return an error.  The argument
17270 ** to sqlite3_mutex_alloc() is one of these integer constants:
17271 **
17272 ** <ul>
17273 ** <li>  SQLITE_MUTEX_FAST
17274 ** <li>  SQLITE_MUTEX_RECURSIVE
17275 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17276 ** <li>  SQLITE_MUTEX_STATIC_MEM
17277 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17278 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17279 ** <li>  SQLITE_MUTEX_STATIC_LRU
17280 ** <li>  SQLITE_MUTEX_STATIC_LRU2
17281 ** </ul>
17282 **
17283 ** The first two constants cause sqlite3_mutex_alloc() to create
17284 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17285 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17286 ** The mutex implementation does not need to make a distinction
17287 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17288 ** not want to.  But SQLite will only request a recursive mutex in
17289 ** cases where it really needs one.  If a faster non-recursive mutex
17290 ** implementation is available on the host platform, the mutex subsystem
17291 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17292 **
17293 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17294 ** a pointer to a static preexisting mutex.  Six static mutexes are
17295 ** used by the current version of SQLite.  Future versions of SQLite
17296 ** may add additional static mutexes.  Static mutexes are for internal
17297 ** use by SQLite only.  Applications that use SQLite mutexes should
17298 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17299 ** SQLITE_MUTEX_RECURSIVE.
17300 **
17301 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17302 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17303 ** returns a different mutex on every call.  But for the static 
17304 ** mutex types, the same mutex is returned on every call that has
17305 ** the same type number.
17306 */
17307 static sqlite3_mutex *winMutexAlloc(int iType){
17308   sqlite3_mutex *p;
17309
17310   switch( iType ){
17311     case SQLITE_MUTEX_FAST:
17312     case SQLITE_MUTEX_RECURSIVE: {
17313       p = sqlite3MallocZero( sizeof(*p) );
17314       if( p ){  
17315 #ifdef SQLITE_DEBUG
17316         p->id = iType;
17317 #endif
17318         InitializeCriticalSection(&p->mutex);
17319       }
17320       break;
17321     }
17322     default: {
17323       assert( winMutex_isInit==1 );
17324       assert( iType-2 >= 0 );
17325       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
17326       p = &winMutex_staticMutexes[iType-2];
17327 #ifdef SQLITE_DEBUG
17328       p->id = iType;
17329 #endif
17330       break;
17331     }
17332   }
17333   return p;
17334 }
17335
17336
17337 /*
17338 ** This routine deallocates a previously
17339 ** allocated mutex.  SQLite is careful to deallocate every
17340 ** mutex that it allocates.
17341 */
17342 static void winMutexFree(sqlite3_mutex *p){
17343   assert( p );
17344   assert( p->nRef==0 && p->owner==0 );
17345   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17346   DeleteCriticalSection(&p->mutex);
17347   sqlite3_free(p);
17348 }
17349
17350 /*
17351 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17352 ** to enter a mutex.  If another thread is already within the mutex,
17353 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17354 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17355 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17356 ** be entered multiple times by the same thread.  In such cases the,
17357 ** mutex must be exited an equal number of times before another thread
17358 ** can enter.  If the same thread tries to enter any other kind of mutex
17359 ** more than once, the behavior is undefined.
17360 */
17361 static void winMutexEnter(sqlite3_mutex *p){
17362 #ifdef SQLITE_DEBUG
17363   DWORD tid = GetCurrentThreadId(); 
17364   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17365 #endif
17366   EnterCriticalSection(&p->mutex);
17367 #ifdef SQLITE_DEBUG
17368   assert( p->nRef>0 || p->owner==0 );
17369   p->owner = tid; 
17370   p->nRef++;
17371   if( p->trace ){
17372     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17373   }
17374 #endif
17375 }
17376 static int winMutexTry(sqlite3_mutex *p){
17377 #ifndef NDEBUG
17378   DWORD tid = GetCurrentThreadId(); 
17379 #endif
17380   int rc = SQLITE_BUSY;
17381   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
17382   /*
17383   ** The sqlite3_mutex_try() routine is very rarely used, and when it
17384   ** is used it is merely an optimization.  So it is OK for it to always
17385   ** fail.  
17386   **
17387   ** The TryEnterCriticalSection() interface is only available on WinNT.
17388   ** And some windows compilers complain if you try to use it without
17389   ** first doing some #defines that prevent SQLite from building on Win98.
17390   ** For that reason, we will omit this optimization for now.  See
17391   ** ticket #2685.
17392   */
17393 #if 0
17394   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
17395     p->owner = tid;
17396     p->nRef++;
17397     rc = SQLITE_OK;
17398   }
17399 #else
17400   UNUSED_PARAMETER(p);
17401 #endif
17402 #ifdef SQLITE_DEBUG
17403   if( rc==SQLITE_OK && p->trace ){
17404     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17405   }
17406 #endif
17407   return rc;
17408 }
17409
17410 /*
17411 ** The sqlite3_mutex_leave() routine exits a mutex that was
17412 ** previously entered by the same thread.  The behavior
17413 ** is undefined if the mutex is not currently entered or
17414 ** is not currently allocated.  SQLite will never do either.
17415 */
17416 static void winMutexLeave(sqlite3_mutex *p){
17417 #ifndef NDEBUG
17418   DWORD tid = GetCurrentThreadId();
17419   assert( p->nRef>0 );
17420   assert( p->owner==tid );
17421   p->nRef--;
17422   if( p->nRef==0 ) p->owner = 0;
17423   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17424 #endif
17425   LeaveCriticalSection(&p->mutex);
17426 #ifdef SQLITE_DEBUG
17427   if( p->trace ){
17428     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17429   }
17430 #endif
17431 }
17432
17433 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17434   static const sqlite3_mutex_methods sMutex = {
17435     winMutexInit,
17436     winMutexEnd,
17437     winMutexAlloc,
17438     winMutexFree,
17439     winMutexEnter,
17440     winMutexTry,
17441     winMutexLeave,
17442 #ifdef SQLITE_DEBUG
17443     winMutexHeld,
17444     winMutexNotheld
17445 #else
17446     0,
17447     0
17448 #endif
17449   };
17450
17451   return &sMutex;
17452 }
17453 #endif /* SQLITE_MUTEX_W32 */
17454
17455 /************** End of mutex_w32.c *******************************************/
17456 /************** Begin file malloc.c ******************************************/
17457 /*
17458 ** 2001 September 15
17459 **
17460 ** The author disclaims copyright to this source code.  In place of
17461 ** a legal notice, here is a blessing:
17462 **
17463 **    May you do good and not evil.
17464 **    May you find forgiveness for yourself and forgive others.
17465 **    May you share freely, never taking more than you give.
17466 **
17467 *************************************************************************
17468 **
17469 ** Memory allocation functions used throughout sqlite.
17470 */
17471
17472 /*
17473 ** Attempt to release up to n bytes of non-essential memory currently
17474 ** held by SQLite. An example of non-essential memory is memory used to
17475 ** cache database pages that are not currently in use.
17476 */
17477 SQLITE_API int sqlite3_release_memory(int n){
17478 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17479   return sqlite3PcacheReleaseMemory(n);
17480 #else
17481   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
17482   ** is a no-op returning zero if SQLite is not compiled with
17483   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
17484   UNUSED_PARAMETER(n);
17485   return 0;
17486 #endif
17487 }
17488
17489 /*
17490 ** An instance of the following object records the location of
17491 ** each unused scratch buffer.
17492 */
17493 typedef struct ScratchFreeslot {
17494   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
17495 } ScratchFreeslot;
17496
17497 /*
17498 ** State information local to the memory allocation subsystem.
17499 */
17500 static SQLITE_WSD struct Mem0Global {
17501   sqlite3_mutex *mutex;         /* Mutex to serialize access */
17502
17503   /*
17504   ** The alarm callback and its arguments.  The mem0.mutex lock will
17505   ** be held while the callback is running.  Recursive calls into
17506   ** the memory subsystem are allowed, but no new callbacks will be
17507   ** issued.
17508   */
17509   sqlite3_int64 alarmThreshold;
17510   void (*alarmCallback)(void*, sqlite3_int64,int);
17511   void *alarmArg;
17512
17513   /*
17514   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
17515   ** (so that a range test can be used to determine if an allocation
17516   ** being freed came from pScratch) and a pointer to the list of
17517   ** unused scratch allocations.
17518   */
17519   void *pScratchEnd;
17520   ScratchFreeslot *pScratchFree;
17521   u32 nScratchFree;
17522
17523   /*
17524   ** True if heap is nearly "full" where "full" is defined by the
17525   ** sqlite3_soft_heap_limit() setting.
17526   */
17527   int nearlyFull;
17528 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
17529
17530 #define mem0 GLOBAL(struct Mem0Global, mem0)
17531
17532 /*
17533 ** This routine runs when the memory allocator sees that the
17534 ** total memory allocation is about to exceed the soft heap
17535 ** limit.
17536 */
17537 static void softHeapLimitEnforcer(
17538   void *NotUsed, 
17539   sqlite3_int64 NotUsed2,
17540   int allocSize
17541 ){
17542   UNUSED_PARAMETER2(NotUsed, NotUsed2);
17543   sqlite3_release_memory(allocSize);
17544 }
17545
17546 /*
17547 ** Change the alarm callback
17548 */
17549 static int sqlite3MemoryAlarm(
17550   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17551   void *pArg,
17552   sqlite3_int64 iThreshold
17553 ){
17554   int nUsed;
17555   sqlite3_mutex_enter(mem0.mutex);
17556   mem0.alarmCallback = xCallback;
17557   mem0.alarmArg = pArg;
17558   mem0.alarmThreshold = iThreshold;
17559   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17560   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
17561   sqlite3_mutex_leave(mem0.mutex);
17562   return SQLITE_OK;
17563 }
17564
17565 #ifndef SQLITE_OMIT_DEPRECATED
17566 /*
17567 ** Deprecated external interface.  Internal/core SQLite code
17568 ** should call sqlite3MemoryAlarm.
17569 */
17570 SQLITE_API int sqlite3_memory_alarm(
17571   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
17572   void *pArg,
17573   sqlite3_int64 iThreshold
17574 ){
17575   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
17576 }
17577 #endif
17578
17579 /*
17580 ** Set the soft heap-size limit for the library. Passing a zero or 
17581 ** negative value indicates no limit.
17582 */
17583 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
17584   sqlite3_int64 priorLimit;
17585   sqlite3_int64 excess;
17586 #ifndef SQLITE_OMIT_AUTOINIT
17587   sqlite3_initialize();
17588 #endif
17589   sqlite3_mutex_enter(mem0.mutex);
17590   priorLimit = mem0.alarmThreshold;
17591   sqlite3_mutex_leave(mem0.mutex);
17592   if( n<0 ) return priorLimit;
17593   if( n>0 ){
17594     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
17595   }else{
17596     sqlite3MemoryAlarm(0, 0, 0);
17597   }
17598   excess = sqlite3_memory_used() - n;
17599   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
17600   return priorLimit;
17601 }
17602 SQLITE_API void sqlite3_soft_heap_limit(int n){
17603   if( n<0 ) n = 0;
17604   sqlite3_soft_heap_limit64(n);
17605 }
17606
17607 /*
17608 ** Initialize the memory allocation subsystem.
17609 */
17610 SQLITE_PRIVATE int sqlite3MallocInit(void){
17611   if( sqlite3GlobalConfig.m.xMalloc==0 ){
17612     sqlite3MemSetDefault();
17613   }
17614   memset(&mem0, 0, sizeof(mem0));
17615   if( sqlite3GlobalConfig.bCoreMutex ){
17616     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17617   }
17618   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
17619       && sqlite3GlobalConfig.nScratch>0 ){
17620     int i, n, sz;
17621     ScratchFreeslot *pSlot;
17622     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
17623     sqlite3GlobalConfig.szScratch = sz;
17624     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
17625     n = sqlite3GlobalConfig.nScratch;
17626     mem0.pScratchFree = pSlot;
17627     mem0.nScratchFree = n;
17628     for(i=0; i<n-1; i++){
17629       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
17630       pSlot = pSlot->pNext;
17631     }
17632     pSlot->pNext = 0;
17633     mem0.pScratchEnd = (void*)&pSlot[1];
17634   }else{
17635     mem0.pScratchEnd = 0;
17636     sqlite3GlobalConfig.pScratch = 0;
17637     sqlite3GlobalConfig.szScratch = 0;
17638     sqlite3GlobalConfig.nScratch = 0;
17639   }
17640   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
17641       || sqlite3GlobalConfig.nPage<1 ){
17642     sqlite3GlobalConfig.pPage = 0;
17643     sqlite3GlobalConfig.szPage = 0;
17644     sqlite3GlobalConfig.nPage = 0;
17645   }
17646   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
17647 }
17648
17649 /*
17650 ** Return true if the heap is currently under memory pressure - in other
17651 ** words if the amount of heap used is close to the limit set by
17652 ** sqlite3_soft_heap_limit().
17653 */
17654 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
17655   return mem0.nearlyFull;
17656 }
17657
17658 /*
17659 ** Deinitialize the memory allocation subsystem.
17660 */
17661 SQLITE_PRIVATE void sqlite3MallocEnd(void){
17662   if( sqlite3GlobalConfig.m.xShutdown ){
17663     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
17664   }
17665   memset(&mem0, 0, sizeof(mem0));
17666 }
17667
17668 /*
17669 ** Return the amount of memory currently checked out.
17670 */
17671 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
17672   int n, mx;
17673   sqlite3_int64 res;
17674   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
17675   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
17676   return res;
17677 }
17678
17679 /*
17680 ** Return the maximum amount of memory that has ever been
17681 ** checked out since either the beginning of this process
17682 ** or since the most recent reset.
17683 */
17684 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
17685   int n, mx;
17686   sqlite3_int64 res;
17687   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
17688   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
17689   return res;
17690 }
17691
17692 /*
17693 ** Trigger the alarm 
17694 */
17695 static void sqlite3MallocAlarm(int nByte){
17696   void (*xCallback)(void*,sqlite3_int64,int);
17697   sqlite3_int64 nowUsed;
17698   void *pArg;
17699   if( mem0.alarmCallback==0 ) return;
17700   xCallback = mem0.alarmCallback;
17701   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17702   pArg = mem0.alarmArg;
17703   mem0.alarmCallback = 0;
17704   sqlite3_mutex_leave(mem0.mutex);
17705   xCallback(pArg, nowUsed, nByte);
17706   sqlite3_mutex_enter(mem0.mutex);
17707   mem0.alarmCallback = xCallback;
17708   mem0.alarmArg = pArg;
17709 }
17710
17711 /*
17712 ** Do a memory allocation with statistics and alarms.  Assume the
17713 ** lock is already held.
17714 */
17715 static int mallocWithAlarm(int n, void **pp){
17716   int nFull;
17717   void *p;
17718   assert( sqlite3_mutex_held(mem0.mutex) );
17719   nFull = sqlite3GlobalConfig.m.xRoundup(n);
17720   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
17721   if( mem0.alarmCallback!=0 ){
17722     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
17723     if( nUsed+nFull >= mem0.alarmThreshold ){
17724       mem0.nearlyFull = 1;
17725       sqlite3MallocAlarm(nFull);
17726     }else{
17727       mem0.nearlyFull = 0;
17728     }
17729   }
17730   p = sqlite3GlobalConfig.m.xMalloc(nFull);
17731 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
17732   if( p==0 && mem0.alarmCallback ){
17733     sqlite3MallocAlarm(nFull);
17734     p = sqlite3GlobalConfig.m.xMalloc(nFull);
17735   }
17736 #endif
17737   if( p ){
17738     nFull = sqlite3MallocSize(p);
17739     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
17740     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
17741   }
17742   *pp = p;
17743   return nFull;
17744 }
17745
17746 /*
17747 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
17748 ** assumes the memory subsystem has already been initialized.
17749 */
17750 SQLITE_PRIVATE void *sqlite3Malloc(int n){
17751   void *p;
17752   if( n<=0               /* IMP: R-65312-04917 */ 
17753    || n>=0x7fffff00
17754   ){
17755     /* A memory allocation of a number of bytes which is near the maximum
17756     ** signed integer value might cause an integer overflow inside of the
17757     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
17758     ** 255 bytes of overhead.  SQLite itself will never use anything near
17759     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
17760     p = 0;
17761   }else if( sqlite3GlobalConfig.bMemstat ){
17762     sqlite3_mutex_enter(mem0.mutex);
17763     mallocWithAlarm(n, &p);
17764     sqlite3_mutex_leave(mem0.mutex);
17765   }else{
17766     p = sqlite3GlobalConfig.m.xMalloc(n);
17767   }
17768   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
17769   return p;
17770 }
17771
17772 /*
17773 ** This version of the memory allocation is for use by the application.
17774 ** First make sure the memory subsystem is initialized, then do the
17775 ** allocation.
17776 */
17777 SQLITE_API void *sqlite3_malloc(int n){
17778 #ifndef SQLITE_OMIT_AUTOINIT
17779   if( sqlite3_initialize() ) return 0;
17780 #endif
17781   return sqlite3Malloc(n);
17782 }
17783
17784 /*
17785 ** Each thread may only have a single outstanding allocation from
17786 ** xScratchMalloc().  We verify this constraint in the single-threaded
17787 ** case by setting scratchAllocOut to 1 when an allocation
17788 ** is outstanding clearing it when the allocation is freed.
17789 */
17790 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17791 static int scratchAllocOut = 0;
17792 #endif
17793
17794
17795 /*
17796 ** Allocate memory that is to be used and released right away.
17797 ** This routine is similar to alloca() in that it is not intended
17798 ** for situations where the memory might be held long-term.  This
17799 ** routine is intended to get memory to old large transient data
17800 ** structures that would not normally fit on the stack of an
17801 ** embedded processor.
17802 */
17803 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
17804   void *p;
17805   assert( n>0 );
17806
17807   sqlite3_mutex_enter(mem0.mutex);
17808   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
17809     p = mem0.pScratchFree;
17810     mem0.pScratchFree = mem0.pScratchFree->pNext;
17811     mem0.nScratchFree--;
17812     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
17813     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17814     sqlite3_mutex_leave(mem0.mutex);
17815   }else{
17816     if( sqlite3GlobalConfig.bMemstat ){
17817       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
17818       n = mallocWithAlarm(n, &p);
17819       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
17820       sqlite3_mutex_leave(mem0.mutex);
17821     }else{
17822       sqlite3_mutex_leave(mem0.mutex);
17823       p = sqlite3GlobalConfig.m.xMalloc(n);
17824     }
17825     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
17826   }
17827   assert( sqlite3_mutex_notheld(mem0.mutex) );
17828
17829
17830 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17831   /* Verify that no more than two scratch allocations per thread
17832   ** are outstanding at one time.  (This is only checked in the
17833   ** single-threaded case since checking in the multi-threaded case
17834   ** would be much more complicated.) */
17835   assert( scratchAllocOut<=1 );
17836   if( p ) scratchAllocOut++;
17837 #endif
17838
17839   return p;
17840 }
17841 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
17842   if( p ){
17843
17844 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
17845     /* Verify that no more than two scratch allocation per thread
17846     ** is outstanding at one time.  (This is only checked in the
17847     ** single-threaded case since checking in the multi-threaded case
17848     ** would be much more complicated.) */
17849     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
17850     scratchAllocOut--;
17851 #endif
17852
17853     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
17854       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
17855       ScratchFreeslot *pSlot;
17856       pSlot = (ScratchFreeslot*)p;
17857       sqlite3_mutex_enter(mem0.mutex);
17858       pSlot->pNext = mem0.pScratchFree;
17859       mem0.pScratchFree = pSlot;
17860       mem0.nScratchFree++;
17861       assert( mem0.nScratchFree<=sqlite3GlobalConfig.nScratch );
17862       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
17863       sqlite3_mutex_leave(mem0.mutex);
17864     }else{
17865       /* Release memory back to the heap */
17866       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
17867       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
17868       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17869       if( sqlite3GlobalConfig.bMemstat ){
17870         int iSize = sqlite3MallocSize(p);
17871         sqlite3_mutex_enter(mem0.mutex);
17872         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
17873         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
17874         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
17875         sqlite3GlobalConfig.m.xFree(p);
17876         sqlite3_mutex_leave(mem0.mutex);
17877       }else{
17878         sqlite3GlobalConfig.m.xFree(p);
17879       }
17880     }
17881   }
17882 }
17883
17884 /*
17885 ** TRUE if p is a lookaside memory allocation from db
17886 */
17887 #ifndef SQLITE_OMIT_LOOKASIDE
17888 static int isLookaside(sqlite3 *db, void *p){
17889   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
17890 }
17891 #else
17892 #define isLookaside(A,B) 0
17893 #endif
17894
17895 /*
17896 ** Return the size of a memory allocation previously obtained from
17897 ** sqlite3Malloc() or sqlite3_malloc().
17898 */
17899 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
17900   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17901   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17902   return sqlite3GlobalConfig.m.xSize(p);
17903 }
17904 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
17905   assert( db==0 || sqlite3_mutex_held(db->mutex) );
17906   if( db && isLookaside(db, p) ){
17907     return db->lookaside.sz;
17908   }else{
17909     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17910     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17911     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17912     return sqlite3GlobalConfig.m.xSize(p);
17913   }
17914 }
17915
17916 /*
17917 ** Free memory previously obtained from sqlite3Malloc().
17918 */
17919 SQLITE_API void sqlite3_free(void *p){
17920   if( p==0 ) return;  /* IMP: R-49053-54554 */
17921   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
17922   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17923   if( sqlite3GlobalConfig.bMemstat ){
17924     sqlite3_mutex_enter(mem0.mutex);
17925     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
17926     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
17927     sqlite3GlobalConfig.m.xFree(p);
17928     sqlite3_mutex_leave(mem0.mutex);
17929   }else{
17930     sqlite3GlobalConfig.m.xFree(p);
17931   }
17932 }
17933
17934 /*
17935 ** Free memory that might be associated with a particular database
17936 ** connection.
17937 */
17938 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
17939   assert( db==0 || sqlite3_mutex_held(db->mutex) );
17940   if( db ){
17941     if( db->pnBytesFreed ){
17942       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
17943       return;
17944     }
17945     if( isLookaside(db, p) ){
17946       LookasideSlot *pBuf = (LookasideSlot*)p;
17947       pBuf->pNext = db->lookaside.pFree;
17948       db->lookaside.pFree = pBuf;
17949       db->lookaside.nOut--;
17950       return;
17951     }
17952   }
17953   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
17954   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
17955   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17956   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
17957   sqlite3_free(p);
17958 }
17959
17960 /*
17961 ** Change the size of an existing memory allocation
17962 */
17963 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
17964   int nOld, nNew;
17965   void *pNew;
17966   if( pOld==0 ){
17967     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
17968   }
17969   if( nBytes<=0 ){
17970     sqlite3_free(pOld); /* IMP: R-31593-10574 */
17971     return 0;
17972   }
17973   if( nBytes>=0x7fffff00 ){
17974     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
17975     return 0;
17976   }
17977   nOld = sqlite3MallocSize(pOld);
17978   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
17979   ** argument to xRealloc is always a value returned by a prior call to
17980   ** xRoundup. */
17981   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
17982   if( nOld==nNew ){
17983     pNew = pOld;
17984   }else if( sqlite3GlobalConfig.bMemstat ){
17985     sqlite3_mutex_enter(mem0.mutex);
17986     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
17987     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
17988           mem0.alarmThreshold ){
17989       sqlite3MallocAlarm(nNew-nOld);
17990     }
17991     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
17992     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
17993     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17994     if( pNew==0 && mem0.alarmCallback ){
17995       sqlite3MallocAlarm(nBytes);
17996       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
17997     }
17998     if( pNew ){
17999       nNew = sqlite3MallocSize(pNew);
18000       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
18001     }
18002     sqlite3_mutex_leave(mem0.mutex);
18003   }else{
18004     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18005   }
18006   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
18007   return pNew;
18008 }
18009
18010 /*
18011 ** The public interface to sqlite3Realloc.  Make sure that the memory
18012 ** subsystem is initialized prior to invoking sqliteRealloc.
18013 */
18014 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
18015 #ifndef SQLITE_OMIT_AUTOINIT
18016   if( sqlite3_initialize() ) return 0;
18017 #endif
18018   return sqlite3Realloc(pOld, n);
18019 }
18020
18021
18022 /*
18023 ** Allocate and zero memory.
18024 */ 
18025 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
18026   void *p = sqlite3Malloc(n);
18027   if( p ){
18028     memset(p, 0, n);
18029   }
18030   return p;
18031 }
18032
18033 /*
18034 ** Allocate and zero memory.  If the allocation fails, make
18035 ** the mallocFailed flag in the connection pointer.
18036 */
18037 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
18038   void *p = sqlite3DbMallocRaw(db, n);
18039   if( p ){
18040     memset(p, 0, n);
18041   }
18042   return p;
18043 }
18044
18045 /*
18046 ** Allocate and zero memory.  If the allocation fails, make
18047 ** the mallocFailed flag in the connection pointer.
18048 **
18049 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
18050 ** failure on the same database connection) then always return 0.
18051 ** Hence for a particular database connection, once malloc starts
18052 ** failing, it fails consistently until mallocFailed is reset.
18053 ** This is an important assumption.  There are many places in the
18054 ** code that do things like this:
18055 **
18056 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
18057 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
18058 **         if( b ) a[10] = 9;
18059 **
18060 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
18061 ** that all prior mallocs (ex: "a") worked too.
18062 */
18063 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
18064   void *p;
18065   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18066   assert( db==0 || db->pnBytesFreed==0 );
18067 #ifndef SQLITE_OMIT_LOOKASIDE
18068   if( db ){
18069     LookasideSlot *pBuf;
18070     if( db->mallocFailed ){
18071       return 0;
18072     }
18073     if( db->lookaside.bEnabled && n<=db->lookaside.sz
18074          && (pBuf = db->lookaside.pFree)!=0 ){
18075       db->lookaside.pFree = pBuf->pNext;
18076       db->lookaside.nOut++;
18077       if( db->lookaside.nOut>db->lookaside.mxOut ){
18078         db->lookaside.mxOut = db->lookaside.nOut;
18079       }
18080       return (void*)pBuf;
18081     }
18082   }
18083 #else
18084   if( db && db->mallocFailed ){
18085     return 0;
18086   }
18087 #endif
18088   p = sqlite3Malloc(n);
18089   if( !p && db ){
18090     db->mallocFailed = 1;
18091   }
18092   sqlite3MemdebugSetType(p, MEMTYPE_DB |
18093          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18094   return p;
18095 }
18096
18097 /*
18098 ** Resize the block of memory pointed to by p to n bytes. If the
18099 ** resize fails, set the mallocFailed flag in the connection object.
18100 */
18101 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18102   void *pNew = 0;
18103   assert( db!=0 );
18104   assert( sqlite3_mutex_held(db->mutex) );
18105   if( db->mallocFailed==0 ){
18106     if( p==0 ){
18107       return sqlite3DbMallocRaw(db, n);
18108     }
18109     if( isLookaside(db, p) ){
18110       if( n<=db->lookaside.sz ){
18111         return p;
18112       }
18113       pNew = sqlite3DbMallocRaw(db, n);
18114       if( pNew ){
18115         memcpy(pNew, p, db->lookaside.sz);
18116         sqlite3DbFree(db, p);
18117       }
18118     }else{
18119       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18120       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18121       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18122       pNew = sqlite3_realloc(p, n);
18123       if( !pNew ){
18124         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18125         db->mallocFailed = 1;
18126       }
18127       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
18128             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18129     }
18130   }
18131   return pNew;
18132 }
18133
18134 /*
18135 ** Attempt to reallocate p.  If the reallocation fails, then free p
18136 ** and set the mallocFailed flag in the database connection.
18137 */
18138 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18139   void *pNew;
18140   pNew = sqlite3DbRealloc(db, p, n);
18141   if( !pNew ){
18142     sqlite3DbFree(db, p);
18143   }
18144   return pNew;
18145 }
18146
18147 /*
18148 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
18149 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18150 ** is because when memory debugging is turned on, these two functions are 
18151 ** called via macros that record the current file and line number in the
18152 ** ThreadData structure.
18153 */
18154 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18155   char *zNew;
18156   size_t n;
18157   if( z==0 ){
18158     return 0;
18159   }
18160   n = sqlite3Strlen30(z) + 1;
18161   assert( (n&0x7fffffff)==n );
18162   zNew = sqlite3DbMallocRaw(db, (int)n);
18163   if( zNew ){
18164     memcpy(zNew, z, n);
18165   }
18166   return zNew;
18167 }
18168 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18169   char *zNew;
18170   if( z==0 ){
18171     return 0;
18172   }
18173   assert( (n&0x7fffffff)==n );
18174   zNew = sqlite3DbMallocRaw(db, n+1);
18175   if( zNew ){
18176     memcpy(zNew, z, n);
18177     zNew[n] = 0;
18178   }
18179   return zNew;
18180 }
18181
18182 /*
18183 ** Create a string from the zFromat argument and the va_list that follows.
18184 ** Store the string in memory obtained from sqliteMalloc() and make *pz
18185 ** point to that string.
18186 */
18187 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18188   va_list ap;
18189   char *z;
18190
18191   va_start(ap, zFormat);
18192   z = sqlite3VMPrintf(db, zFormat, ap);
18193   va_end(ap);
18194   sqlite3DbFree(db, *pz);
18195   *pz = z;
18196 }
18197
18198
18199 /*
18200 ** This function must be called before exiting any API function (i.e. 
18201 ** returning control to the user) that has called sqlite3_malloc or
18202 ** sqlite3_realloc.
18203 **
18204 ** The returned value is normally a copy of the second argument to this
18205 ** function. However, if a malloc() failure has occurred since the previous
18206 ** invocation SQLITE_NOMEM is returned instead. 
18207 **
18208 ** If the first argument, db, is not NULL and a malloc() error has occurred,
18209 ** then the connection error-code (the value returned by sqlite3_errcode())
18210 ** is set to SQLITE_NOMEM.
18211 */
18212 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18213   /* If the db handle is not NULL, then we must hold the connection handle
18214   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
18215   ** is unsafe, as is the call to sqlite3Error().
18216   */
18217   assert( !db || sqlite3_mutex_held(db->mutex) );
18218   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18219     sqlite3Error(db, SQLITE_NOMEM, 0);
18220     db->mallocFailed = 0;
18221     rc = SQLITE_NOMEM;
18222   }
18223   return rc & (db ? db->errMask : 0xff);
18224 }
18225
18226 /************** End of malloc.c **********************************************/
18227 /************** Begin file printf.c ******************************************/
18228 /*
18229 ** The "printf" code that follows dates from the 1980's.  It is in
18230 ** the public domain.  The original comments are included here for
18231 ** completeness.  They are very out-of-date but might be useful as
18232 ** an historical reference.  Most of the "enhancements" have been backed
18233 ** out so that the functionality is now the same as standard printf().
18234 **
18235 **************************************************************************
18236 **
18237 ** The following modules is an enhanced replacement for the "printf" subroutines
18238 ** found in the standard C library.  The following enhancements are
18239 ** supported:
18240 **
18241 **      +  Additional functions.  The standard set of "printf" functions
18242 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
18243 **         vsprintf.  This module adds the following:
18244 **
18245 **           *  snprintf -- Works like sprintf, but has an extra argument
18246 **                          which is the size of the buffer written to.
18247 **
18248 **           *  mprintf --  Similar to sprintf.  Writes output to memory
18249 **                          obtained from malloc.
18250 **
18251 **           *  xprintf --  Calls a function to dispose of output.
18252 **
18253 **           *  nprintf --  No output, but returns the number of characters
18254 **                          that would have been output by printf.
18255 **
18256 **           *  A v- version (ex: vsnprintf) of every function is also
18257 **              supplied.
18258 **
18259 **      +  A few extensions to the formatting notation are supported:
18260 **
18261 **           *  The "=" flag (similar to "-") causes the output to be
18262 **              be centered in the appropriately sized field.
18263 **
18264 **           *  The %b field outputs an integer in binary notation.
18265 **
18266 **           *  The %c field now accepts a precision.  The character output
18267 **              is repeated by the number of times the precision specifies.
18268 **
18269 **           *  The %' field works like %c, but takes as its character the
18270 **              next character of the format string, instead of the next
18271 **              argument.  For example,  printf("%.78'-")  prints 78 minus
18272 **              signs, the same as  printf("%.78c",'-').
18273 **
18274 **      +  When compiled using GCC on a SPARC, this version of printf is
18275 **         faster than the library printf for SUN OS 4.1.
18276 **
18277 **      +  All functions are fully reentrant.
18278 **
18279 */
18280
18281 /*
18282 ** Conversion types fall into various categories as defined by the
18283 ** following enumeration.
18284 */
18285 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
18286 #define etFLOAT       2 /* Floating point.  %f */
18287 #define etEXP         3 /* Exponentional notation. %e and %E */
18288 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
18289 #define etSIZE        5 /* Return number of characters processed so far. %n */
18290 #define etSTRING      6 /* Strings. %s */
18291 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
18292 #define etPERCENT     8 /* Percent symbol. %% */
18293 #define etCHARX       9 /* Characters. %c */
18294 /* The rest are extensions, not normally found in printf() */
18295 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
18296 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18297                           NULL pointers replaced by SQL NULL.  %Q */
18298 #define etTOKEN      12 /* a pointer to a Token structure */
18299 #define etSRCLIST    13 /* a pointer to a SrcList */
18300 #define etPOINTER    14 /* The %p conversion */
18301 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18302 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
18303
18304 #define etINVALID     0 /* Any unrecognized conversion type */
18305
18306
18307 /*
18308 ** An "etByte" is an 8-bit unsigned value.
18309 */
18310 typedef unsigned char etByte;
18311
18312 /*
18313 ** Each builtin conversion character (ex: the 'd' in "%d") is described
18314 ** by an instance of the following structure
18315 */
18316 typedef struct et_info {   /* Information about each format field */
18317   char fmttype;            /* The format field code letter */
18318   etByte base;             /* The base for radix conversion */
18319   etByte flags;            /* One or more of FLAG_ constants below */
18320   etByte type;             /* Conversion paradigm */
18321   etByte charset;          /* Offset into aDigits[] of the digits string */
18322   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
18323 } et_info;
18324
18325 /*
18326 ** Allowed values for et_info.flags
18327 */
18328 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
18329 #define FLAG_INTERN  2     /* True if for internal use only */
18330 #define FLAG_STRING  4     /* Allow infinity precision */
18331
18332
18333 /*
18334 ** The following table is searched linearly, so it is good to put the
18335 ** most frequently used conversion types first.
18336 */
18337 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
18338 static const char aPrefix[] = "-x0\000X0";
18339 static const et_info fmtinfo[] = {
18340   {  'd', 10, 1, etRADIX,      0,  0 },
18341   {  's',  0, 4, etSTRING,     0,  0 },
18342   {  'g',  0, 1, etGENERIC,    30, 0 },
18343   {  'z',  0, 4, etDYNSTRING,  0,  0 },
18344   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
18345   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
18346   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
18347   {  'c',  0, 0, etCHARX,      0,  0 },
18348   {  'o',  8, 0, etRADIX,      0,  2 },
18349   {  'u', 10, 0, etRADIX,      0,  0 },
18350   {  'x', 16, 0, etRADIX,      16, 1 },
18351   {  'X', 16, 0, etRADIX,      0,  4 },
18352 #ifndef SQLITE_OMIT_FLOATING_POINT
18353   {  'f',  0, 1, etFLOAT,      0,  0 },
18354   {  'e',  0, 1, etEXP,        30, 0 },
18355   {  'E',  0, 1, etEXP,        14, 0 },
18356   {  'G',  0, 1, etGENERIC,    14, 0 },
18357 #endif
18358   {  'i', 10, 1, etRADIX,      0,  0 },
18359   {  'n',  0, 0, etSIZE,       0,  0 },
18360   {  '%',  0, 0, etPERCENT,    0,  0 },
18361   {  'p', 16, 0, etPOINTER,    0,  1 },
18362
18363 /* All the rest have the FLAG_INTERN bit set and are thus for internal
18364 ** use only */
18365   {  'T',  0, 2, etTOKEN,      0,  0 },
18366   {  'S',  0, 2, etSRCLIST,    0,  0 },
18367   {  'r', 10, 3, etORDINAL,    0,  0 },
18368 };
18369
18370 /*
18371 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
18372 ** conversions will work.
18373 */
18374 #ifndef SQLITE_OMIT_FLOATING_POINT
18375 /*
18376 ** "*val" is a double such that 0.1 <= *val < 10.0
18377 ** Return the ascii code for the leading digit of *val, then
18378 ** multiply "*val" by 10.0 to renormalize.
18379 **
18380 ** Example:
18381 **     input:     *val = 3.14159
18382 **     output:    *val = 1.4159    function return = '3'
18383 **
18384 ** The counter *cnt is incremented each time.  After counter exceeds
18385 ** 16 (the number of significant digits in a 64-bit float) '0' is
18386 ** always returned.
18387 */
18388 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
18389   int digit;
18390   LONGDOUBLE_TYPE d;
18391   if( (*cnt)++ >= 16 ) return '0';
18392   digit = (int)*val;
18393   d = digit;
18394   digit += '0';
18395   *val = (*val - d)*10.0;
18396   return (char)digit;
18397 }
18398 #endif /* SQLITE_OMIT_FLOATING_POINT */
18399
18400 /*
18401 ** Append N space characters to the given string buffer.
18402 */
18403 static void appendSpace(StrAccum *pAccum, int N){
18404   static const char zSpaces[] = "                             ";
18405   while( N>=(int)sizeof(zSpaces)-1 ){
18406     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
18407     N -= sizeof(zSpaces)-1;
18408   }
18409   if( N>0 ){
18410     sqlite3StrAccumAppend(pAccum, zSpaces, N);
18411   }
18412 }
18413
18414 /*
18415 ** On machines with a small stack size, you can redefine the
18416 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
18417 */
18418 #ifndef SQLITE_PRINT_BUF_SIZE
18419 # if defined(SQLITE_SMALL_STACK)
18420 #   define SQLITE_PRINT_BUF_SIZE 50
18421 # else
18422 #   define SQLITE_PRINT_BUF_SIZE 350
18423 # endif
18424 #endif
18425 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
18426
18427 /*
18428 ** The root program.  All variations call this core.
18429 **
18430 ** INPUTS:
18431 **   func   This is a pointer to a function taking three arguments
18432 **            1. A pointer to anything.  Same as the "arg" parameter.
18433 **            2. A pointer to the list of characters to be output
18434 **               (Note, this list is NOT null terminated.)
18435 **            3. An integer number of characters to be output.
18436 **               (Note: This number might be zero.)
18437 **
18438 **   arg    This is the pointer to anything which will be passed as the
18439 **          first argument to "func".  Use it for whatever you like.
18440 **
18441 **   fmt    This is the format string, as in the usual print.
18442 **
18443 **   ap     This is a pointer to a list of arguments.  Same as in
18444 **          vfprint.
18445 **
18446 ** OUTPUTS:
18447 **          The return value is the total number of characters sent to
18448 **          the function "func".  Returns -1 on a error.
18449 **
18450 ** Note that the order in which automatic variables are declared below
18451 ** seems to make a big difference in determining how fast this beast
18452 ** will run.
18453 */
18454 SQLITE_PRIVATE void sqlite3VXPrintf(
18455   StrAccum *pAccum,                  /* Accumulate results here */
18456   int useExtended,                   /* Allow extended %-conversions */
18457   const char *fmt,                   /* Format string */
18458   va_list ap                         /* arguments */
18459 ){
18460   int c;                     /* Next character in the format string */
18461   char *bufpt;               /* Pointer to the conversion buffer */
18462   int precision;             /* Precision of the current field */
18463   int length;                /* Length of the field */
18464   int idx;                   /* A general purpose loop counter */
18465   int width;                 /* Width of the current field */
18466   etByte flag_leftjustify;   /* True if "-" flag is present */
18467   etByte flag_plussign;      /* True if "+" flag is present */
18468   etByte flag_blanksign;     /* True if " " flag is present */
18469   etByte flag_alternateform; /* True if "#" flag is present */
18470   etByte flag_altform2;      /* True if "!" flag is present */
18471   etByte flag_zeropad;       /* True if field width constant starts with zero */
18472   etByte flag_long;          /* True if "l" flag is present */
18473   etByte flag_longlong;      /* True if the "ll" flag is present */
18474   etByte done;               /* Loop termination flag */
18475   sqlite_uint64 longvalue;   /* Value for integer types */
18476   LONGDOUBLE_TYPE realvalue; /* Value for real types */
18477   const et_info *infop;      /* Pointer to the appropriate info structure */
18478   char buf[etBUFSIZE];       /* Conversion buffer */
18479   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
18480   etByte xtype = 0;          /* Conversion paradigm */
18481   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
18482 #ifndef SQLITE_OMIT_FLOATING_POINT
18483   int  exp, e2;              /* exponent of real numbers */
18484   double rounder;            /* Used for rounding floating point values */
18485   etByte flag_dp;            /* True if decimal point should be shown */
18486   etByte flag_rtz;           /* True if trailing zeros should be removed */
18487   etByte flag_exp;           /* True to force display of the exponent */
18488   int nsd;                   /* Number of significant digits returned */
18489 #endif
18490
18491   length = 0;
18492   bufpt = 0;
18493   for(; (c=(*fmt))!=0; ++fmt){
18494     if( c!='%' ){
18495       int amt;
18496       bufpt = (char *)fmt;
18497       amt = 1;
18498       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
18499       sqlite3StrAccumAppend(pAccum, bufpt, amt);
18500       if( c==0 ) break;
18501     }
18502     if( (c=(*++fmt))==0 ){
18503       sqlite3StrAccumAppend(pAccum, "%", 1);
18504       break;
18505     }
18506     /* Find out what flags are present */
18507     flag_leftjustify = flag_plussign = flag_blanksign = 
18508      flag_alternateform = flag_altform2 = flag_zeropad = 0;
18509     done = 0;
18510     do{
18511       switch( c ){
18512         case '-':   flag_leftjustify = 1;     break;
18513         case '+':   flag_plussign = 1;        break;
18514         case ' ':   flag_blanksign = 1;       break;
18515         case '#':   flag_alternateform = 1;   break;
18516         case '!':   flag_altform2 = 1;        break;
18517         case '0':   flag_zeropad = 1;         break;
18518         default:    done = 1;                 break;
18519       }
18520     }while( !done && (c=(*++fmt))!=0 );
18521     /* Get the field width */
18522     width = 0;
18523     if( c=='*' ){
18524       width = va_arg(ap,int);
18525       if( width<0 ){
18526         flag_leftjustify = 1;
18527         width = -width;
18528       }
18529       c = *++fmt;
18530     }else{
18531       while( c>='0' && c<='9' ){
18532         width = width*10 + c - '0';
18533         c = *++fmt;
18534       }
18535     }
18536     if( width > etBUFSIZE-10 ){
18537       width = etBUFSIZE-10;
18538     }
18539     /* Get the precision */
18540     if( c=='.' ){
18541       precision = 0;
18542       c = *++fmt;
18543       if( c=='*' ){
18544         precision = va_arg(ap,int);
18545         if( precision<0 ) precision = -precision;
18546         c = *++fmt;
18547       }else{
18548         while( c>='0' && c<='9' ){
18549           precision = precision*10 + c - '0';
18550           c = *++fmt;
18551         }
18552       }
18553     }else{
18554       precision = -1;
18555     }
18556     /* Get the conversion type modifier */
18557     if( c=='l' ){
18558       flag_long = 1;
18559       c = *++fmt;
18560       if( c=='l' ){
18561         flag_longlong = 1;
18562         c = *++fmt;
18563       }else{
18564         flag_longlong = 0;
18565       }
18566     }else{
18567       flag_long = flag_longlong = 0;
18568     }
18569     /* Fetch the info entry for the field */
18570     infop = &fmtinfo[0];
18571     xtype = etINVALID;
18572     for(idx=0; idx<ArraySize(fmtinfo); idx++){
18573       if( c==fmtinfo[idx].fmttype ){
18574         infop = &fmtinfo[idx];
18575         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
18576           xtype = infop->type;
18577         }else{
18578           return;
18579         }
18580         break;
18581       }
18582     }
18583     zExtra = 0;
18584
18585
18586     /* Limit the precision to prevent overflowing buf[] during conversion */
18587     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
18588       precision = etBUFSIZE-40;
18589     }
18590
18591     /*
18592     ** At this point, variables are initialized as follows:
18593     **
18594     **   flag_alternateform          TRUE if a '#' is present.
18595     **   flag_altform2               TRUE if a '!' is present.
18596     **   flag_plussign               TRUE if a '+' is present.
18597     **   flag_leftjustify            TRUE if a '-' is present or if the
18598     **                               field width was negative.
18599     **   flag_zeropad                TRUE if the width began with 0.
18600     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
18601     **                               the conversion character.
18602     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
18603     **                               the conversion character.
18604     **   flag_blanksign              TRUE if a ' ' is present.
18605     **   width                       The specified field width.  This is
18606     **                               always non-negative.  Zero is the default.
18607     **   precision                   The specified precision.  The default
18608     **                               is -1.
18609     **   xtype                       The class of the conversion.
18610     **   infop                       Pointer to the appropriate info struct.
18611     */
18612     switch( xtype ){
18613       case etPOINTER:
18614         flag_longlong = sizeof(char*)==sizeof(i64);
18615         flag_long = sizeof(char*)==sizeof(long int);
18616         /* Fall through into the next case */
18617       case etORDINAL:
18618       case etRADIX:
18619         if( infop->flags & FLAG_SIGNED ){
18620           i64 v;
18621           if( flag_longlong ){
18622             v = va_arg(ap,i64);
18623           }else if( flag_long ){
18624             v = va_arg(ap,long int);
18625           }else{
18626             v = va_arg(ap,int);
18627           }
18628           if( v<0 ){
18629             longvalue = -v;
18630             prefix = '-';
18631           }else{
18632             longvalue = v;
18633             if( flag_plussign )        prefix = '+';
18634             else if( flag_blanksign )  prefix = ' ';
18635             else                       prefix = 0;
18636           }
18637         }else{
18638           if( flag_longlong ){
18639             longvalue = va_arg(ap,u64);
18640           }else if( flag_long ){
18641             longvalue = va_arg(ap,unsigned long int);
18642           }else{
18643             longvalue = va_arg(ap,unsigned int);
18644           }
18645           prefix = 0;
18646         }
18647         if( longvalue==0 ) flag_alternateform = 0;
18648         if( flag_zeropad && precision<width-(prefix!=0) ){
18649           precision = width-(prefix!=0);
18650         }
18651         bufpt = &buf[etBUFSIZE-1];
18652         if( xtype==etORDINAL ){
18653           static const char zOrd[] = "thstndrd";
18654           int x = (int)(longvalue % 10);
18655           if( x>=4 || (longvalue/10)%10==1 ){
18656             x = 0;
18657           }
18658           buf[etBUFSIZE-3] = zOrd[x*2];
18659           buf[etBUFSIZE-2] = zOrd[x*2+1];
18660           bufpt -= 2;
18661         }
18662         {
18663           register const char *cset;      /* Use registers for speed */
18664           register int base;
18665           cset = &aDigits[infop->charset];
18666           base = infop->base;
18667           do{                                           /* Convert to ascii */
18668             *(--bufpt) = cset[longvalue%base];
18669             longvalue = longvalue/base;
18670           }while( longvalue>0 );
18671         }
18672         length = (int)(&buf[etBUFSIZE-1]-bufpt);
18673         for(idx=precision-length; idx>0; idx--){
18674           *(--bufpt) = '0';                             /* Zero pad */
18675         }
18676         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
18677         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
18678           const char *pre;
18679           char x;
18680           pre = &aPrefix[infop->prefix];
18681           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
18682         }
18683         length = (int)(&buf[etBUFSIZE-1]-bufpt);
18684         break;
18685       case etFLOAT:
18686       case etEXP:
18687       case etGENERIC:
18688         realvalue = va_arg(ap,double);
18689 #ifdef SQLITE_OMIT_FLOATING_POINT
18690         length = 0;
18691 #else
18692         if( precision<0 ) precision = 6;         /* Set default precision */
18693         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
18694         if( realvalue<0.0 ){
18695           realvalue = -realvalue;
18696           prefix = '-';
18697         }else{
18698           if( flag_plussign )          prefix = '+';
18699           else if( flag_blanksign )    prefix = ' ';
18700           else                         prefix = 0;
18701         }
18702         if( xtype==etGENERIC && precision>0 ) precision--;
18703 #if 0
18704         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
18705         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
18706 #else
18707         /* It makes more sense to use 0.5 */
18708         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
18709 #endif
18710         if( xtype==etFLOAT ) realvalue += rounder;
18711         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
18712         exp = 0;
18713         if( sqlite3IsNaN((double)realvalue) ){
18714           bufpt = "NaN";
18715           length = 3;
18716           break;
18717         }
18718         if( realvalue>0.0 ){
18719           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
18720           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
18721           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
18722           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
18723           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
18724           if( exp>350 ){
18725             if( prefix=='-' ){
18726               bufpt = "-Inf";
18727             }else if( prefix=='+' ){
18728               bufpt = "+Inf";
18729             }else{
18730               bufpt = "Inf";
18731             }
18732             length = sqlite3Strlen30(bufpt);
18733             break;
18734           }
18735         }
18736         bufpt = buf;
18737         /*
18738         ** If the field type is etGENERIC, then convert to either etEXP
18739         ** or etFLOAT, as appropriate.
18740         */
18741         flag_exp = xtype==etEXP;
18742         if( xtype!=etFLOAT ){
18743           realvalue += rounder;
18744           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
18745         }
18746         if( xtype==etGENERIC ){
18747           flag_rtz = !flag_alternateform;
18748           if( exp<-4 || exp>precision ){
18749             xtype = etEXP;
18750           }else{
18751             precision = precision - exp;
18752             xtype = etFLOAT;
18753           }
18754         }else{
18755           flag_rtz = 0;
18756         }
18757         if( xtype==etEXP ){
18758           e2 = 0;
18759         }else{
18760           e2 = exp;
18761         }
18762         nsd = 0;
18763         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
18764         /* The sign in front of the number */
18765         if( prefix ){
18766           *(bufpt++) = prefix;
18767         }
18768         /* Digits prior to the decimal point */
18769         if( e2<0 ){
18770           *(bufpt++) = '0';
18771         }else{
18772           for(; e2>=0; e2--){
18773             *(bufpt++) = et_getdigit(&realvalue,&nsd);
18774           }
18775         }
18776         /* The decimal point */
18777         if( flag_dp ){
18778           *(bufpt++) = '.';
18779         }
18780         /* "0" digits after the decimal point but before the first
18781         ** significant digit of the number */
18782         for(e2++; e2<0; precision--, e2++){
18783           assert( precision>0 );
18784           *(bufpt++) = '0';
18785         }
18786         /* Significant digits after the decimal point */
18787         while( (precision--)>0 ){
18788           *(bufpt++) = et_getdigit(&realvalue,&nsd);
18789         }
18790         /* Remove trailing zeros and the "." if no digits follow the "." */
18791         if( flag_rtz && flag_dp ){
18792           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
18793           assert( bufpt>buf );
18794           if( bufpt[-1]=='.' ){
18795             if( flag_altform2 ){
18796               *(bufpt++) = '0';
18797             }else{
18798               *(--bufpt) = 0;
18799             }
18800           }
18801         }
18802         /* Add the "eNNN" suffix */
18803         if( flag_exp || xtype==etEXP ){
18804           *(bufpt++) = aDigits[infop->charset];
18805           if( exp<0 ){
18806             *(bufpt++) = '-'; exp = -exp;
18807           }else{
18808             *(bufpt++) = '+';
18809           }
18810           if( exp>=100 ){
18811             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
18812             exp %= 100;
18813           }
18814           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
18815           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
18816         }
18817         *bufpt = 0;
18818
18819         /* The converted number is in buf[] and zero terminated. Output it.
18820         ** Note that the number is in the usual order, not reversed as with
18821         ** integer conversions. */
18822         length = (int)(bufpt-buf);
18823         bufpt = buf;
18824
18825         /* Special case:  Add leading zeros if the flag_zeropad flag is
18826         ** set and we are not left justified */
18827         if( flag_zeropad && !flag_leftjustify && length < width){
18828           int i;
18829           int nPad = width - length;
18830           for(i=width; i>=nPad; i--){
18831             bufpt[i] = bufpt[i-nPad];
18832           }
18833           i = prefix!=0;
18834           while( nPad-- ) bufpt[i++] = '0';
18835           length = width;
18836         }
18837 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
18838         break;
18839       case etSIZE:
18840         *(va_arg(ap,int*)) = pAccum->nChar;
18841         length = width = 0;
18842         break;
18843       case etPERCENT:
18844         buf[0] = '%';
18845         bufpt = buf;
18846         length = 1;
18847         break;
18848       case etCHARX:
18849         c = va_arg(ap,int);
18850         buf[0] = (char)c;
18851         if( precision>=0 ){
18852           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
18853           length = precision;
18854         }else{
18855           length =1;
18856         }
18857         bufpt = buf;
18858         break;
18859       case etSTRING:
18860       case etDYNSTRING:
18861         bufpt = va_arg(ap,char*);
18862         if( bufpt==0 ){
18863           bufpt = "";
18864         }else if( xtype==etDYNSTRING ){
18865           zExtra = bufpt;
18866         }
18867         if( precision>=0 ){
18868           for(length=0; length<precision && bufpt[length]; length++){}
18869         }else{
18870           length = sqlite3Strlen30(bufpt);
18871         }
18872         break;
18873       case etSQLESCAPE:
18874       case etSQLESCAPE2:
18875       case etSQLESCAPE3: {
18876         int i, j, k, n, isnull;
18877         int needQuote;
18878         char ch;
18879         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
18880         char *escarg = va_arg(ap,char*);
18881         isnull = escarg==0;
18882         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
18883         k = precision;
18884         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
18885           if( ch==q )  n++;
18886         }
18887         needQuote = !isnull && xtype==etSQLESCAPE2;
18888         n += i + 1 + needQuote*2;
18889         if( n>etBUFSIZE ){
18890           bufpt = zExtra = sqlite3Malloc( n );
18891           if( bufpt==0 ){
18892             pAccum->mallocFailed = 1;
18893             return;
18894           }
18895         }else{
18896           bufpt = buf;
18897         }
18898         j = 0;
18899         if( needQuote ) bufpt[j++] = q;
18900         k = i;
18901         for(i=0; i<k; i++){
18902           bufpt[j++] = ch = escarg[i];
18903           if( ch==q ) bufpt[j++] = ch;
18904         }
18905         if( needQuote ) bufpt[j++] = q;
18906         bufpt[j] = 0;
18907         length = j;
18908         /* The precision in %q and %Q means how many input characters to
18909         ** consume, not the length of the output...
18910         ** if( precision>=0 && precision<length ) length = precision; */
18911         break;
18912       }
18913       case etTOKEN: {
18914         Token *pToken = va_arg(ap, Token*);
18915         if( pToken ){
18916           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
18917         }
18918         length = width = 0;
18919         break;
18920       }
18921       case etSRCLIST: {
18922         SrcList *pSrc = va_arg(ap, SrcList*);
18923         int k = va_arg(ap, int);
18924         struct SrcList_item *pItem = &pSrc->a[k];
18925         assert( k>=0 && k<pSrc->nSrc );
18926         if( pItem->zDatabase ){
18927           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
18928           sqlite3StrAccumAppend(pAccum, ".", 1);
18929         }
18930         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
18931         length = width = 0;
18932         break;
18933       }
18934       default: {
18935         assert( xtype==etINVALID );
18936         return;
18937       }
18938     }/* End switch over the format type */
18939     /*
18940     ** The text of the conversion is pointed to by "bufpt" and is
18941     ** "length" characters long.  The field width is "width".  Do
18942     ** the output.
18943     */
18944     if( !flag_leftjustify ){
18945       register int nspace;
18946       nspace = width-length;
18947       if( nspace>0 ){
18948         appendSpace(pAccum, nspace);
18949       }
18950     }
18951     if( length>0 ){
18952       sqlite3StrAccumAppend(pAccum, bufpt, length);
18953     }
18954     if( flag_leftjustify ){
18955       register int nspace;
18956       nspace = width-length;
18957       if( nspace>0 ){
18958         appendSpace(pAccum, nspace);
18959       }
18960     }
18961     if( zExtra ){
18962       sqlite3_free(zExtra);
18963     }
18964   }/* End for loop over the format string */
18965 } /* End of function */
18966
18967 /*
18968 ** Append N bytes of text from z to the StrAccum object.
18969 */
18970 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
18971   assert( z!=0 || N==0 );
18972   if( p->tooBig | p->mallocFailed ){
18973     testcase(p->tooBig);
18974     testcase(p->mallocFailed);
18975     return;
18976   }
18977   if( N<0 ){
18978     N = sqlite3Strlen30(z);
18979   }
18980   if( N==0 || NEVER(z==0) ){
18981     return;
18982   }
18983   if( p->nChar+N >= p->nAlloc ){
18984     char *zNew;
18985     if( !p->useMalloc ){
18986       p->tooBig = 1;
18987       N = p->nAlloc - p->nChar - 1;
18988       if( N<=0 ){
18989         return;
18990       }
18991     }else{
18992       i64 szNew = p->nChar;
18993       szNew += N + 1;
18994       if( szNew > p->mxAlloc ){
18995         sqlite3StrAccumReset(p);
18996         p->tooBig = 1;
18997         return;
18998       }else{
18999         p->nAlloc = (int)szNew;
19000       }
19001       if( p->useMalloc==1 ){
19002         zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
19003       }else{
19004         zNew = sqlite3_malloc(p->nAlloc);
19005       }
19006       if( zNew ){
19007         memcpy(zNew, p->zText, p->nChar);
19008         sqlite3StrAccumReset(p);
19009         p->zText = zNew;
19010       }else{
19011         p->mallocFailed = 1;
19012         sqlite3StrAccumReset(p);
19013         return;
19014       }
19015     }
19016   }
19017   memcpy(&p->zText[p->nChar], z, N);
19018   p->nChar += N;
19019 }
19020
19021 /*
19022 ** Finish off a string by making sure it is zero-terminated.
19023 ** Return a pointer to the resulting string.  Return a NULL
19024 ** pointer if any kind of error was encountered.
19025 */
19026 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19027   if( p->zText ){
19028     p->zText[p->nChar] = 0;
19029     if( p->useMalloc && p->zText==p->zBase ){
19030       if( p->useMalloc==1 ){
19031         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19032       }else{
19033         p->zText = sqlite3_malloc(p->nChar+1);
19034       }
19035       if( p->zText ){
19036         memcpy(p->zText, p->zBase, p->nChar+1);
19037       }else{
19038         p->mallocFailed = 1;
19039       }
19040     }
19041   }
19042   return p->zText;
19043 }
19044
19045 /*
19046 ** Reset an StrAccum string.  Reclaim all malloced memory.
19047 */
19048 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
19049   if( p->zText!=p->zBase ){
19050     if( p->useMalloc==1 ){
19051       sqlite3DbFree(p->db, p->zText);
19052     }else{
19053       sqlite3_free(p->zText);
19054     }
19055   }
19056   p->zText = 0;
19057 }
19058
19059 /*
19060 ** Initialize a string accumulator
19061 */
19062 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
19063   p->zText = p->zBase = zBase;
19064   p->db = 0;
19065   p->nChar = 0;
19066   p->nAlloc = n;
19067   p->mxAlloc = mx;
19068   p->useMalloc = 1;
19069   p->tooBig = 0;
19070   p->mallocFailed = 0;
19071 }
19072
19073 /*
19074 ** Print into memory obtained from sqliteMalloc().  Use the internal
19075 ** %-conversion extensions.
19076 */
19077 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
19078   char *z;
19079   char zBase[SQLITE_PRINT_BUF_SIZE];
19080   StrAccum acc;
19081   assert( db!=0 );
19082   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
19083                       db->aLimit[SQLITE_LIMIT_LENGTH]);
19084   acc.db = db;
19085   sqlite3VXPrintf(&acc, 1, zFormat, ap);
19086   z = sqlite3StrAccumFinish(&acc);
19087   if( acc.mallocFailed ){
19088     db->mallocFailed = 1;
19089   }
19090   return z;
19091 }
19092
19093 /*
19094 ** Print into memory obtained from sqliteMalloc().  Use the internal
19095 ** %-conversion extensions.
19096 */
19097 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19098   va_list ap;
19099   char *z;
19100   va_start(ap, zFormat);
19101   z = sqlite3VMPrintf(db, zFormat, ap);
19102   va_end(ap);
19103   return z;
19104 }
19105
19106 /*
19107 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19108 ** the string and before returnning.  This routine is intended to be used
19109 ** to modify an existing string.  For example:
19110 **
19111 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19112 **
19113 */
19114 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19115   va_list ap;
19116   char *z;
19117   va_start(ap, zFormat);
19118   z = sqlite3VMPrintf(db, zFormat, ap);
19119   va_end(ap);
19120   sqlite3DbFree(db, zStr);
19121   return z;
19122 }
19123
19124 /*
19125 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
19126 ** %-conversion extensions.
19127 */
19128 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19129   char *z;
19130   char zBase[SQLITE_PRINT_BUF_SIZE];
19131   StrAccum acc;
19132 #ifndef SQLITE_OMIT_AUTOINIT
19133   if( sqlite3_initialize() ) return 0;
19134 #endif
19135   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19136   acc.useMalloc = 2;
19137   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19138   z = sqlite3StrAccumFinish(&acc);
19139   return z;
19140 }
19141
19142 /*
19143 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
19144 ** %-conversion extensions.
19145 */
19146 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19147   va_list ap;
19148   char *z;
19149 #ifndef SQLITE_OMIT_AUTOINIT
19150   if( sqlite3_initialize() ) return 0;
19151 #endif
19152   va_start(ap, zFormat);
19153   z = sqlite3_vmprintf(zFormat, ap);
19154   va_end(ap);
19155   return z;
19156 }
19157
19158 /*
19159 ** sqlite3_snprintf() works like snprintf() except that it ignores the
19160 ** current locale settings.  This is important for SQLite because we
19161 ** are not able to use a "," as the decimal point in place of "." as
19162 ** specified by some locales.
19163 */
19164 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19165   char *z;
19166   va_list ap;
19167   StrAccum acc;
19168
19169   if( n<=0 ){
19170     return zBuf;
19171   }
19172   sqlite3StrAccumInit(&acc, zBuf, n, 0);
19173   acc.useMalloc = 0;
19174   va_start(ap,zFormat);
19175   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19176   va_end(ap);
19177   z = sqlite3StrAccumFinish(&acc);
19178   return z;
19179 }
19180
19181 /*
19182 ** This is the routine that actually formats the sqlite3_log() message.
19183 ** We house it in a separate routine from sqlite3_log() to avoid using
19184 ** stack space on small-stack systems when logging is disabled.
19185 **
19186 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
19187 ** allocate memory because it might be called while the memory allocator
19188 ** mutex is held.
19189 */
19190 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19191   StrAccum acc;                          /* String accumulator */
19192   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
19193
19194   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19195   acc.useMalloc = 0;
19196   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19197   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19198                            sqlite3StrAccumFinish(&acc));
19199 }
19200
19201 /*
19202 ** Format and write a message to the log if logging is enabled.
19203 */
19204 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19205   va_list ap;                             /* Vararg list */
19206   if( sqlite3GlobalConfig.xLog ){
19207     va_start(ap, zFormat);
19208     renderLogMsg(iErrCode, zFormat, ap);
19209     va_end(ap);
19210   }
19211 }
19212
19213 #if defined(SQLITE_DEBUG)
19214 /*
19215 ** A version of printf() that understands %lld.  Used for debugging.
19216 ** The printf() built into some versions of windows does not understand %lld
19217 ** and segfaults if you give it a long long int.
19218 */
19219 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19220   va_list ap;
19221   StrAccum acc;
19222   char zBuf[500];
19223   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19224   acc.useMalloc = 0;
19225   va_start(ap,zFormat);
19226   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19227   va_end(ap);
19228   sqlite3StrAccumFinish(&acc);
19229   fprintf(stdout,"%s", zBuf);
19230   fflush(stdout);
19231 }
19232 #endif
19233
19234 #ifndef SQLITE_OMIT_TRACE
19235 /*
19236 ** variable-argument wrapper around sqlite3VXPrintf().
19237 */
19238 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19239   va_list ap;
19240   va_start(ap,zFormat);
19241   sqlite3VXPrintf(p, 1, zFormat, ap);
19242   va_end(ap);
19243 }
19244 #endif
19245
19246 /************** End of printf.c **********************************************/
19247 /************** Begin file random.c ******************************************/
19248 /*
19249 ** 2001 September 15
19250 **
19251 ** The author disclaims copyright to this source code.  In place of
19252 ** a legal notice, here is a blessing:
19253 **
19254 **    May you do good and not evil.
19255 **    May you find forgiveness for yourself and forgive others.
19256 **    May you share freely, never taking more than you give.
19257 **
19258 *************************************************************************
19259 ** This file contains code to implement a pseudo-random number
19260 ** generator (PRNG) for SQLite.
19261 **
19262 ** Random numbers are used by some of the database backends in order
19263 ** to generate random integer keys for tables or random filenames.
19264 */
19265
19266
19267 /* All threads share a single random number generator.
19268 ** This structure is the current state of the generator.
19269 */
19270 static SQLITE_WSD struct sqlite3PrngType {
19271   unsigned char isInit;          /* True if initialized */
19272   unsigned char i, j;            /* State variables */
19273   unsigned char s[256];          /* State variables */
19274 } sqlite3Prng;
19275
19276 /*
19277 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
19278 ** must be held while executing this routine.
19279 **
19280 ** Why not just use a library random generator like lrand48() for this?
19281 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
19282 ** good source of random numbers.  The lrand48() library function may
19283 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
19284 ** subtle problems on some systems that could cause problems.  It is hard
19285 ** to know.  To minimize the risk of problems due to bad lrand48()
19286 ** implementations, SQLite uses this random number generator based
19287 ** on RC4, which we know works very well.
19288 **
19289 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
19290 ** randomness any more.  But we will leave this code in all the same.
19291 */
19292 static u8 randomByte(void){
19293   unsigned char t;
19294
19295
19296   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19297   ** state vector.  If writable static data is unsupported on the target,
19298   ** we have to locate the state vector at run-time.  In the more common
19299   ** case where writable static data is supported, wsdPrng can refer directly
19300   ** to the "sqlite3Prng" state vector declared above.
19301   */
19302 #ifdef SQLITE_OMIT_WSD
19303   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19304 # define wsdPrng p[0]
19305 #else
19306 # define wsdPrng sqlite3Prng
19307 #endif
19308
19309
19310   /* Initialize the state of the random number generator once,
19311   ** the first time this routine is called.  The seed value does
19312   ** not need to contain a lot of randomness since we are not
19313   ** trying to do secure encryption or anything like that...
19314   **
19315   ** Nothing in this file or anywhere else in SQLite does any kind of
19316   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
19317   ** number generator) not as an encryption device.
19318   */
19319   if( !wsdPrng.isInit ){
19320     int i;
19321     char k[256];
19322     wsdPrng.j = 0;
19323     wsdPrng.i = 0;
19324     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
19325     for(i=0; i<256; i++){
19326       wsdPrng.s[i] = (u8)i;
19327     }
19328     for(i=0; i<256; i++){
19329       wsdPrng.j += wsdPrng.s[i] + k[i];
19330       t = wsdPrng.s[wsdPrng.j];
19331       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
19332       wsdPrng.s[i] = t;
19333     }
19334     wsdPrng.isInit = 1;
19335   }
19336
19337   /* Generate and return single random byte
19338   */
19339   wsdPrng.i++;
19340   t = wsdPrng.s[wsdPrng.i];
19341   wsdPrng.j += t;
19342   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
19343   wsdPrng.s[wsdPrng.j] = t;
19344   t += wsdPrng.s[wsdPrng.i];
19345   return wsdPrng.s[t];
19346 }
19347
19348 /*
19349 ** Return N random bytes.
19350 */
19351 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
19352   unsigned char *zBuf = pBuf;
19353 #if SQLITE_THREADSAFE
19354   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
19355 #endif
19356   sqlite3_mutex_enter(mutex);
19357   while( N-- ){
19358     *(zBuf++) = randomByte();
19359   }
19360   sqlite3_mutex_leave(mutex);
19361 }
19362
19363 #ifndef SQLITE_OMIT_BUILTIN_TEST
19364 /*
19365 ** For testing purposes, we sometimes want to preserve the state of
19366 ** PRNG and restore the PRNG to its saved state at a later time, or
19367 ** to reset the PRNG to its initial state.  These routines accomplish
19368 ** those tasks.
19369 **
19370 ** The sqlite3_test_control() interface calls these routines to
19371 ** control the PRNG.
19372 */
19373 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
19374 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
19375   memcpy(
19376     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19377     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19378     sizeof(sqlite3Prng)
19379   );
19380 }
19381 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
19382   memcpy(
19383     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
19384     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
19385     sizeof(sqlite3Prng)
19386   );
19387 }
19388 SQLITE_PRIVATE void sqlite3PrngResetState(void){
19389   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
19390 }
19391 #endif /* SQLITE_OMIT_BUILTIN_TEST */
19392
19393 /************** End of random.c **********************************************/
19394 /************** Begin file utf.c *********************************************/
19395 /*
19396 ** 2004 April 13
19397 **
19398 ** The author disclaims copyright to this source code.  In place of
19399 ** a legal notice, here is a blessing:
19400 **
19401 **    May you do good and not evil.
19402 **    May you find forgiveness for yourself and forgive others.
19403 **    May you share freely, never taking more than you give.
19404 **
19405 *************************************************************************
19406 ** This file contains routines used to translate between UTF-8, 
19407 ** UTF-16, UTF-16BE, and UTF-16LE.
19408 **
19409 ** Notes on UTF-8:
19410 **
19411 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
19412 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
19413 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
19414 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
19415 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
19416 **
19417 **
19418 ** Notes on UTF-16:  (with wwww+1==uuuuu)
19419 **
19420 **      Word-0               Word-1          Value
19421 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
19422 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
19423 **
19424 **
19425 ** BOM or Byte Order Mark:
19426 **     0xff 0xfe   little-endian utf-16 follows
19427 **     0xfe 0xff   big-endian utf-16 follows
19428 **
19429 */
19430
19431 #ifndef SQLITE_AMALGAMATION
19432 /*
19433 ** The following constant value is used by the SQLITE_BIGENDIAN and
19434 ** SQLITE_LITTLEENDIAN macros.
19435 */
19436 SQLITE_PRIVATE const int sqlite3one = 1;
19437 #endif /* SQLITE_AMALGAMATION */
19438
19439 /*
19440 ** This lookup table is used to help decode the first byte of
19441 ** a multi-byte UTF8 character.
19442 */
19443 static const unsigned char sqlite3Utf8Trans1[] = {
19444   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19445   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19446   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
19447   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
19448   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19449   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
19450   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
19451   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
19452 };
19453
19454
19455 #define WRITE_UTF8(zOut, c) {                          \
19456   if( c<0x00080 ){                                     \
19457     *zOut++ = (u8)(c&0xFF);                            \
19458   }                                                    \
19459   else if( c<0x00800 ){                                \
19460     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
19461     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19462   }                                                    \
19463   else if( c<0x10000 ){                                \
19464     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
19465     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19466     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19467   }else{                                               \
19468     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
19469     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
19470     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
19471     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
19472   }                                                    \
19473 }
19474
19475 #define WRITE_UTF16LE(zOut, c) {                                    \
19476   if( c<=0xFFFF ){                                                  \
19477     *zOut++ = (u8)(c&0x00FF);                                       \
19478     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19479   }else{                                                            \
19480     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19481     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19482     *zOut++ = (u8)(c&0x00FF);                                       \
19483     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19484   }                                                                 \
19485 }
19486
19487 #define WRITE_UTF16BE(zOut, c) {                                    \
19488   if( c<=0xFFFF ){                                                  \
19489     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
19490     *zOut++ = (u8)(c&0x00FF);                                       \
19491   }else{                                                            \
19492     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
19493     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
19494     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
19495     *zOut++ = (u8)(c&0x00FF);                                       \
19496   }                                                                 \
19497 }
19498
19499 #define READ_UTF16LE(zIn, TERM, c){                                   \
19500   c = (*zIn++);                                                       \
19501   c += ((*zIn++)<<8);                                                 \
19502   if( c>=0xD800 && c<0xE000 && TERM ){                                \
19503     int c2 = (*zIn++);                                                \
19504     c2 += ((*zIn++)<<8);                                              \
19505     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19506   }                                                                   \
19507 }
19508
19509 #define READ_UTF16BE(zIn, TERM, c){                                   \
19510   c = ((*zIn++)<<8);                                                  \
19511   c += (*zIn++);                                                      \
19512   if( c>=0xD800 && c<0xE000 && TERM ){                                \
19513     int c2 = ((*zIn++)<<8);                                           \
19514     c2 += (*zIn++);                                                   \
19515     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
19516   }                                                                   \
19517 }
19518
19519 /*
19520 ** Translate a single UTF-8 character.  Return the unicode value.
19521 **
19522 ** During translation, assume that the byte that zTerm points
19523 ** is a 0x00.
19524 **
19525 ** Write a pointer to the next unread byte back into *pzNext.
19526 **
19527 ** Notes On Invalid UTF-8:
19528 **
19529 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
19530 **     be encoded as a multi-byte character.  Any multi-byte character that
19531 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
19532 **
19533 **  *  This routine never allows a UTF16 surrogate value to be encoded.
19534 **     If a multi-byte character attempts to encode a value between
19535 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
19536 **
19537 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
19538 **     byte of a character are interpreted as single-byte characters
19539 **     and rendered as themselves even though they are technically
19540 **     invalid characters.
19541 **
19542 **  *  This routine accepts an infinite number of different UTF8 encodings
19543 **     for unicode values 0x80 and greater.  It do not change over-length
19544 **     encodings to 0xfffd as some systems recommend.
19545 */
19546 #define READ_UTF8(zIn, zTerm, c)                           \
19547   c = *(zIn++);                                            \
19548   if( c>=0xc0 ){                                           \
19549     c = sqlite3Utf8Trans1[c-0xc0];                         \
19550     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
19551       c = (c<<6) + (0x3f & *(zIn++));                      \
19552     }                                                      \
19553     if( c<0x80                                             \
19554         || (c&0xFFFFF800)==0xD800                          \
19555         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
19556   }
19557 SQLITE_PRIVATE int sqlite3Utf8Read(
19558   const unsigned char *zIn,       /* First byte of UTF-8 character */
19559   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
19560 ){
19561   int c;
19562
19563   /* Same as READ_UTF8() above but without the zTerm parameter.
19564   ** For this routine, we assume the UTF8 string is always zero-terminated.
19565   */
19566   c = *(zIn++);
19567   if( c>=0xc0 ){
19568     c = sqlite3Utf8Trans1[c-0xc0];
19569     while( (*zIn & 0xc0)==0x80 ){
19570       c = (c<<6) + (0x3f & *(zIn++));
19571     }
19572     if( c<0x80
19573         || (c&0xFFFFF800)==0xD800
19574         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
19575   }
19576   *pzNext = zIn;
19577   return c;
19578 }
19579
19580
19581
19582
19583 /*
19584 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
19585 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
19586 */ 
19587 /* #define TRANSLATE_TRACE 1 */
19588
19589 #ifndef SQLITE_OMIT_UTF16
19590 /*
19591 ** This routine transforms the internal text encoding used by pMem to
19592 ** desiredEnc. It is an error if the string is already of the desired
19593 ** encoding, or if *pMem does not contain a string value.
19594 */
19595 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
19596   int len;                    /* Maximum length of output string in bytes */
19597   unsigned char *zOut;                  /* Output buffer */
19598   unsigned char *zIn;                   /* Input iterator */
19599   unsigned char *zTerm;                 /* End of input */
19600   unsigned char *z;                     /* Output iterator */
19601   unsigned int c;
19602
19603   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
19604   assert( pMem->flags&MEM_Str );
19605   assert( pMem->enc!=desiredEnc );
19606   assert( pMem->enc!=0 );
19607   assert( pMem->n>=0 );
19608
19609 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19610   {
19611     char zBuf[100];
19612     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19613     fprintf(stderr, "INPUT:  %s\n", zBuf);
19614   }
19615 #endif
19616
19617   /* If the translation is between UTF-16 little and big endian, then 
19618   ** all that is required is to swap the byte order. This case is handled
19619   ** differently from the others.
19620   */
19621   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
19622     u8 temp;
19623     int rc;
19624     rc = sqlite3VdbeMemMakeWriteable(pMem);
19625     if( rc!=SQLITE_OK ){
19626       assert( rc==SQLITE_NOMEM );
19627       return SQLITE_NOMEM;
19628     }
19629     zIn = (u8*)pMem->z;
19630     zTerm = &zIn[pMem->n&~1];
19631     while( zIn<zTerm ){
19632       temp = *zIn;
19633       *zIn = *(zIn+1);
19634       zIn++;
19635       *zIn++ = temp;
19636     }
19637     pMem->enc = desiredEnc;
19638     goto translate_out;
19639   }
19640
19641   /* Set len to the maximum number of bytes required in the output buffer. */
19642   if( desiredEnc==SQLITE_UTF8 ){
19643     /* When converting from UTF-16, the maximum growth results from
19644     ** translating a 2-byte character to a 4-byte UTF-8 character.
19645     ** A single byte is required for the output string
19646     ** nul-terminator.
19647     */
19648     pMem->n &= ~1;
19649     len = pMem->n * 2 + 1;
19650   }else{
19651     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
19652     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
19653     ** character. Two bytes are required in the output buffer for the
19654     ** nul-terminator.
19655     */
19656     len = pMem->n * 2 + 2;
19657   }
19658
19659   /* Set zIn to point at the start of the input buffer and zTerm to point 1
19660   ** byte past the end.
19661   **
19662   ** Variable zOut is set to point at the output buffer, space obtained
19663   ** from sqlite3_malloc().
19664   */
19665   zIn = (u8*)pMem->z;
19666   zTerm = &zIn[pMem->n];
19667   zOut = sqlite3DbMallocRaw(pMem->db, len);
19668   if( !zOut ){
19669     return SQLITE_NOMEM;
19670   }
19671   z = zOut;
19672
19673   if( pMem->enc==SQLITE_UTF8 ){
19674     if( desiredEnc==SQLITE_UTF16LE ){
19675       /* UTF-8 -> UTF-16 Little-endian */
19676       while( zIn<zTerm ){
19677         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19678         READ_UTF8(zIn, zTerm, c);
19679         WRITE_UTF16LE(z, c);
19680       }
19681     }else{
19682       assert( desiredEnc==SQLITE_UTF16BE );
19683       /* UTF-8 -> UTF-16 Big-endian */
19684       while( zIn<zTerm ){
19685         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
19686         READ_UTF8(zIn, zTerm, c);
19687         WRITE_UTF16BE(z, c);
19688       }
19689     }
19690     pMem->n = (int)(z - zOut);
19691     *z++ = 0;
19692   }else{
19693     assert( desiredEnc==SQLITE_UTF8 );
19694     if( pMem->enc==SQLITE_UTF16LE ){
19695       /* UTF-16 Little-endian -> UTF-8 */
19696       while( zIn<zTerm ){
19697         READ_UTF16LE(zIn, zIn<zTerm, c); 
19698         WRITE_UTF8(z, c);
19699       }
19700     }else{
19701       /* UTF-16 Big-endian -> UTF-8 */
19702       while( zIn<zTerm ){
19703         READ_UTF16BE(zIn, zIn<zTerm, c); 
19704         WRITE_UTF8(z, c);
19705       }
19706     }
19707     pMem->n = (int)(z - zOut);
19708   }
19709   *z = 0;
19710   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
19711
19712   sqlite3VdbeMemRelease(pMem);
19713   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
19714   pMem->enc = desiredEnc;
19715   pMem->flags |= (MEM_Term|MEM_Dyn);
19716   pMem->z = (char*)zOut;
19717   pMem->zMalloc = pMem->z;
19718
19719 translate_out:
19720 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
19721   {
19722     char zBuf[100];
19723     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
19724     fprintf(stderr, "OUTPUT: %s\n", zBuf);
19725   }
19726 #endif
19727   return SQLITE_OK;
19728 }
19729
19730 /*
19731 ** This routine checks for a byte-order mark at the beginning of the 
19732 ** UTF-16 string stored in *pMem. If one is present, it is removed and
19733 ** the encoding of the Mem adjusted. This routine does not do any
19734 ** byte-swapping, it just sets Mem.enc appropriately.
19735 **
19736 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
19737 ** changed by this function.
19738 */
19739 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
19740   int rc = SQLITE_OK;
19741   u8 bom = 0;
19742
19743   assert( pMem->n>=0 );
19744   if( pMem->n>1 ){
19745     u8 b1 = *(u8 *)pMem->z;
19746     u8 b2 = *(((u8 *)pMem->z) + 1);
19747     if( b1==0xFE && b2==0xFF ){
19748       bom = SQLITE_UTF16BE;
19749     }
19750     if( b1==0xFF && b2==0xFE ){
19751       bom = SQLITE_UTF16LE;
19752     }
19753   }
19754   
19755   if( bom ){
19756     rc = sqlite3VdbeMemMakeWriteable(pMem);
19757     if( rc==SQLITE_OK ){
19758       pMem->n -= 2;
19759       memmove(pMem->z, &pMem->z[2], pMem->n);
19760       pMem->z[pMem->n] = '\0';
19761       pMem->z[pMem->n+1] = '\0';
19762       pMem->flags |= MEM_Term;
19763       pMem->enc = bom;
19764     }
19765   }
19766   return rc;
19767 }
19768 #endif /* SQLITE_OMIT_UTF16 */
19769
19770 /*
19771 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
19772 ** return the number of unicode characters in pZ up to (but not including)
19773 ** the first 0x00 byte. If nByte is not less than zero, return the
19774 ** number of unicode characters in the first nByte of pZ (or up to 
19775 ** the first 0x00, whichever comes first).
19776 */
19777 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
19778   int r = 0;
19779   const u8 *z = (const u8*)zIn;
19780   const u8 *zTerm;
19781   if( nByte>=0 ){
19782     zTerm = &z[nByte];
19783   }else{
19784     zTerm = (const u8*)(-1);
19785   }
19786   assert( z<=zTerm );
19787   while( *z!=0 && z<zTerm ){
19788     SQLITE_SKIP_UTF8(z);
19789     r++;
19790   }
19791   return r;
19792 }
19793
19794 /* This test function is not currently used by the automated test-suite. 
19795 ** Hence it is only available in debug builds.
19796 */
19797 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19798 /*
19799 ** Translate UTF-8 to UTF-8.
19800 **
19801 ** This has the effect of making sure that the string is well-formed
19802 ** UTF-8.  Miscoded characters are removed.
19803 **
19804 ** The translation is done in-place (since it is impossible for the
19805 ** correct UTF-8 encoding to be longer than a malformed encoding).
19806 */
19807 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
19808   unsigned char *zOut = zIn;
19809   unsigned char *zStart = zIn;
19810   u32 c;
19811
19812   while( zIn[0] ){
19813     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
19814     if( c!=0xfffd ){
19815       WRITE_UTF8(zOut, c);
19816     }
19817   }
19818   *zOut = 0;
19819   return (int)(zOut - zStart);
19820 }
19821 #endif
19822
19823 #ifndef SQLITE_OMIT_UTF16
19824 /*
19825 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
19826 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
19827 ** be freed by the calling function.
19828 **
19829 ** NULL is returned if there is an allocation error.
19830 */
19831 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
19832   Mem m;
19833   memset(&m, 0, sizeof(m));
19834   m.db = db;
19835   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
19836   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
19837   if( db->mallocFailed ){
19838     sqlite3VdbeMemRelease(&m);
19839     m.z = 0;
19840   }
19841   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
19842   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
19843   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
19844   assert( m.z || db->mallocFailed );
19845   return m.z;
19846 }
19847
19848 /*
19849 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
19850 ** enc. A pointer to the new string is returned, and the value of *pnOut
19851 ** is set to the length of the returned string in bytes. The call should
19852 ** arrange to call sqlite3DbFree() on the returned pointer when it is
19853 ** no longer required.
19854 ** 
19855 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
19856 ** flag set.
19857 */
19858 #ifdef SQLITE_ENABLE_STAT2
19859 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
19860   Mem m;
19861   memset(&m, 0, sizeof(m));
19862   m.db = db;
19863   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
19864   if( sqlite3VdbeMemTranslate(&m, enc) ){
19865     assert( db->mallocFailed );
19866     return 0;
19867   }
19868   assert( m.z==m.zMalloc );
19869   *pnOut = m.n;
19870   return m.z;
19871 }
19872 #endif
19873
19874 /*
19875 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
19876 ** Return the number of bytes in the first nChar unicode characters
19877 ** in pZ.  nChar must be non-negative.
19878 */
19879 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
19880   int c;
19881   unsigned char const *z = zIn;
19882   int n = 0;
19883   
19884   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
19885     while( n<nChar ){
19886       READ_UTF16BE(z, 1, c);
19887       n++;
19888     }
19889   }else{
19890     while( n<nChar ){
19891       READ_UTF16LE(z, 1, c);
19892       n++;
19893     }
19894   }
19895   return (int)(z-(unsigned char const *)zIn);
19896 }
19897
19898 #if defined(SQLITE_TEST)
19899 /*
19900 ** This routine is called from the TCL test function "translate_selftest".
19901 ** It checks that the primitives for serializing and deserializing
19902 ** characters in each encoding are inverses of each other.
19903 */
19904 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
19905   unsigned int i, t;
19906   unsigned char zBuf[20];
19907   unsigned char *z;
19908   int n;
19909   unsigned int c;
19910
19911   for(i=0; i<0x00110000; i++){
19912     z = zBuf;
19913     WRITE_UTF8(z, i);
19914     n = (int)(z-zBuf);
19915     assert( n>0 && n<=4 );
19916     z[0] = 0;
19917     z = zBuf;
19918     c = sqlite3Utf8Read(z, (const u8**)&z);
19919     t = i;
19920     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
19921     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
19922     assert( c==t );
19923     assert( (z-zBuf)==n );
19924   }
19925   for(i=0; i<0x00110000; i++){
19926     if( i>=0xD800 && i<0xE000 ) continue;
19927     z = zBuf;
19928     WRITE_UTF16LE(z, i);
19929     n = (int)(z-zBuf);
19930     assert( n>0 && n<=4 );
19931     z[0] = 0;
19932     z = zBuf;
19933     READ_UTF16LE(z, 1, c);
19934     assert( c==i );
19935     assert( (z-zBuf)==n );
19936   }
19937   for(i=0; i<0x00110000; i++){
19938     if( i>=0xD800 && i<0xE000 ) continue;
19939     z = zBuf;
19940     WRITE_UTF16BE(z, i);
19941     n = (int)(z-zBuf);
19942     assert( n>0 && n<=4 );
19943     z[0] = 0;
19944     z = zBuf;
19945     READ_UTF16BE(z, 1, c);
19946     assert( c==i );
19947     assert( (z-zBuf)==n );
19948   }
19949 }
19950 #endif /* SQLITE_TEST */
19951 #endif /* SQLITE_OMIT_UTF16 */
19952
19953 /************** End of utf.c *************************************************/
19954 /************** Begin file util.c ********************************************/
19955 /*
19956 ** 2001 September 15
19957 **
19958 ** The author disclaims copyright to this source code.  In place of
19959 ** a legal notice, here is a blessing:
19960 **
19961 **    May you do good and not evil.
19962 **    May you find forgiveness for yourself and forgive others.
19963 **    May you share freely, never taking more than you give.
19964 **
19965 *************************************************************************
19966 ** Utility functions used throughout sqlite.
19967 **
19968 ** This file contains functions for allocating memory, comparing
19969 ** strings, and stuff like that.
19970 **
19971 */
19972 #ifdef SQLITE_HAVE_ISNAN
19973 # include <math.h>
19974 #endif
19975
19976 /*
19977 ** Routine needed to support the testcase() macro.
19978 */
19979 #ifdef SQLITE_COVERAGE_TEST
19980 SQLITE_PRIVATE void sqlite3Coverage(int x){
19981   static int dummy = 0;
19982   dummy += x;
19983 }
19984 #endif
19985
19986 #ifndef SQLITE_OMIT_FLOATING_POINT
19987 /*
19988 ** Return true if the floating point value is Not a Number (NaN).
19989 **
19990 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
19991 ** Otherwise, we have our own implementation that works on most systems.
19992 */
19993 SQLITE_PRIVATE int sqlite3IsNaN(double x){
19994   int rc;   /* The value return */
19995 #if !defined(SQLITE_HAVE_ISNAN)
19996   /*
19997   ** Systems that support the isnan() library function should probably
19998   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
19999   ** found that many systems do not have a working isnan() function so
20000   ** this implementation is provided as an alternative.
20001   **
20002   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20003   ** On the other hand, the use of -ffast-math comes with the following
20004   ** warning:
20005   **
20006   **      This option [-ffast-math] should never be turned on by any
20007   **      -O option since it can result in incorrect output for programs
20008   **      which depend on an exact implementation of IEEE or ISO 
20009   **      rules/specifications for math functions.
20010   **
20011   ** Under MSVC, this NaN test may fail if compiled with a floating-
20012   ** point precision mode other than /fp:precise.  From the MSDN 
20013   ** documentation:
20014   **
20015   **      The compiler [with /fp:precise] will properly handle comparisons 
20016   **      involving NaN. For example, x != x evaluates to true if x is NaN 
20017   **      ...
20018   */
20019 #ifdef __FAST_MATH__
20020 # error SQLite will not work correctly with the -ffast-math option of GCC.
20021 #endif
20022   volatile double y = x;
20023   volatile double z = y;
20024   rc = (y!=z);
20025 #else  /* if defined(SQLITE_HAVE_ISNAN) */
20026   rc = isnan(x);
20027 #endif /* SQLITE_HAVE_ISNAN */
20028   testcase( rc );
20029   return rc;
20030 }
20031 #endif /* SQLITE_OMIT_FLOATING_POINT */
20032
20033 /*
20034 ** Compute a string length that is limited to what can be stored in
20035 ** lower 30 bits of a 32-bit signed integer.
20036 **
20037 ** The value returned will never be negative.  Nor will it ever be greater
20038 ** than the actual length of the string.  For very long strings (greater
20039 ** than 1GiB) the value returned might be less than the true string length.
20040 */
20041 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
20042   const char *z2 = z;
20043   if( z==0 ) return 0;
20044   while( *z2 ){ z2++; }
20045   return 0x3fffffff & (int)(z2 - z);
20046 }
20047
20048 /*
20049 ** Set the most recent error code and error string for the sqlite
20050 ** handle "db". The error code is set to "err_code".
20051 **
20052 ** If it is not NULL, string zFormat specifies the format of the
20053 ** error string in the style of the printf functions: The following
20054 ** format characters are allowed:
20055 **
20056 **      %s      Insert a string
20057 **      %z      A string that should be freed after use
20058 **      %d      Insert an integer
20059 **      %T      Insert a token
20060 **      %S      Insert the first element of a SrcList
20061 **
20062 ** zFormat and any string tokens that follow it are assumed to be
20063 ** encoded in UTF-8.
20064 **
20065 ** To clear the most recent error for sqlite handle "db", sqlite3Error
20066 ** should be called with err_code set to SQLITE_OK and zFormat set
20067 ** to NULL.
20068 */
20069 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
20070   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
20071     db->errCode = err_code;
20072     if( zFormat ){
20073       char *z;
20074       va_list ap;
20075       va_start(ap, zFormat);
20076       z = sqlite3VMPrintf(db, zFormat, ap);
20077       va_end(ap);
20078       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
20079     }else{
20080       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
20081     }
20082   }
20083 }
20084
20085 /*
20086 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
20087 ** The following formatting characters are allowed:
20088 **
20089 **      %s      Insert a string
20090 **      %z      A string that should be freed after use
20091 **      %d      Insert an integer
20092 **      %T      Insert a token
20093 **      %S      Insert the first element of a SrcList
20094 **
20095 ** This function should be used to report any error that occurs whilst
20096 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
20097 ** last thing the sqlite3_prepare() function does is copy the error
20098 ** stored by this function into the database handle using sqlite3Error().
20099 ** Function sqlite3Error() should be used during statement execution
20100 ** (sqlite3_step() etc.).
20101 */
20102 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20103   char *zMsg;
20104   va_list ap;
20105   sqlite3 *db = pParse->db;
20106   va_start(ap, zFormat);
20107   zMsg = sqlite3VMPrintf(db, zFormat, ap);
20108   va_end(ap);
20109   if( db->suppressErr ){
20110     sqlite3DbFree(db, zMsg);
20111   }else{
20112     pParse->nErr++;
20113     sqlite3DbFree(db, pParse->zErrMsg);
20114     pParse->zErrMsg = zMsg;
20115     pParse->rc = SQLITE_ERROR;
20116   }
20117 }
20118
20119 /*
20120 ** Convert an SQL-style quoted string into a normal string by removing
20121 ** the quote characters.  The conversion is done in-place.  If the
20122 ** input does not begin with a quote character, then this routine
20123 ** is a no-op.
20124 **
20125 ** The input string must be zero-terminated.  A new zero-terminator
20126 ** is added to the dequoted string.
20127 **
20128 ** The return value is -1 if no dequoting occurs or the length of the
20129 ** dequoted string, exclusive of the zero terminator, if dequoting does
20130 ** occur.
20131 **
20132 ** 2002-Feb-14: This routine is extended to remove MS-Access style
20133 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
20134 ** "a-b-c".
20135 */
20136 SQLITE_PRIVATE int sqlite3Dequote(char *z){
20137   char quote;
20138   int i, j;
20139   if( z==0 ) return -1;
20140   quote = z[0];
20141   switch( quote ){
20142     case '\'':  break;
20143     case '"':   break;
20144     case '`':   break;                /* For MySQL compatibility */
20145     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
20146     default:    return -1;
20147   }
20148   for(i=1, j=0; ALWAYS(z[i]); i++){
20149     if( z[i]==quote ){
20150       if( z[i+1]==quote ){
20151         z[j++] = quote;
20152         i++;
20153       }else{
20154         break;
20155       }
20156     }else{
20157       z[j++] = z[i];
20158     }
20159   }
20160   z[j] = 0;
20161   return j;
20162 }
20163
20164 /* Convenient short-hand */
20165 #define UpperToLower sqlite3UpperToLower
20166
20167 /*
20168 ** Some systems have stricmp().  Others have strcasecmp().  Because
20169 ** there is no consistency, we will define our own.
20170 **
20171 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20172 ** applications and extensions to compare the contents of two buffers
20173 ** containing UTF-8 strings in a case-independent fashion, using the same
20174 ** definition of case independence that SQLite uses internally when
20175 ** comparing identifiers.
20176 */
20177 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20178   register unsigned char *a, *b;
20179   a = (unsigned char *)zLeft;
20180   b = (unsigned char *)zRight;
20181   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20182   return UpperToLower[*a] - UpperToLower[*b];
20183 }
20184 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20185   register unsigned char *a, *b;
20186   a = (unsigned char *)zLeft;
20187   b = (unsigned char *)zRight;
20188   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20189   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20190 }
20191
20192 /*
20193 ** The string z[] is an text representation of a real number.
20194 ** Convert this string to a double and write it into *pResult.
20195 **
20196 ** The string z[] is length bytes in length (bytes, not characters) and
20197 ** uses the encoding enc.  The string is not necessarily zero-terminated.
20198 **
20199 ** Return TRUE if the result is a valid real number (or integer) and FALSE
20200 ** if the string is empty or contains extraneous text.  Valid numbers
20201 ** are in one of these formats:
20202 **
20203 **    [+-]digits[E[+-]digits]
20204 **    [+-]digits.[digits][E[+-]digits]
20205 **    [+-].digits[E[+-]digits]
20206 **
20207 ** Leading and trailing whitespace is ignored for the purpose of determining
20208 ** validity.
20209 **
20210 ** If some prefix of the input string is a valid number, this routine
20211 ** returns FALSE but it still converts the prefix and writes the result
20212 ** into *pResult.
20213 */
20214 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20215 #ifndef SQLITE_OMIT_FLOATING_POINT
20216   int incr = (enc==SQLITE_UTF8?1:2);
20217   const char *zEnd = z + length;
20218   /* sign * significand * (10 ^ (esign * exponent)) */
20219   int sign = 1;    /* sign of significand */
20220   i64 s = 0;       /* significand */
20221   int d = 0;       /* adjust exponent for shifting decimal point */
20222   int esign = 1;   /* sign of exponent */
20223   int e = 0;       /* exponent */
20224   int eValid = 1;  /* True exponent is either not used or is well-formed */
20225   double result;
20226   int nDigits = 0;
20227
20228   *pResult = 0.0;   /* Default return value, in case of an error */
20229
20230   if( enc==SQLITE_UTF16BE ) z++;
20231
20232   /* skip leading spaces */
20233   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20234   if( z>=zEnd ) return 0;
20235
20236   /* get sign of significand */
20237   if( *z=='-' ){
20238     sign = -1;
20239     z+=incr;
20240   }else if( *z=='+' ){
20241     z+=incr;
20242   }
20243
20244   /* skip leading zeroes */
20245   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20246
20247   /* copy max significant digits to significand */
20248   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20249     s = s*10 + (*z - '0');
20250     z+=incr, nDigits++;
20251   }
20252
20253   /* skip non-significant significand digits
20254   ** (increase exponent by d to shift decimal left) */
20255   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20256   if( z>=zEnd ) goto do_atof_calc;
20257
20258   /* if decimal point is present */
20259   if( *z=='.' ){
20260     z+=incr;
20261     /* copy digits from after decimal to significand
20262     ** (decrease exponent by d to shift decimal right) */
20263     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20264       s = s*10 + (*z - '0');
20265       z+=incr, nDigits++, d--;
20266     }
20267     /* skip non-significant digits */
20268     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20269   }
20270   if( z>=zEnd ) goto do_atof_calc;
20271
20272   /* if exponent is present */
20273   if( *z=='e' || *z=='E' ){
20274     z+=incr;
20275     eValid = 0;
20276     if( z>=zEnd ) goto do_atof_calc;
20277     /* get sign of exponent */
20278     if( *z=='-' ){
20279       esign = -1;
20280       z+=incr;
20281     }else if( *z=='+' ){
20282       z+=incr;
20283     }
20284     /* copy digits to exponent */
20285     while( z<zEnd && sqlite3Isdigit(*z) ){
20286       e = e*10 + (*z - '0');
20287       z+=incr;
20288       eValid = 1;
20289     }
20290   }
20291
20292   /* skip trailing spaces */
20293   if( nDigits && eValid ){
20294     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20295   }
20296
20297 do_atof_calc:
20298   /* adjust exponent by d, and update sign */
20299   e = (e*esign) + d;
20300   if( e<0 ) {
20301     esign = -1;
20302     e *= -1;
20303   } else {
20304     esign = 1;
20305   }
20306
20307   /* if 0 significand */
20308   if( !s ) {
20309     /* In the IEEE 754 standard, zero is signed.
20310     ** Add the sign if we've seen at least one digit */
20311     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20312   } else {
20313     /* attempt to reduce exponent */
20314     if( esign>0 ){
20315       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20316     }else{
20317       while( !(s%10) && e>0 ) e--,s/=10;
20318     }
20319
20320     /* adjust the sign of significand */
20321     s = sign<0 ? -s : s;
20322
20323     /* if exponent, scale significand as appropriate
20324     ** and store in result. */
20325     if( e ){
20326       double scale = 1.0;
20327       /* attempt to handle extremely small/large numbers better */
20328       if( e>307 && e<342 ){
20329         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
20330         if( esign<0 ){
20331           result = s / scale;
20332           result /= 1.0e+308;
20333         }else{
20334           result = s * scale;
20335           result *= 1.0e+308;
20336         }
20337       }else{
20338         /* 1.0e+22 is the largest power of 10 than can be 
20339         ** represented exactly. */
20340         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
20341         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
20342         if( esign<0 ){
20343           result = s / scale;
20344         }else{
20345           result = s * scale;
20346         }
20347       }
20348     } else {
20349       result = (double)s;
20350     }
20351   }
20352
20353   /* store the result */
20354   *pResult = result;
20355
20356   /* return true if number and no extra non-whitespace chracters after */
20357   return z>=zEnd && nDigits>0 && eValid;
20358 #else
20359   return !sqlite3Atoi64(z, pResult, length, enc);
20360 #endif /* SQLITE_OMIT_FLOATING_POINT */
20361 }
20362
20363 /*
20364 ** Compare the 19-character string zNum against the text representation
20365 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
20366 ** if zNum is less than, equal to, or greater than the string.
20367 ** Note that zNum must contain exactly 19 characters.
20368 **
20369 ** Unlike memcmp() this routine is guaranteed to return the difference
20370 ** in the values of the last digit if the only difference is in the
20371 ** last digit.  So, for example,
20372 **
20373 **      compare2pow63("9223372036854775800", 1)
20374 **
20375 ** will return -8.
20376 */
20377 static int compare2pow63(const char *zNum, int incr){
20378   int c = 0;
20379   int i;
20380                     /* 012345678901234567 */
20381   const char *pow63 = "922337203685477580";
20382   for(i=0; c==0 && i<18; i++){
20383     c = (zNum[i*incr]-pow63[i])*10;
20384   }
20385   if( c==0 ){
20386     c = zNum[18*incr] - '8';
20387     testcase( c==(-1) );
20388     testcase( c==0 );
20389     testcase( c==(+1) );
20390   }
20391   return c;
20392 }
20393
20394
20395 /*
20396 ** Convert zNum to a 64-bit signed integer and write
20397 ** the value of the integer into *pNum.
20398 ** If zNum is exactly 9223372036854665808, return 2.
20399 ** This is a special case as the context will determine
20400 ** if it is too big (used as a negative).
20401 ** If zNum is not an integer or is an integer that 
20402 ** is too large to be expressed with 64 bits,
20403 ** then return 1.  Otherwise return 0.
20404 **
20405 ** length is the number of bytes in the string (bytes, not characters).
20406 ** The string is not necessarily zero-terminated.  The encoding is
20407 ** given by enc.
20408 */
20409 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
20410   int incr = (enc==SQLITE_UTF8?1:2);
20411   i64 v = 0;
20412   int neg = 0; /* assume positive */
20413   int i;
20414   int c = 0;
20415   const char *zStart;
20416   const char *zEnd = zNum + length;
20417   if( enc==SQLITE_UTF16BE ) zNum++;
20418   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
20419   if( zNum>=zEnd ) goto do_atoi_calc;
20420   if( *zNum=='-' ){
20421     neg = 1;
20422     zNum+=incr;
20423   }else if( *zNum=='+' ){
20424     zNum+=incr;
20425   }
20426 do_atoi_calc:
20427   zStart = zNum;
20428   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
20429   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
20430     v = v*10 + c - '0';
20431   }
20432   *pNum = neg ? -v : v;
20433   testcase( i==18 );
20434   testcase( i==19 );
20435   testcase( i==20 );
20436   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
20437     /* zNum is empty or contains non-numeric text or is longer
20438     ** than 19 digits (thus guaranteeing that it is too large) */
20439     return 1;
20440   }else if( i<19*incr ){
20441     /* Less than 19 digits, so we know that it fits in 64 bits */
20442     return 0;
20443   }else{
20444     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
20445     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
20446     ** is 2^63. Return 1 if to large */
20447     c=compare2pow63(zNum, incr);
20448     if( c==0 && neg==0 ) return 2; /* too big, exactly 9223372036854665808 */
20449     return c<neg ? 0 : 1;
20450   }
20451 }
20452
20453 /*
20454 ** If zNum represents an integer that will fit in 32-bits, then set
20455 ** *pValue to that integer and return true.  Otherwise return false.
20456 **
20457 ** Any non-numeric characters that following zNum are ignored.
20458 ** This is different from sqlite3Atoi64() which requires the
20459 ** input number to be zero-terminated.
20460 */
20461 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
20462   sqlite_int64 v = 0;
20463   int i, c;
20464   int neg = 0;
20465   if( zNum[0]=='-' ){
20466     neg = 1;
20467     zNum++;
20468   }else if( zNum[0]=='+' ){
20469     zNum++;
20470   }
20471   while( zNum[0]=='0' ) zNum++;
20472   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
20473     v = v*10 + c;
20474   }
20475
20476   /* The longest decimal representation of a 32 bit integer is 10 digits:
20477   **
20478   **             1234567890
20479   **     2^31 -> 2147483648
20480   */
20481   testcase( i==10 );
20482   if( i>10 ){
20483     return 0;
20484   }
20485   testcase( v-neg==2147483647 );
20486   if( v-neg>2147483647 ){
20487     return 0;
20488   }
20489   if( neg ){
20490     v = -v;
20491   }
20492   *pValue = (int)v;
20493   return 1;
20494 }
20495
20496 /*
20497 ** Return a 32-bit integer value extracted from a string.  If the
20498 ** string is not an integer, just return 0.
20499 */
20500 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
20501   int x = 0;
20502   if( z ) sqlite3GetInt32(z, &x);
20503   return x;
20504 }
20505
20506 /*
20507 ** The variable-length integer encoding is as follows:
20508 **
20509 ** KEY:
20510 **         A = 0xxxxxxx    7 bits of data and one flag bit
20511 **         B = 1xxxxxxx    7 bits of data and one flag bit
20512 **         C = xxxxxxxx    8 bits of data
20513 **
20514 **  7 bits - A
20515 ** 14 bits - BA
20516 ** 21 bits - BBA
20517 ** 28 bits - BBBA
20518 ** 35 bits - BBBBA
20519 ** 42 bits - BBBBBA
20520 ** 49 bits - BBBBBBA
20521 ** 56 bits - BBBBBBBA
20522 ** 64 bits - BBBBBBBBC
20523 */
20524
20525 /*
20526 ** Write a 64-bit variable-length integer to memory starting at p[0].
20527 ** The length of data write will be between 1 and 9 bytes.  The number
20528 ** of bytes written is returned.
20529 **
20530 ** A variable-length integer consists of the lower 7 bits of each byte
20531 ** for all bytes that have the 8th bit set and one byte with the 8th
20532 ** bit clear.  Except, if we get to the 9th byte, it stores the full
20533 ** 8 bits and is the last byte.
20534 */
20535 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
20536   int i, j, n;
20537   u8 buf[10];
20538   if( v & (((u64)0xff000000)<<32) ){
20539     p[8] = (u8)v;
20540     v >>= 8;
20541     for(i=7; i>=0; i--){
20542       p[i] = (u8)((v & 0x7f) | 0x80);
20543       v >>= 7;
20544     }
20545     return 9;
20546   }    
20547   n = 0;
20548   do{
20549     buf[n++] = (u8)((v & 0x7f) | 0x80);
20550     v >>= 7;
20551   }while( v!=0 );
20552   buf[0] &= 0x7f;
20553   assert( n<=9 );
20554   for(i=0, j=n-1; j>=0; j--, i++){
20555     p[i] = buf[j];
20556   }
20557   return n;
20558 }
20559
20560 /*
20561 ** This routine is a faster version of sqlite3PutVarint() that only
20562 ** works for 32-bit positive integers and which is optimized for
20563 ** the common case of small integers.  A MACRO version, putVarint32,
20564 ** is provided which inlines the single-byte case.  All code should use
20565 ** the MACRO version as this function assumes the single-byte case has
20566 ** already been handled.
20567 */
20568 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
20569 #ifndef putVarint32
20570   if( (v & ~0x7f)==0 ){
20571     p[0] = v;
20572     return 1;
20573   }
20574 #endif
20575   if( (v & ~0x3fff)==0 ){
20576     p[0] = (u8)((v>>7) | 0x80);
20577     p[1] = (u8)(v & 0x7f);
20578     return 2;
20579   }
20580   return sqlite3PutVarint(p, v);
20581 }
20582
20583 /*
20584 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
20585 ** are defined here rather than simply putting the constant expressions
20586 ** inline in order to work around bugs in the RVT compiler.
20587 **
20588 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
20589 **
20590 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
20591 */
20592 #define SLOT_2_0     0x001fc07f
20593 #define SLOT_4_2_0   0xf01fc07f
20594
20595
20596 /*
20597 ** Read a 64-bit variable-length integer from memory starting at p[0].
20598 ** Return the number of bytes read.  The value is stored in *v.
20599 */
20600 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
20601   u32 a,b,s;
20602
20603   a = *p;
20604   /* a: p0 (unmasked) */
20605   if (!(a&0x80))
20606   {
20607     *v = a;
20608     return 1;
20609   }
20610
20611   p++;
20612   b = *p;
20613   /* b: p1 (unmasked) */
20614   if (!(b&0x80))
20615   {
20616     a &= 0x7f;
20617     a = a<<7;
20618     a |= b;
20619     *v = a;
20620     return 2;
20621   }
20622
20623   /* Verify that constants are precomputed correctly */
20624   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
20625   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
20626
20627   p++;
20628   a = a<<14;
20629   a |= *p;
20630   /* a: p0<<14 | p2 (unmasked) */
20631   if (!(a&0x80))
20632   {
20633     a &= SLOT_2_0;
20634     b &= 0x7f;
20635     b = b<<7;
20636     a |= b;
20637     *v = a;
20638     return 3;
20639   }
20640
20641   /* CSE1 from below */
20642   a &= SLOT_2_0;
20643   p++;
20644   b = b<<14;
20645   b |= *p;
20646   /* b: p1<<14 | p3 (unmasked) */
20647   if (!(b&0x80))
20648   {
20649     b &= SLOT_2_0;
20650     /* moved CSE1 up */
20651     /* a &= (0x7f<<14)|(0x7f); */
20652     a = a<<7;
20653     a |= b;
20654     *v = a;
20655     return 4;
20656   }
20657
20658   /* a: p0<<14 | p2 (masked) */
20659   /* b: p1<<14 | p3 (unmasked) */
20660   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20661   /* moved CSE1 up */
20662   /* a &= (0x7f<<14)|(0x7f); */
20663   b &= SLOT_2_0;
20664   s = a;
20665   /* s: p0<<14 | p2 (masked) */
20666
20667   p++;
20668   a = a<<14;
20669   a |= *p;
20670   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20671   if (!(a&0x80))
20672   {
20673     /* we can skip these cause they were (effectively) done above in calc'ing s */
20674     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20675     /* b &= (0x7f<<14)|(0x7f); */
20676     b = b<<7;
20677     a |= b;
20678     s = s>>18;
20679     *v = ((u64)s)<<32 | a;
20680     return 5;
20681   }
20682
20683   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20684   s = s<<7;
20685   s |= b;
20686   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
20687
20688   p++;
20689   b = b<<14;
20690   b |= *p;
20691   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
20692   if (!(b&0x80))
20693   {
20694     /* we can skip this cause it was (effectively) done above in calc'ing s */
20695     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
20696     a &= SLOT_2_0;
20697     a = a<<7;
20698     a |= b;
20699     s = s>>18;
20700     *v = ((u64)s)<<32 | a;
20701     return 6;
20702   }
20703
20704   p++;
20705   a = a<<14;
20706   a |= *p;
20707   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
20708   if (!(a&0x80))
20709   {
20710     a &= SLOT_4_2_0;
20711     b &= SLOT_2_0;
20712     b = b<<7;
20713     a |= b;
20714     s = s>>11;
20715     *v = ((u64)s)<<32 | a;
20716     return 7;
20717   }
20718
20719   /* CSE2 from below */
20720   a &= SLOT_2_0;
20721   p++;
20722   b = b<<14;
20723   b |= *p;
20724   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
20725   if (!(b&0x80))
20726   {
20727     b &= SLOT_4_2_0;
20728     /* moved CSE2 up */
20729     /* a &= (0x7f<<14)|(0x7f); */
20730     a = a<<7;
20731     a |= b;
20732     s = s>>4;
20733     *v = ((u64)s)<<32 | a;
20734     return 8;
20735   }
20736
20737   p++;
20738   a = a<<15;
20739   a |= *p;
20740   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
20741
20742   /* moved CSE2 up */
20743   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
20744   b &= SLOT_2_0;
20745   b = b<<8;
20746   a |= b;
20747
20748   s = s<<4;
20749   b = p[-4];
20750   b &= 0x7f;
20751   b = b>>3;
20752   s |= b;
20753
20754   *v = ((u64)s)<<32 | a;
20755
20756   return 9;
20757 }
20758
20759 /*
20760 ** Read a 32-bit variable-length integer from memory starting at p[0].
20761 ** Return the number of bytes read.  The value is stored in *v.
20762 **
20763 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
20764 ** integer, then set *v to 0xffffffff.
20765 **
20766 ** A MACRO version, getVarint32, is provided which inlines the 
20767 ** single-byte case.  All code should use the MACRO version as 
20768 ** this function assumes the single-byte case has already been handled.
20769 */
20770 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
20771   u32 a,b;
20772
20773   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
20774   ** by the getVarin32() macro */
20775   a = *p;
20776   /* a: p0 (unmasked) */
20777 #ifndef getVarint32
20778   if (!(a&0x80))
20779   {
20780     /* Values between 0 and 127 */
20781     *v = a;
20782     return 1;
20783   }
20784 #endif
20785
20786   /* The 2-byte case */
20787   p++;
20788   b = *p;
20789   /* b: p1 (unmasked) */
20790   if (!(b&0x80))
20791   {
20792     /* Values between 128 and 16383 */
20793     a &= 0x7f;
20794     a = a<<7;
20795     *v = a | b;
20796     return 2;
20797   }
20798
20799   /* The 3-byte case */
20800   p++;
20801   a = a<<14;
20802   a |= *p;
20803   /* a: p0<<14 | p2 (unmasked) */
20804   if (!(a&0x80))
20805   {
20806     /* Values between 16384 and 2097151 */
20807     a &= (0x7f<<14)|(0x7f);
20808     b &= 0x7f;
20809     b = b<<7;
20810     *v = a | b;
20811     return 3;
20812   }
20813
20814   /* A 32-bit varint is used to store size information in btrees.
20815   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
20816   ** A 3-byte varint is sufficient, for example, to record the size
20817   ** of a 1048569-byte BLOB or string.
20818   **
20819   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
20820   ** rare larger cases can be handled by the slower 64-bit varint
20821   ** routine.
20822   */
20823 #if 1
20824   {
20825     u64 v64;
20826     u8 n;
20827
20828     p -= 2;
20829     n = sqlite3GetVarint(p, &v64);
20830     assert( n>3 && n<=9 );
20831     if( (v64 & SQLITE_MAX_U32)!=v64 ){
20832       *v = 0xffffffff;
20833     }else{
20834       *v = (u32)v64;
20835     }
20836     return n;
20837   }
20838
20839 #else
20840   /* For following code (kept for historical record only) shows an
20841   ** unrolling for the 3- and 4-byte varint cases.  This code is
20842   ** slightly faster, but it is also larger and much harder to test.
20843   */
20844   p++;
20845   b = b<<14;
20846   b |= *p;
20847   /* b: p1<<14 | p3 (unmasked) */
20848   if (!(b&0x80))
20849   {
20850     /* Values between 2097152 and 268435455 */
20851     b &= (0x7f<<14)|(0x7f);
20852     a &= (0x7f<<14)|(0x7f);
20853     a = a<<7;
20854     *v = a | b;
20855     return 4;
20856   }
20857
20858   p++;
20859   a = a<<14;
20860   a |= *p;
20861   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
20862   if (!(a&0x80))
20863   {
20864     /* Values  between 268435456 and 34359738367 */
20865     a &= SLOT_4_2_0;
20866     b &= SLOT_4_2_0;
20867     b = b<<7;
20868     *v = a | b;
20869     return 5;
20870   }
20871
20872   /* We can only reach this point when reading a corrupt database
20873   ** file.  In that case we are not in any hurry.  Use the (relatively
20874   ** slow) general-purpose sqlite3GetVarint() routine to extract the
20875   ** value. */
20876   {
20877     u64 v64;
20878     u8 n;
20879
20880     p -= 4;
20881     n = sqlite3GetVarint(p, &v64);
20882     assert( n>5 && n<=9 );
20883     *v = (u32)v64;
20884     return n;
20885   }
20886 #endif
20887 }
20888
20889 /*
20890 ** Return the number of bytes that will be needed to store the given
20891 ** 64-bit integer.
20892 */
20893 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
20894   int i = 0;
20895   do{
20896     i++;
20897     v >>= 7;
20898   }while( v!=0 && ALWAYS(i<9) );
20899   return i;
20900 }
20901
20902
20903 /*
20904 ** Read or write a four-byte big-endian integer value.
20905 */
20906 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
20907   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
20908 }
20909 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
20910   p[0] = (u8)(v>>24);
20911   p[1] = (u8)(v>>16);
20912   p[2] = (u8)(v>>8);
20913   p[3] = (u8)v;
20914 }
20915
20916
20917
20918 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20919 /*
20920 ** Translate a single byte of Hex into an integer.
20921 ** This routine only works if h really is a valid hexadecimal
20922 ** character:  0..9a..fA..F
20923 */
20924 static u8 hexToInt(int h){
20925   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
20926 #ifdef SQLITE_ASCII
20927   h += 9*(1&(h>>6));
20928 #endif
20929 #ifdef SQLITE_EBCDIC
20930   h += 9*(1&~(h>>4));
20931 #endif
20932   return (u8)(h & 0xf);
20933 }
20934 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20935
20936 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
20937 /*
20938 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
20939 ** value.  Return a pointer to its binary value.  Space to hold the
20940 ** binary value has been obtained from malloc and must be freed by
20941 ** the calling routine.
20942 */
20943 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
20944   char *zBlob;
20945   int i;
20946
20947   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
20948   n--;
20949   if( zBlob ){
20950     for(i=0; i<n; i+=2){
20951       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
20952     }
20953     zBlob[i/2] = 0;
20954   }
20955   return zBlob;
20956 }
20957 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
20958
20959 /*
20960 ** Log an error that is an API call on a connection pointer that should
20961 ** not have been used.  The "type" of connection pointer is given as the
20962 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
20963 */
20964 static void logBadConnection(const char *zType){
20965   sqlite3_log(SQLITE_MISUSE, 
20966      "API call with %s database connection pointer",
20967      zType
20968   );
20969 }
20970
20971 /*
20972 ** Check to make sure we have a valid db pointer.  This test is not
20973 ** foolproof but it does provide some measure of protection against
20974 ** misuse of the interface such as passing in db pointers that are
20975 ** NULL or which have been previously closed.  If this routine returns
20976 ** 1 it means that the db pointer is valid and 0 if it should not be
20977 ** dereferenced for any reason.  The calling function should invoke
20978 ** SQLITE_MISUSE immediately.
20979 **
20980 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
20981 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
20982 ** open properly and is not fit for general use but which can be
20983 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
20984 */
20985 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
20986   u32 magic;
20987   if( db==0 ){
20988     logBadConnection("NULL");
20989     return 0;
20990   }
20991   magic = db->magic;
20992   if( magic!=SQLITE_MAGIC_OPEN ){
20993     if( sqlite3SafetyCheckSickOrOk(db) ){
20994       testcase( sqlite3GlobalConfig.xLog!=0 );
20995       logBadConnection("unopened");
20996     }
20997     return 0;
20998   }else{
20999     return 1;
21000   }
21001 }
21002 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
21003   u32 magic;
21004   magic = db->magic;
21005   if( magic!=SQLITE_MAGIC_SICK &&
21006       magic!=SQLITE_MAGIC_OPEN &&
21007       magic!=SQLITE_MAGIC_BUSY ){
21008     testcase( sqlite3GlobalConfig.xLog!=0 );
21009     logBadConnection("invalid");
21010     return 0;
21011   }else{
21012     return 1;
21013   }
21014 }
21015
21016 /************** End of util.c ************************************************/
21017 /************** Begin file hash.c ********************************************/
21018 /*
21019 ** 2001 September 22
21020 **
21021 ** The author disclaims copyright to this source code.  In place of
21022 ** a legal notice, here is a blessing:
21023 **
21024 **    May you do good and not evil.
21025 **    May you find forgiveness for yourself and forgive others.
21026 **    May you share freely, never taking more than you give.
21027 **
21028 *************************************************************************
21029 ** This is the implementation of generic hash-tables
21030 ** used in SQLite.
21031 */
21032
21033 /* Turn bulk memory into a hash table object by initializing the
21034 ** fields of the Hash structure.
21035 **
21036 ** "pNew" is a pointer to the hash table that is to be initialized.
21037 */
21038 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
21039   assert( pNew!=0 );
21040   pNew->first = 0;
21041   pNew->count = 0;
21042   pNew->htsize = 0;
21043   pNew->ht = 0;
21044 }
21045
21046 /* Remove all entries from a hash table.  Reclaim all memory.
21047 ** Call this routine to delete a hash table or to reset a hash table
21048 ** to the empty state.
21049 */
21050 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
21051   HashElem *elem;         /* For looping over all elements of the table */
21052
21053   assert( pH!=0 );
21054   elem = pH->first;
21055   pH->first = 0;
21056   sqlite3_free(pH->ht);
21057   pH->ht = 0;
21058   pH->htsize = 0;
21059   while( elem ){
21060     HashElem *next_elem = elem->next;
21061     sqlite3_free(elem);
21062     elem = next_elem;
21063   }
21064   pH->count = 0;
21065 }
21066
21067 /*
21068 ** The hashing function.
21069 */
21070 static unsigned int strHash(const char *z, int nKey){
21071   int h = 0;
21072   assert( nKey>=0 );
21073   while( nKey > 0  ){
21074     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
21075     nKey--;
21076   }
21077   return h;
21078 }
21079
21080
21081 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
21082 ** insert pNew into the pEntry hash bucket.
21083 */
21084 static void insertElement(
21085   Hash *pH,              /* The complete hash table */
21086   struct _ht *pEntry,    /* The entry into which pNew is inserted */
21087   HashElem *pNew         /* The element to be inserted */
21088 ){
21089   HashElem *pHead;       /* First element already in pEntry */
21090   if( pEntry ){
21091     pHead = pEntry->count ? pEntry->chain : 0;
21092     pEntry->count++;
21093     pEntry->chain = pNew;
21094   }else{
21095     pHead = 0;
21096   }
21097   if( pHead ){
21098     pNew->next = pHead;
21099     pNew->prev = pHead->prev;
21100     if( pHead->prev ){ pHead->prev->next = pNew; }
21101     else             { pH->first = pNew; }
21102     pHead->prev = pNew;
21103   }else{
21104     pNew->next = pH->first;
21105     if( pH->first ){ pH->first->prev = pNew; }
21106     pNew->prev = 0;
21107     pH->first = pNew;
21108   }
21109 }
21110
21111
21112 /* Resize the hash table so that it cantains "new_size" buckets.
21113 **
21114 ** The hash table might fail to resize if sqlite3_malloc() fails or
21115 ** if the new size is the same as the prior size.
21116 ** Return TRUE if the resize occurs and false if not.
21117 */
21118 static int rehash(Hash *pH, unsigned int new_size){
21119   struct _ht *new_ht;            /* The new hash table */
21120   HashElem *elem, *next_elem;    /* For looping over existing elements */
21121
21122 #if SQLITE_MALLOC_SOFT_LIMIT>0
21123   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21124     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21125   }
21126   if( new_size==pH->htsize ) return 0;
21127 #endif
21128
21129   /* The inability to allocates space for a larger hash table is
21130   ** a performance hit but it is not a fatal error.  So mark the
21131   ** allocation as a benign.
21132   */
21133   sqlite3BeginBenignMalloc();
21134   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21135   sqlite3EndBenignMalloc();
21136
21137   if( new_ht==0 ) return 0;
21138   sqlite3_free(pH->ht);
21139   pH->ht = new_ht;
21140   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21141   memset(new_ht, 0, new_size*sizeof(struct _ht));
21142   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21143     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21144     next_elem = elem->next;
21145     insertElement(pH, &new_ht[h], elem);
21146   }
21147   return 1;
21148 }
21149
21150 /* This function (for internal use only) locates an element in an
21151 ** hash table that matches the given key.  The hash for this key has
21152 ** already been computed and is passed as the 4th parameter.
21153 */
21154 static HashElem *findElementGivenHash(
21155   const Hash *pH,     /* The pH to be searched */
21156   const char *pKey,   /* The key we are searching for */
21157   int nKey,           /* Bytes in key (not counting zero terminator) */
21158   unsigned int h      /* The hash for this key. */
21159 ){
21160   HashElem *elem;                /* Used to loop thru the element list */
21161   int count;                     /* Number of elements left to test */
21162
21163   if( pH->ht ){
21164     struct _ht *pEntry = &pH->ht[h];
21165     elem = pEntry->chain;
21166     count = pEntry->count;
21167   }else{
21168     elem = pH->first;
21169     count = pH->count;
21170   }
21171   while( count-- && ALWAYS(elem) ){
21172     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
21173       return elem;
21174     }
21175     elem = elem->next;
21176   }
21177   return 0;
21178 }
21179
21180 /* Remove a single entry from the hash table given a pointer to that
21181 ** element and a hash on the element's key.
21182 */
21183 static void removeElementGivenHash(
21184   Hash *pH,         /* The pH containing "elem" */
21185   HashElem* elem,   /* The element to be removed from the pH */
21186   unsigned int h    /* Hash value for the element */
21187 ){
21188   struct _ht *pEntry;
21189   if( elem->prev ){
21190     elem->prev->next = elem->next; 
21191   }else{
21192     pH->first = elem->next;
21193   }
21194   if( elem->next ){
21195     elem->next->prev = elem->prev;
21196   }
21197   if( pH->ht ){
21198     pEntry = &pH->ht[h];
21199     if( pEntry->chain==elem ){
21200       pEntry->chain = elem->next;
21201     }
21202     pEntry->count--;
21203     assert( pEntry->count>=0 );
21204   }
21205   sqlite3_free( elem );
21206   pH->count--;
21207   if( pH->count<=0 ){
21208     assert( pH->first==0 );
21209     assert( pH->count==0 );
21210     sqlite3HashClear(pH);
21211   }
21212 }
21213
21214 /* Attempt to locate an element of the hash table pH with a key
21215 ** that matches pKey,nKey.  Return the data for this element if it is
21216 ** found, or NULL if there is no match.
21217 */
21218 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
21219   HashElem *elem;    /* The element that matches key */
21220   unsigned int h;    /* A hash on key */
21221
21222   assert( pH!=0 );
21223   assert( pKey!=0 );
21224   assert( nKey>=0 );
21225   if( pH->ht ){
21226     h = strHash(pKey, nKey) % pH->htsize;
21227   }else{
21228     h = 0;
21229   }
21230   elem = findElementGivenHash(pH, pKey, nKey, h);
21231   return elem ? elem->data : 0;
21232 }
21233
21234 /* Insert an element into the hash table pH.  The key is pKey,nKey
21235 ** and the data is "data".
21236 **
21237 ** If no element exists with a matching key, then a new
21238 ** element is created and NULL is returned.
21239 **
21240 ** If another element already exists with the same key, then the
21241 ** new data replaces the old data and the old data is returned.
21242 ** The key is not copied in this instance.  If a malloc fails, then
21243 ** the new data is returned and the hash table is unchanged.
21244 **
21245 ** If the "data" parameter to this function is NULL, then the
21246 ** element corresponding to "key" is removed from the hash table.
21247 */
21248 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
21249   unsigned int h;       /* the hash of the key modulo hash table size */
21250   HashElem *elem;       /* Used to loop thru the element list */
21251   HashElem *new_elem;   /* New element added to the pH */
21252
21253   assert( pH!=0 );
21254   assert( pKey!=0 );
21255   assert( nKey>=0 );
21256   if( pH->htsize ){
21257     h = strHash(pKey, nKey) % pH->htsize;
21258   }else{
21259     h = 0;
21260   }
21261   elem = findElementGivenHash(pH,pKey,nKey,h);
21262   if( elem ){
21263     void *old_data = elem->data;
21264     if( data==0 ){
21265       removeElementGivenHash(pH,elem,h);
21266     }else{
21267       elem->data = data;
21268       elem->pKey = pKey;
21269       assert(nKey==elem->nKey);
21270     }
21271     return old_data;
21272   }
21273   if( data==0 ) return 0;
21274   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
21275   if( new_elem==0 ) return data;
21276   new_elem->pKey = pKey;
21277   new_elem->nKey = nKey;
21278   new_elem->data = data;
21279   pH->count++;
21280   if( pH->count>=10 && pH->count > 2*pH->htsize ){
21281     if( rehash(pH, pH->count*2) ){
21282       assert( pH->htsize>0 );
21283       h = strHash(pKey, nKey) % pH->htsize;
21284     }
21285   }
21286   if( pH->ht ){
21287     insertElement(pH, &pH->ht[h], new_elem);
21288   }else{
21289     insertElement(pH, 0, new_elem);
21290   }
21291   return 0;
21292 }
21293
21294 /************** End of hash.c ************************************************/
21295 /************** Begin file opcodes.c *****************************************/
21296 /* Automatically generated.  Do not edit */
21297 /* See the mkopcodec.awk script for details. */
21298 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
21299 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
21300  static const char *const azName[] = { "?",
21301      /*   1 */ "Goto",
21302      /*   2 */ "Gosub",
21303      /*   3 */ "Return",
21304      /*   4 */ "Yield",
21305      /*   5 */ "HaltIfNull",
21306      /*   6 */ "Halt",
21307      /*   7 */ "Integer",
21308      /*   8 */ "Int64",
21309      /*   9 */ "String",
21310      /*  10 */ "Null",
21311      /*  11 */ "Blob",
21312      /*  12 */ "Variable",
21313      /*  13 */ "Move",
21314      /*  14 */ "Copy",
21315      /*  15 */ "SCopy",
21316      /*  16 */ "ResultRow",
21317      /*  17 */ "CollSeq",
21318      /*  18 */ "Function",
21319      /*  19 */ "Not",
21320      /*  20 */ "AddImm",
21321      /*  21 */ "MustBeInt",
21322      /*  22 */ "RealAffinity",
21323      /*  23 */ "Permutation",
21324      /*  24 */ "Compare",
21325      /*  25 */ "Jump",
21326      /*  26 */ "If",
21327      /*  27 */ "IfNot",
21328      /*  28 */ "Column",
21329      /*  29 */ "Affinity",
21330      /*  30 */ "MakeRecord",
21331      /*  31 */ "Count",
21332      /*  32 */ "Savepoint",
21333      /*  33 */ "AutoCommit",
21334      /*  34 */ "Transaction",
21335      /*  35 */ "ReadCookie",
21336      /*  36 */ "SetCookie",
21337      /*  37 */ "VerifyCookie",
21338      /*  38 */ "OpenRead",
21339      /*  39 */ "OpenWrite",
21340      /*  40 */ "OpenAutoindex",
21341      /*  41 */ "OpenEphemeral",
21342      /*  42 */ "OpenPseudo",
21343      /*  43 */ "Close",
21344      /*  44 */ "SeekLt",
21345      /*  45 */ "SeekLe",
21346      /*  46 */ "SeekGe",
21347      /*  47 */ "SeekGt",
21348      /*  48 */ "Seek",
21349      /*  49 */ "NotFound",
21350      /*  50 */ "Found",
21351      /*  51 */ "IsUnique",
21352      /*  52 */ "NotExists",
21353      /*  53 */ "Sequence",
21354      /*  54 */ "NewRowid",
21355      /*  55 */ "Insert",
21356      /*  56 */ "InsertInt",
21357      /*  57 */ "Delete",
21358      /*  58 */ "ResetCount",
21359      /*  59 */ "RowKey",
21360      /*  60 */ "RowData",
21361      /*  61 */ "Rowid",
21362      /*  62 */ "NullRow",
21363      /*  63 */ "Last",
21364      /*  64 */ "Sort",
21365      /*  65 */ "Rewind",
21366      /*  66 */ "Prev",
21367      /*  67 */ "Next",
21368      /*  68 */ "Or",
21369      /*  69 */ "And",
21370      /*  70 */ "IdxInsert",
21371      /*  71 */ "IdxDelete",
21372      /*  72 */ "IdxRowid",
21373      /*  73 */ "IsNull",
21374      /*  74 */ "NotNull",
21375      /*  75 */ "Ne",
21376      /*  76 */ "Eq",
21377      /*  77 */ "Gt",
21378      /*  78 */ "Le",
21379      /*  79 */ "Lt",
21380      /*  80 */ "Ge",
21381      /*  81 */ "IdxLT",
21382      /*  82 */ "BitAnd",
21383      /*  83 */ "BitOr",
21384      /*  84 */ "ShiftLeft",
21385      /*  85 */ "ShiftRight",
21386      /*  86 */ "Add",
21387      /*  87 */ "Subtract",
21388      /*  88 */ "Multiply",
21389      /*  89 */ "Divide",
21390      /*  90 */ "Remainder",
21391      /*  91 */ "Concat",
21392      /*  92 */ "IdxGE",
21393      /*  93 */ "BitNot",
21394      /*  94 */ "String8",
21395      /*  95 */ "Destroy",
21396      /*  96 */ "Clear",
21397      /*  97 */ "CreateIndex",
21398      /*  98 */ "CreateTable",
21399      /*  99 */ "ParseSchema",
21400      /* 100 */ "LoadAnalysis",
21401      /* 101 */ "DropTable",
21402      /* 102 */ "DropIndex",
21403      /* 103 */ "DropTrigger",
21404      /* 104 */ "IntegrityCk",
21405      /* 105 */ "RowSetAdd",
21406      /* 106 */ "RowSetRead",
21407      /* 107 */ "RowSetTest",
21408      /* 108 */ "Program",
21409      /* 109 */ "Param",
21410      /* 110 */ "FkCounter",
21411      /* 111 */ "FkIfZero",
21412      /* 112 */ "MemMax",
21413      /* 113 */ "IfPos",
21414      /* 114 */ "IfNeg",
21415      /* 115 */ "IfZero",
21416      /* 116 */ "AggStep",
21417      /* 117 */ "AggFinal",
21418      /* 118 */ "Checkpoint",
21419      /* 119 */ "JournalMode",
21420      /* 120 */ "Vacuum",
21421      /* 121 */ "IncrVacuum",
21422      /* 122 */ "Expire",
21423      /* 123 */ "TableLock",
21424      /* 124 */ "VBegin",
21425      /* 125 */ "VCreate",
21426      /* 126 */ "VDestroy",
21427      /* 127 */ "VOpen",
21428      /* 128 */ "VFilter",
21429      /* 129 */ "VColumn",
21430      /* 130 */ "Real",
21431      /* 131 */ "VNext",
21432      /* 132 */ "VRename",
21433      /* 133 */ "VUpdate",
21434      /* 134 */ "Pagecount",
21435      /* 135 */ "MaxPgcnt",
21436      /* 136 */ "Trace",
21437      /* 137 */ "Noop",
21438      /* 138 */ "Explain",
21439      /* 139 */ "NotUsed_139",
21440      /* 140 */ "NotUsed_140",
21441      /* 141 */ "ToText",
21442      /* 142 */ "ToBlob",
21443      /* 143 */ "ToNumeric",
21444      /* 144 */ "ToInt",
21445      /* 145 */ "ToReal",
21446   };
21447   return azName[i];
21448 }
21449 #endif
21450
21451 /************** End of opcodes.c *********************************************/
21452 /************** Begin file os_os2.c ******************************************/
21453 /*
21454 ** 2006 Feb 14
21455 **
21456 ** The author disclaims copyright to this source code.  In place of
21457 ** a legal notice, here is a blessing:
21458 **
21459 **    May you do good and not evil.
21460 **    May you find forgiveness for yourself and forgive others.
21461 **    May you share freely, never taking more than you give.
21462 **
21463 ******************************************************************************
21464 **
21465 ** This file contains code that is specific to OS/2.
21466 */
21467
21468
21469 #if SQLITE_OS_OS2
21470
21471 /*
21472 ** A Note About Memory Allocation:
21473 **
21474 ** This driver uses malloc()/free() directly rather than going through
21475 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
21476 ** are designed for use on embedded systems where memory is scarce and
21477 ** malloc failures happen frequently.  OS/2 does not typically run on
21478 ** embedded systems, and when it does the developers normally have bigger
21479 ** problems to worry about than running out of memory.  So there is not
21480 ** a compelling need to use the wrappers.
21481 **
21482 ** But there is a good reason to not use the wrappers.  If we use the
21483 ** wrappers then we will get simulated malloc() failures within this
21484 ** driver.  And that causes all kinds of problems for our tests.  We
21485 ** could enhance SQLite to deal with simulated malloc failures within
21486 ** the OS driver, but the code to deal with those failure would not
21487 ** be exercised on Linux (which does not need to malloc() in the driver)
21488 ** and so we would have difficulty writing coverage tests for that
21489 ** code.  Better to leave the code out, we think.
21490 **
21491 ** The point of this discussion is as follows:  When creating a new
21492 ** OS layer for an embedded system, if you use this file as an example,
21493 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
21494 ** desktops but not so well in embedded systems.
21495 */
21496
21497 /*
21498 ** Macros used to determine whether or not to use threads.
21499 */
21500 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
21501 # define SQLITE_OS2_THREADS 1
21502 #endif
21503
21504 /*
21505 ** Include code that is common to all os_*.c files
21506 */
21507 /************** Include os_common.h in the middle of os_os2.c ****************/
21508 /************** Begin file os_common.h ***************************************/
21509 /*
21510 ** 2004 May 22
21511 **
21512 ** The author disclaims copyright to this source code.  In place of
21513 ** a legal notice, here is a blessing:
21514 **
21515 **    May you do good and not evil.
21516 **    May you find forgiveness for yourself and forgive others.
21517 **    May you share freely, never taking more than you give.
21518 **
21519 ******************************************************************************
21520 **
21521 ** This file contains macros and a little bit of code that is common to
21522 ** all of the platform-specific files (os_*.c) and is #included into those
21523 ** files.
21524 **
21525 ** This file should be #included by the os_*.c files only.  It is not a
21526 ** general purpose header file.
21527 */
21528 #ifndef _OS_COMMON_H_
21529 #define _OS_COMMON_H_
21530
21531 /*
21532 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21533 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21534 ** switch.  The following code should catch this problem at compile-time.
21535 */
21536 #ifdef MEMORY_DEBUG
21537 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21538 #endif
21539
21540 #ifdef SQLITE_DEBUG
21541 SQLITE_PRIVATE int sqlite3OSTrace = 0;
21542 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
21543 #else
21544 #define OSTRACE(X)
21545 #endif
21546
21547 /*
21548 ** Macros for performance tracing.  Normally turned off.  Only works
21549 ** on i486 hardware.
21550 */
21551 #ifdef SQLITE_PERFORMANCE_TRACE
21552
21553 /* 
21554 ** hwtime.h contains inline assembler code for implementing 
21555 ** high-performance timing routines.
21556 */
21557 /************** Include hwtime.h in the middle of os_common.h ****************/
21558 /************** Begin file hwtime.h ******************************************/
21559 /*
21560 ** 2008 May 27
21561 **
21562 ** The author disclaims copyright to this source code.  In place of
21563 ** a legal notice, here is a blessing:
21564 **
21565 **    May you do good and not evil.
21566 **    May you find forgiveness for yourself and forgive others.
21567 **    May you share freely, never taking more than you give.
21568 **
21569 ******************************************************************************
21570 **
21571 ** This file contains inline asm code for retrieving "high-performance"
21572 ** counters for x86 class CPUs.
21573 */
21574 #ifndef _HWTIME_H_
21575 #define _HWTIME_H_
21576
21577 /*
21578 ** The following routine only works on pentium-class (or newer) processors.
21579 ** It uses the RDTSC opcode to read the cycle count value out of the
21580 ** processor and returns that value.  This can be used for high-res
21581 ** profiling.
21582 */
21583 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
21584       (defined(i386) || defined(__i386__) || defined(_M_IX86))
21585
21586   #if defined(__GNUC__)
21587
21588   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21589      unsigned int lo, hi;
21590      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21591      return (sqlite_uint64)hi << 32 | lo;
21592   }
21593
21594   #elif defined(_MSC_VER)
21595
21596   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21597      __asm {
21598         rdtsc
21599         ret       ; return value at EDX:EAX
21600      }
21601   }
21602
21603   #endif
21604
21605 #elif (defined(__GNUC__) && defined(__x86_64__))
21606
21607   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21608       unsigned long val;
21609       __asm__ __volatile__ ("rdtsc" : "=A" (val));
21610       return val;
21611   }
21612  
21613 #elif (defined(__GNUC__) && defined(__ppc__))
21614
21615   __inline__ sqlite_uint64 sqlite3Hwtime(void){
21616       unsigned long long retval;
21617       unsigned long junk;
21618       __asm__ __volatile__ ("\n\
21619           1:      mftbu   %1\n\
21620                   mftb    %L0\n\
21621                   mftbu   %0\n\
21622                   cmpw    %0,%1\n\
21623                   bne     1b"
21624                   : "=r" (retval), "=r" (junk));
21625       return retval;
21626   }
21627
21628 #else
21629
21630   #error Need implementation of sqlite3Hwtime() for your platform.
21631
21632   /*
21633   ** To compile without implementing sqlite3Hwtime() for your platform,
21634   ** you can remove the above #error and use the following
21635   ** stub function.  You will lose timing support for many
21636   ** of the debugging and testing utilities, but it should at
21637   ** least compile and run.
21638   */
21639 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21640
21641 #endif
21642
21643 #endif /* !defined(_HWTIME_H_) */
21644
21645 /************** End of hwtime.h **********************************************/
21646 /************** Continuing where we left off in os_common.h ******************/
21647
21648 static sqlite_uint64 g_start;
21649 static sqlite_uint64 g_elapsed;
21650 #define TIMER_START       g_start=sqlite3Hwtime()
21651 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21652 #define TIMER_ELAPSED     g_elapsed
21653 #else
21654 #define TIMER_START
21655 #define TIMER_END
21656 #define TIMER_ELAPSED     ((sqlite_uint64)0)
21657 #endif
21658
21659 /*
21660 ** If we compile with the SQLITE_TEST macro set, then the following block
21661 ** of code will give us the ability to simulate a disk I/O error.  This
21662 ** is used for testing the I/O recovery logic.
21663 */
21664 #ifdef SQLITE_TEST
21665 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21666 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21667 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21668 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21669 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21670 SQLITE_API int sqlite3_diskfull_pending = 0;
21671 SQLITE_API int sqlite3_diskfull = 0;
21672 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21673 #define SimulateIOError(CODE)  \
21674   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21675        || sqlite3_io_error_pending-- == 1 )  \
21676               { local_ioerr(); CODE; }
21677 static void local_ioerr(){
21678   IOTRACE(("IOERR\n"));
21679   sqlite3_io_error_hit++;
21680   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21681 }
21682 #define SimulateDiskfullError(CODE) \
21683    if( sqlite3_diskfull_pending ){ \
21684      if( sqlite3_diskfull_pending == 1 ){ \
21685        local_ioerr(); \
21686        sqlite3_diskfull = 1; \
21687        sqlite3_io_error_hit = 1; \
21688        CODE; \
21689      }else{ \
21690        sqlite3_diskfull_pending--; \
21691      } \
21692    }
21693 #else
21694 #define SimulateIOErrorBenign(X)
21695 #define SimulateIOError(A)
21696 #define SimulateDiskfullError(A)
21697 #endif
21698
21699 /*
21700 ** When testing, keep a count of the number of open files.
21701 */
21702 #ifdef SQLITE_TEST
21703 SQLITE_API int sqlite3_open_file_count = 0;
21704 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
21705 #else
21706 #define OpenCounter(X)
21707 #endif
21708
21709 #endif /* !defined(_OS_COMMON_H_) */
21710
21711 /************** End of os_common.h *******************************************/
21712 /************** Continuing where we left off in os_os2.c *********************/
21713
21714 /*
21715 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
21716 ** protability layer.
21717 */
21718 typedef struct os2File os2File;
21719 struct os2File {
21720   const sqlite3_io_methods *pMethod;  /* Always the first entry */
21721   HFILE h;                  /* Handle for accessing the file */
21722   char* pathToDel;          /* Name of file to delete on close, NULL if not */
21723   unsigned char locktype;   /* Type of lock currently held on this file */
21724 };
21725
21726 #define LOCK_TIMEOUT 10L /* the default locking timeout */
21727
21728 /*****************************************************************************
21729 ** The next group of routines implement the I/O methods specified
21730 ** by the sqlite3_io_methods object.
21731 ******************************************************************************/
21732
21733 /*
21734 ** Close a file.
21735 */
21736 static int os2Close( sqlite3_file *id ){
21737   APIRET rc = NO_ERROR;
21738   os2File *pFile;
21739   if( id && (pFile = (os2File*)id) != 0 ){
21740     OSTRACE(( "CLOSE %d\n", pFile->h ));
21741     rc = DosClose( pFile->h );
21742     pFile->locktype = NO_LOCK;
21743     if( pFile->pathToDel != NULL ){
21744       rc = DosForceDelete( (PSZ)pFile->pathToDel );
21745       free( pFile->pathToDel );
21746       pFile->pathToDel = NULL;
21747     }
21748     id = 0;
21749     OpenCounter( -1 );
21750   }
21751
21752   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21753 }
21754
21755 /*
21756 ** Read data from a file into a buffer.  Return SQLITE_OK if all
21757 ** bytes were read successfully and SQLITE_IOERR if anything goes
21758 ** wrong.
21759 */
21760 static int os2Read(
21761   sqlite3_file *id,               /* File to read from */
21762   void *pBuf,                     /* Write content into this buffer */
21763   int amt,                        /* Number of bytes to read */
21764   sqlite3_int64 offset            /* Begin reading at this offset */
21765 ){
21766   ULONG fileLocation = 0L;
21767   ULONG got;
21768   os2File *pFile = (os2File*)id;
21769   assert( id!=0 );
21770   SimulateIOError( return SQLITE_IOERR_READ );
21771   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
21772   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21773     return SQLITE_IOERR;
21774   }
21775   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
21776     return SQLITE_IOERR_READ;
21777   }
21778   if( got == (ULONG)amt )
21779     return SQLITE_OK;
21780   else {
21781     /* Unread portions of the input buffer must be zero-filled */
21782     memset(&((char*)pBuf)[got], 0, amt-got);
21783     return SQLITE_IOERR_SHORT_READ;
21784   }
21785 }
21786
21787 /*
21788 ** Write data from a buffer into a file.  Return SQLITE_OK on success
21789 ** or some other error code on failure.
21790 */
21791 static int os2Write(
21792   sqlite3_file *id,               /* File to write into */
21793   const void *pBuf,               /* The bytes to be written */
21794   int amt,                        /* Number of bytes to write */
21795   sqlite3_int64 offset            /* Offset into the file to begin writing at */
21796 ){
21797   ULONG fileLocation = 0L;
21798   APIRET rc = NO_ERROR;
21799   ULONG wrote;
21800   os2File *pFile = (os2File*)id;
21801   assert( id!=0 );
21802   SimulateIOError( return SQLITE_IOERR_WRITE );
21803   SimulateDiskfullError( return SQLITE_FULL );
21804   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
21805   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
21806     return SQLITE_IOERR;
21807   }
21808   assert( amt>0 );
21809   while( amt > 0 &&
21810          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
21811          wrote > 0
21812   ){
21813     amt -= wrote;
21814     pBuf = &((char*)pBuf)[wrote];
21815   }
21816
21817   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
21818 }
21819
21820 /*
21821 ** Truncate an open file to a specified size
21822 */
21823 static int os2Truncate( sqlite3_file *id, i64 nByte ){
21824   APIRET rc = NO_ERROR;
21825   os2File *pFile = (os2File*)id;
21826   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
21827   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
21828   rc = DosSetFileSize( pFile->h, nByte );
21829   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
21830 }
21831
21832 #ifdef SQLITE_TEST
21833 /*
21834 ** Count the number of fullsyncs and normal syncs.  This is used to test
21835 ** that syncs and fullsyncs are occuring at the right times.
21836 */
21837 SQLITE_API int sqlite3_sync_count = 0;
21838 SQLITE_API int sqlite3_fullsync_count = 0;
21839 #endif
21840
21841 /*
21842 ** Make sure all writes to a particular file are committed to disk.
21843 */
21844 static int os2Sync( sqlite3_file *id, int flags ){
21845   os2File *pFile = (os2File*)id;
21846   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
21847 #ifdef SQLITE_TEST
21848   if( flags & SQLITE_SYNC_FULL){
21849     sqlite3_fullsync_count++;
21850   }
21851   sqlite3_sync_count++;
21852 #endif
21853   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
21854   ** no-op
21855   */
21856 #ifdef SQLITE_NO_SYNC
21857   UNUSED_PARAMETER(pFile);
21858   return SQLITE_OK;
21859 #else
21860   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21861 #endif
21862 }
21863
21864 /*
21865 ** Determine the current size of a file in bytes
21866 */
21867 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
21868   APIRET rc = NO_ERROR;
21869   FILESTATUS3 fsts3FileInfo;
21870   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
21871   assert( id!=0 );
21872   SimulateIOError( return SQLITE_IOERR_FSTAT );
21873   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
21874   if( rc == NO_ERROR ){
21875     *pSize = fsts3FileInfo.cbFile;
21876     return SQLITE_OK;
21877   }else{
21878     return SQLITE_IOERR_FSTAT;
21879   }
21880 }
21881
21882 /*
21883 ** Acquire a reader lock.
21884 */
21885 static int getReadLock( os2File *pFile ){
21886   FILELOCK  LockArea,
21887             UnlockArea;
21888   APIRET res;
21889   memset(&LockArea, 0, sizeof(LockArea));
21890   memset(&UnlockArea, 0, sizeof(UnlockArea));
21891   LockArea.lOffset = SHARED_FIRST;
21892   LockArea.lRange = SHARED_SIZE;
21893   UnlockArea.lOffset = 0L;
21894   UnlockArea.lRange = 0L;
21895   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21896   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
21897   return res;
21898 }
21899
21900 /*
21901 ** Undo a readlock
21902 */
21903 static int unlockReadLock( os2File *id ){
21904   FILELOCK  LockArea,
21905             UnlockArea;
21906   APIRET res;
21907   memset(&LockArea, 0, sizeof(LockArea));
21908   memset(&UnlockArea, 0, sizeof(UnlockArea));
21909   LockArea.lOffset = 0L;
21910   LockArea.lRange = 0L;
21911   UnlockArea.lOffset = SHARED_FIRST;
21912   UnlockArea.lRange = SHARED_SIZE;
21913   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
21914   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
21915   return res;
21916 }
21917
21918 /*
21919 ** Lock the file with the lock specified by parameter locktype - one
21920 ** of the following:
21921 **
21922 **     (1) SHARED_LOCK
21923 **     (2) RESERVED_LOCK
21924 **     (3) PENDING_LOCK
21925 **     (4) EXCLUSIVE_LOCK
21926 **
21927 ** Sometimes when requesting one lock state, additional lock states
21928 ** are inserted in between.  The locking might fail on one of the later
21929 ** transitions leaving the lock state different from what it started but
21930 ** still short of its goal.  The following chart shows the allowed
21931 ** transitions and the inserted intermediate states:
21932 **
21933 **    UNLOCKED -> SHARED
21934 **    SHARED -> RESERVED
21935 **    SHARED -> (PENDING) -> EXCLUSIVE
21936 **    RESERVED -> (PENDING) -> EXCLUSIVE
21937 **    PENDING -> EXCLUSIVE
21938 **
21939 ** This routine will only increase a lock.  The os2Unlock() routine
21940 ** erases all locks at once and returns us immediately to locking level 0.
21941 ** It is not possible to lower the locking level one step at a time.  You
21942 ** must go straight to locking level 0.
21943 */
21944 static int os2Lock( sqlite3_file *id, int locktype ){
21945   int rc = SQLITE_OK;       /* Return code from subroutines */
21946   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
21947   int newLocktype;       /* Set pFile->locktype to this value before exiting */
21948   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
21949   FILELOCK  LockArea,
21950             UnlockArea;
21951   os2File *pFile = (os2File*)id;
21952   memset(&LockArea, 0, sizeof(LockArea));
21953   memset(&UnlockArea, 0, sizeof(UnlockArea));
21954   assert( pFile!=0 );
21955   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
21956
21957   /* If there is already a lock of this type or more restrictive on the
21958   ** os2File, do nothing. Don't use the end_lock: exit path, as
21959   ** sqlite3_mutex_enter() hasn't been called yet.
21960   */
21961   if( pFile->locktype>=locktype ){
21962     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
21963     return SQLITE_OK;
21964   }
21965
21966   /* Make sure the locking sequence is correct
21967   */
21968   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
21969   assert( locktype!=PENDING_LOCK );
21970   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
21971
21972   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
21973   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
21974   ** the PENDING_LOCK byte is temporary.
21975   */
21976   newLocktype = pFile->locktype;
21977   if( pFile->locktype==NO_LOCK
21978       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
21979   ){
21980     LockArea.lOffset = PENDING_BYTE;
21981     LockArea.lRange = 1L;
21982     UnlockArea.lOffset = 0L;
21983     UnlockArea.lRange = 0L;
21984
21985     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
21986     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
21987     if( res == NO_ERROR ){
21988       gotPendingLock = 1;
21989       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
21990     }
21991   }
21992
21993   /* Acquire a shared lock
21994   */
21995   if( locktype==SHARED_LOCK && res == NO_ERROR ){
21996     assert( pFile->locktype==NO_LOCK );
21997     res = getReadLock(pFile);
21998     if( res == NO_ERROR ){
21999       newLocktype = SHARED_LOCK;
22000     }
22001     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
22002   }
22003
22004   /* Acquire a RESERVED lock
22005   */
22006   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
22007     assert( pFile->locktype==SHARED_LOCK );
22008     LockArea.lOffset = RESERVED_BYTE;
22009     LockArea.lRange = 1L;
22010     UnlockArea.lOffset = 0L;
22011     UnlockArea.lRange = 0L;
22012     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22013     if( res == NO_ERROR ){
22014       newLocktype = RESERVED_LOCK;
22015     }
22016     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
22017   }
22018
22019   /* Acquire a PENDING lock
22020   */
22021   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22022     newLocktype = PENDING_LOCK;
22023     gotPendingLock = 0;
22024     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
22025                pFile->h ));
22026   }
22027
22028   /* Acquire an EXCLUSIVE lock
22029   */
22030   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22031     assert( pFile->locktype>=SHARED_LOCK );
22032     res = unlockReadLock(pFile);
22033     OSTRACE(( "unreadlock = %d\n", res ));
22034     LockArea.lOffset = SHARED_FIRST;
22035     LockArea.lRange = SHARED_SIZE;
22036     UnlockArea.lOffset = 0L;
22037     UnlockArea.lRange = 0L;
22038     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22039     if( res == NO_ERROR ){
22040       newLocktype = EXCLUSIVE_LOCK;
22041     }else{
22042       OSTRACE(( "OS/2 error-code = %d\n", res ));
22043       getReadLock(pFile);
22044     }
22045     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
22046   }
22047
22048   /* If we are holding a PENDING lock that ought to be released, then
22049   ** release it now.
22050   */
22051   if( gotPendingLock && locktype==SHARED_LOCK ){
22052     int r;
22053     LockArea.lOffset = 0L;
22054     LockArea.lRange = 0L;
22055     UnlockArea.lOffset = PENDING_BYTE;
22056     UnlockArea.lRange = 1L;
22057     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22058     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
22059   }
22060
22061   /* Update the state of the lock has held in the file descriptor then
22062   ** return the appropriate result code.
22063   */
22064   if( res == NO_ERROR ){
22065     rc = SQLITE_OK;
22066   }else{
22067     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22068               locktype, newLocktype ));
22069     rc = SQLITE_BUSY;
22070   }
22071   pFile->locktype = newLocktype;
22072   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
22073   return rc;
22074 }
22075
22076 /*
22077 ** This routine checks if there is a RESERVED lock held on the specified
22078 ** file by this or any other process. If such a lock is held, return
22079 ** non-zero, otherwise zero.
22080 */
22081 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
22082   int r = 0;
22083   os2File *pFile = (os2File*)id;
22084   assert( pFile!=0 );
22085   if( pFile->locktype>=RESERVED_LOCK ){
22086     r = 1;
22087     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
22088   }else{
22089     FILELOCK  LockArea,
22090               UnlockArea;
22091     APIRET rc = NO_ERROR;
22092     memset(&LockArea, 0, sizeof(LockArea));
22093     memset(&UnlockArea, 0, sizeof(UnlockArea));
22094     LockArea.lOffset = RESERVED_BYTE;
22095     LockArea.lRange = 1L;
22096     UnlockArea.lOffset = 0L;
22097     UnlockArea.lRange = 0L;
22098     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22099     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
22100     if( rc == NO_ERROR ){
22101       APIRET rcu = NO_ERROR; /* return code for unlocking */
22102       LockArea.lOffset = 0L;
22103       LockArea.lRange = 0L;
22104       UnlockArea.lOffset = RESERVED_BYTE;
22105       UnlockArea.lRange = 1L;
22106       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22107       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22108     }
22109     r = !(rc == NO_ERROR);
22110     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22111   }
22112   *pOut = r;
22113   return SQLITE_OK;
22114 }
22115
22116 /*
22117 ** Lower the locking level on file descriptor id to locktype.  locktype
22118 ** must be either NO_LOCK or SHARED_LOCK.
22119 **
22120 ** If the locking level of the file descriptor is already at or below
22121 ** the requested locking level, this routine is a no-op.
22122 **
22123 ** It is not possible for this routine to fail if the second argument
22124 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
22125 ** might return SQLITE_IOERR;
22126 */
22127 static int os2Unlock( sqlite3_file *id, int locktype ){
22128   int type;
22129   os2File *pFile = (os2File*)id;
22130   APIRET rc = SQLITE_OK;
22131   APIRET res = NO_ERROR;
22132   FILELOCK  LockArea,
22133             UnlockArea;
22134   memset(&LockArea, 0, sizeof(LockArea));
22135   memset(&UnlockArea, 0, sizeof(UnlockArea));
22136   assert( pFile!=0 );
22137   assert( locktype<=SHARED_LOCK );
22138   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22139   type = pFile->locktype;
22140   if( type>=EXCLUSIVE_LOCK ){
22141     LockArea.lOffset = 0L;
22142     LockArea.lRange = 0L;
22143     UnlockArea.lOffset = SHARED_FIRST;
22144     UnlockArea.lRange = SHARED_SIZE;
22145     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22146     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22147     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22148       /* This should never happen.  We should always be able to
22149       ** reacquire the read lock */
22150       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22151       rc = SQLITE_IOERR_UNLOCK;
22152     }
22153   }
22154   if( type>=RESERVED_LOCK ){
22155     LockArea.lOffset = 0L;
22156     LockArea.lRange = 0L;
22157     UnlockArea.lOffset = RESERVED_BYTE;
22158     UnlockArea.lRange = 1L;
22159     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22160     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
22161   }
22162   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22163     res = unlockReadLock(pFile);
22164     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
22165               pFile->h, type, locktype, res ));
22166   }
22167   if( type>=PENDING_LOCK ){
22168     LockArea.lOffset = 0L;
22169     LockArea.lRange = 0L;
22170     UnlockArea.lOffset = PENDING_BYTE;
22171     UnlockArea.lRange = 1L;
22172     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22173     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
22174   }
22175   pFile->locktype = locktype;
22176   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
22177   return rc;
22178 }
22179
22180 /*
22181 ** Control and query of the open file handle.
22182 */
22183 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
22184   switch( op ){
22185     case SQLITE_FCNTL_LOCKSTATE: {
22186       *(int*)pArg = ((os2File*)id)->locktype;
22187       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
22188                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
22189       return SQLITE_OK;
22190     }
22191   }
22192   return SQLITE_ERROR;
22193 }
22194
22195 /*
22196 ** Return the sector size in bytes of the underlying block device for
22197 ** the specified file. This is almost always 512 bytes, but may be
22198 ** larger for some devices.
22199 **
22200 ** SQLite code assumes this function cannot fail. It also assumes that
22201 ** if two files are created in the same file-system directory (i.e.
22202 ** a database and its journal file) that the sector size will be the
22203 ** same for both.
22204 */
22205 static int os2SectorSize(sqlite3_file *id){
22206   return SQLITE_DEFAULT_SECTOR_SIZE;
22207 }
22208
22209 /*
22210 ** Return a vector of device characteristics.
22211 */
22212 static int os2DeviceCharacteristics(sqlite3_file *id){
22213   return 0;
22214 }
22215
22216
22217 /*
22218 ** Character set conversion objects used by conversion routines.
22219 */
22220 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
22221 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
22222
22223 /*
22224 ** Helper function to initialize the conversion objects from and to UTF-8.
22225 */
22226 static void initUconvObjects( void ){
22227   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
22228     ucUtf8 = NULL;
22229   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
22230     uclCp = NULL;
22231 }
22232
22233 /*
22234 ** Helper function to free the conversion objects from and to UTF-8.
22235 */
22236 static void freeUconvObjects( void ){
22237   if ( ucUtf8 )
22238     UniFreeUconvObject( ucUtf8 );
22239   if ( uclCp )
22240     UniFreeUconvObject( uclCp );
22241   ucUtf8 = NULL;
22242   uclCp = NULL;
22243 }
22244
22245 /*
22246 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
22247 ** The two-step process: first convert the incoming UTF-8 string
22248 ** into UCS-2 and then from UCS-2 to the current codepage.
22249 ** The returned char pointer has to be freed.
22250 */
22251 static char *convertUtf8PathToCp( const char *in ){
22252   UniChar tempPath[CCHMAXPATH];
22253   char *out = (char *)calloc( CCHMAXPATH, 1 );
22254
22255   if( !out )
22256     return NULL;
22257
22258   if( !ucUtf8 || !uclCp )
22259     initUconvObjects();
22260
22261   /* determine string for the conversion of UTF-8 which is CP1208 */
22262   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22263     return out; /* if conversion fails, return the empty string */
22264
22265   /* conversion for current codepage which can be used for paths */
22266   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
22267
22268   return out;
22269 }
22270
22271 /*
22272 ** Helper function to convert filenames from local codepage to UTF-8.
22273 ** The two-step process: first convert the incoming codepage-specific
22274 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
22275 ** The returned char pointer has to be freed.
22276 **
22277 ** This function is non-static to be able to use this in shell.c and
22278 ** similar applications that take command line arguments.
22279 */
22280 char *convertCpPathToUtf8( const char *in ){
22281   UniChar tempPath[CCHMAXPATH];
22282   char *out = (char *)calloc( CCHMAXPATH, 1 );
22283
22284   if( !out )
22285     return NULL;
22286
22287   if( !ucUtf8 || !uclCp )
22288     initUconvObjects();
22289
22290   /* conversion for current codepage which can be used for paths */
22291   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
22292     return out; /* if conversion fails, return the empty string */
22293
22294   /* determine string for the conversion of UTF-8 which is CP1208 */
22295   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
22296
22297   return out;
22298 }
22299
22300 /*
22301 ** This vector defines all the methods that can operate on an
22302 ** sqlite3_file for os2.
22303 */
22304 static const sqlite3_io_methods os2IoMethod = {
22305   1,                        /* iVersion */
22306   os2Close,
22307   os2Read,
22308   os2Write,
22309   os2Truncate,
22310   os2Sync,
22311   os2FileSize,
22312   os2Lock,
22313   os2Unlock,
22314   os2CheckReservedLock,
22315   os2FileControl,
22316   os2SectorSize,
22317   os2DeviceCharacteristics
22318 };
22319
22320 /***************************************************************************
22321 ** Here ends the I/O methods that form the sqlite3_io_methods object.
22322 **
22323 ** The next block of code implements the VFS methods.
22324 ****************************************************************************/
22325
22326 /*
22327 ** Create a temporary file name in zBuf.  zBuf must be big enough to
22328 ** hold at pVfs->mxPathname characters.
22329 */
22330 static int getTempname(int nBuf, char *zBuf ){
22331   static const unsigned char zChars[] =
22332     "abcdefghijklmnopqrstuvwxyz"
22333     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
22334     "0123456789";
22335   int i, j;
22336   char zTempPathBuf[3];
22337   PSZ zTempPath = (PSZ)&zTempPathBuf;
22338   if( sqlite3_temp_directory ){
22339     zTempPath = sqlite3_temp_directory;
22340   }else{
22341     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
22342       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
22343         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
22344            ULONG ulDriveNum = 0, ulDriveMap = 0;
22345            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
22346            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
22347         }
22348       }
22349     }
22350   }
22351   /* Strip off a trailing slashes or backslashes, otherwise we would get *
22352    * multiple (back)slashes which causes DosOpen() to fail.              *
22353    * Trailing spaces are not allowed, either.                            */
22354   j = sqlite3Strlen30(zTempPath);
22355   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
22356                     || zTempPath[j-1] == ' ' ) ){
22357     j--;
22358   }
22359   zTempPath[j] = '\0';
22360   if( !sqlite3_temp_directory ){
22361     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
22362     sqlite3_snprintf( nBuf-30, zBuf,
22363                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
22364     free( zTempPathUTF );
22365   }else{
22366     sqlite3_snprintf( nBuf-30, zBuf,
22367                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
22368   }
22369   j = sqlite3Strlen30( zBuf );
22370   sqlite3_randomness( 20, &zBuf[j] );
22371   for( i = 0; i < 20; i++, j++ ){
22372     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
22373   }
22374   zBuf[j] = 0;
22375   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
22376   return SQLITE_OK;
22377 }
22378
22379
22380 /*
22381 ** Turn a relative pathname into a full pathname.  Write the full
22382 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
22383 ** bytes in size.
22384 */
22385 static int os2FullPathname(
22386   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
22387   const char *zRelative,      /* Possibly relative input path */
22388   int nFull,                  /* Size of output buffer in bytes */
22389   char *zFull                 /* Output buffer */
22390 ){
22391   char *zRelativeCp = convertUtf8PathToCp( zRelative );
22392   char zFullCp[CCHMAXPATH] = "\0";
22393   char *zFullUTF;
22394   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
22395                                 CCHMAXPATH );
22396   free( zRelativeCp );
22397   zFullUTF = convertCpPathToUtf8( zFullCp );
22398   sqlite3_snprintf( nFull, zFull, zFullUTF );
22399   free( zFullUTF );
22400   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22401 }
22402
22403
22404 /*
22405 ** Open a file.
22406 */
22407 static int os2Open(
22408   sqlite3_vfs *pVfs,            /* Not used */
22409   const char *zName,            /* Name of the file */
22410   sqlite3_file *id,             /* Write the SQLite file handle here */
22411   int flags,                    /* Open mode flags */
22412   int *pOutFlags                /* Status return flags */
22413 ){
22414   HFILE h;
22415   ULONG ulFileAttribute = FILE_NORMAL;
22416   ULONG ulOpenFlags = 0;
22417   ULONG ulOpenMode = 0;
22418   os2File *pFile = (os2File*)id;
22419   APIRET rc = NO_ERROR;
22420   ULONG ulAction;
22421   char *zNameCp;
22422   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
22423
22424   /* If the second argument to this function is NULL, generate a 
22425   ** temporary file name to use 
22426   */
22427   if( !zName ){
22428     int rc = getTempname(CCHMAXPATH+1, zTmpname);
22429     if( rc!=SQLITE_OK ){
22430       return rc;
22431     }
22432     zName = zTmpname;
22433   }
22434
22435
22436   memset( pFile, 0, sizeof(*pFile) );
22437
22438   OSTRACE(( "OPEN want %d\n", flags ));
22439
22440   if( flags & SQLITE_OPEN_READWRITE ){
22441     ulOpenMode |= OPEN_ACCESS_READWRITE;
22442     OSTRACE(( "OPEN read/write\n" ));
22443   }else{
22444     ulOpenMode |= OPEN_ACCESS_READONLY;
22445     OSTRACE(( "OPEN read only\n" ));
22446   }
22447
22448   if( flags & SQLITE_OPEN_CREATE ){
22449     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
22450     OSTRACE(( "OPEN open new/create\n" ));
22451   }else{
22452     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
22453     OSTRACE(( "OPEN open existing\n" ));
22454   }
22455
22456   if( flags & SQLITE_OPEN_MAIN_DB ){
22457     ulOpenMode |= OPEN_SHARE_DENYNONE;
22458     OSTRACE(( "OPEN share read/write\n" ));
22459   }else{
22460     ulOpenMode |= OPEN_SHARE_DENYWRITE;
22461     OSTRACE(( "OPEN share read only\n" ));
22462   }
22463
22464   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
22465     char pathUtf8[CCHMAXPATH];
22466 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
22467     ulFileAttribute = FILE_HIDDEN;
22468 #endif
22469     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
22470     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
22471     OSTRACE(( "OPEN hidden/delete on close file attributes\n" ));
22472   }else{
22473     pFile->pathToDel = NULL;
22474     OSTRACE(( "OPEN normal file attribute\n" ));
22475   }
22476
22477   /* always open in random access mode for possibly better speed */
22478   ulOpenMode |= OPEN_FLAGS_RANDOM;
22479   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
22480   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
22481
22482   zNameCp = convertUtf8PathToCp( zName );
22483   rc = DosOpen( (PSZ)zNameCp,
22484                 &h,
22485                 &ulAction,
22486                 0L,
22487                 ulFileAttribute,
22488                 ulOpenFlags,
22489                 ulOpenMode,
22490                 (PEAOP2)NULL );
22491   free( zNameCp );
22492   if( rc != NO_ERROR ){
22493     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
22494               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode ));
22495     if( pFile->pathToDel )
22496       free( pFile->pathToDel );
22497     pFile->pathToDel = NULL;
22498     if( flags & SQLITE_OPEN_READWRITE ){
22499       OSTRACE(( "OPEN %d Invalid handle\n",
22500                 ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) ));
22501       return os2Open( pVfs, zName, id,
22502                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
22503                       pOutFlags );
22504     }else{
22505       return SQLITE_CANTOPEN;
22506     }
22507   }
22508
22509   if( pOutFlags ){
22510     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
22511   }
22512
22513   pFile->pMethod = &os2IoMethod;
22514   pFile->h = h;
22515   OpenCounter(+1);
22516   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
22517   return SQLITE_OK;
22518 }
22519
22520 /*
22521 ** Delete the named file.
22522 */
22523 static int os2Delete(
22524   sqlite3_vfs *pVfs,                     /* Not used on os2 */
22525   const char *zFilename,                 /* Name of file to delete */
22526   int syncDir                            /* Not used on os2 */
22527 ){
22528   APIRET rc = NO_ERROR;
22529   char *zFilenameCp = convertUtf8PathToCp( zFilename );
22530   SimulateIOError( return SQLITE_IOERR_DELETE );
22531   rc = DosDelete( (PSZ)zFilenameCp );
22532   free( zFilenameCp );
22533   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
22534   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
22535 }
22536
22537 /*
22538 ** Check the existance and status of a file.
22539 */
22540 static int os2Access(
22541   sqlite3_vfs *pVfs,        /* Not used on os2 */
22542   const char *zFilename,    /* Name of file to check */
22543   int flags,                /* Type of test to make on this file */
22544   int *pOut                 /* Write results here */
22545 ){
22546   FILESTATUS3 fsts3ConfigInfo;
22547   APIRET rc = NO_ERROR;
22548   char *zFilenameCp = convertUtf8PathToCp( zFilename );
22549
22550   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
22551   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
22552                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
22553   free( zFilenameCp );
22554   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
22555             fsts3ConfigInfo.attrFile, flags, rc ));
22556   switch( flags ){
22557     case SQLITE_ACCESS_READ:
22558     case SQLITE_ACCESS_EXISTS:
22559       rc = (rc == NO_ERROR);
22560       OSTRACE(( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc));
22561       break;
22562     case SQLITE_ACCESS_READWRITE:
22563       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
22564       OSTRACE(( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc ));
22565       break;
22566     default:
22567       assert( !"Invalid flags argument" );
22568   }
22569   *pOut = rc;
22570   return SQLITE_OK;
22571 }
22572
22573
22574 #ifndef SQLITE_OMIT_LOAD_EXTENSION
22575 /*
22576 ** Interfaces for opening a shared library, finding entry points
22577 ** within the shared library, and closing the shared library.
22578 */
22579 /*
22580 ** Interfaces for opening a shared library, finding entry points
22581 ** within the shared library, and closing the shared library.
22582 */
22583 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
22584   UCHAR loadErr[256];
22585   HMODULE hmod;
22586   APIRET rc;
22587   char *zFilenameCp = convertUtf8PathToCp(zFilename);
22588   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
22589   free(zFilenameCp);
22590   return rc != NO_ERROR ? 0 : (void*)hmod;
22591 }
22592 /*
22593 ** A no-op since the error code is returned on the DosLoadModule call.
22594 ** os2Dlopen returns zero if DosLoadModule is not successful.
22595 */
22596 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
22597 /* no-op */
22598 }
22599 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
22600   PFN pfn;
22601   APIRET rc;
22602   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
22603   if( rc != NO_ERROR ){
22604     /* if the symbol itself was not found, search again for the same
22605      * symbol with an extra underscore, that might be needed depending
22606      * on the calling convention */
22607     char _zSymbol[256] = "_";
22608     strncat(_zSymbol, zSymbol, 255);
22609     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
22610   }
22611   return rc != NO_ERROR ? 0 : (void*)pfn;
22612 }
22613 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
22614   DosFreeModule((HMODULE)pHandle);
22615 }
22616 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
22617   #define os2DlOpen 0
22618   #define os2DlError 0
22619   #define os2DlSym 0
22620   #define os2DlClose 0
22621 #endif
22622
22623
22624 /*
22625 ** Write up to nBuf bytes of randomness into zBuf.
22626 */
22627 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
22628   int n = 0;
22629 #if defined(SQLITE_TEST)
22630   n = nBuf;
22631   memset(zBuf, 0, nBuf);
22632 #else
22633   int sizeofULong = sizeof(ULONG);
22634   if( (int)sizeof(DATETIME) <= nBuf - n ){
22635     DATETIME x;
22636     DosGetDateTime(&x);
22637     memcpy(&zBuf[n], &x, sizeof(x));
22638     n += sizeof(x);
22639   }
22640
22641   if( sizeofULong <= nBuf - n ){
22642     PPIB ppib;
22643     DosGetInfoBlocks(NULL, &ppib);
22644     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
22645     n += sizeofULong;
22646   }
22647
22648   if( sizeofULong <= nBuf - n ){
22649     PTIB ptib;
22650     DosGetInfoBlocks(&ptib, NULL);
22651     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
22652     n += sizeofULong;
22653   }
22654
22655   /* if we still haven't filled the buffer yet the following will */
22656   /* grab everything once instead of making several calls for a single item */
22657   if( sizeofULong <= nBuf - n ){
22658     ULONG ulSysInfo[QSV_MAX];
22659     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
22660
22661     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
22662     n += sizeofULong;
22663
22664     if( sizeofULong <= nBuf - n ){
22665       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
22666       n += sizeofULong;
22667     }
22668     if( sizeofULong <= nBuf - n ){
22669       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
22670       n += sizeofULong;
22671     }
22672     if( sizeofULong <= nBuf - n ){
22673       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
22674       n += sizeofULong;
22675     }
22676     if( sizeofULong <= nBuf - n ){
22677       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
22678       n += sizeofULong;
22679     }
22680   }
22681 #endif
22682
22683   return n;
22684 }
22685
22686 /*
22687 ** Sleep for a little while.  Return the amount of time slept.
22688 ** The argument is the number of microseconds we want to sleep.
22689 ** The return value is the number of microseconds of sleep actually
22690 ** requested from the underlying operating system, a number which
22691 ** might be greater than or equal to the argument, but not less
22692 ** than the argument.
22693 */
22694 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
22695   DosSleep( (microsec/1000) );
22696   return microsec;
22697 }
22698
22699 /*
22700 ** The following variable, if set to a non-zero value, becomes the result
22701 ** returned from sqlite3OsCurrentTime().  This is used for testing.
22702 */
22703 #ifdef SQLITE_TEST
22704 SQLITE_API int sqlite3_current_time = 0;
22705 #endif
22706
22707 /*
22708 ** Find the current time (in Universal Coordinated Time).  Write the
22709 ** current time and date as a Julian Day number into *prNow and
22710 ** return 0.  Return 1 if the time and date cannot be found.
22711 */
22712 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
22713   double now;
22714   SHORT minute; /* needs to be able to cope with negative timezone offset */
22715   USHORT second, hour,
22716          day, month, year;
22717   DATETIME dt;
22718   DosGetDateTime( &dt );
22719   second = (USHORT)dt.seconds;
22720   minute = (SHORT)dt.minutes + dt.timezone;
22721   hour = (USHORT)dt.hours;
22722   day = (USHORT)dt.day;
22723   month = (USHORT)dt.month;
22724   year = (USHORT)dt.year;
22725
22726   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
22727      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
22728   /* Calculate the Julian days */
22729   now = day - 32076 +
22730     1461*(year + 4800 + (month - 14)/12)/4 +
22731     367*(month - 2 - (month - 14)/12*12)/12 -
22732     3*((year + 4900 + (month - 14)/12)/100)/4;
22733
22734   /* Add the fractional hours, mins and seconds */
22735   now += (hour + 12.0)/24.0;
22736   now += minute/1440.0;
22737   now += second/86400.0;
22738   *prNow = now;
22739 #ifdef SQLITE_TEST
22740   if( sqlite3_current_time ){
22741     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
22742   }
22743 #endif
22744   return 0;
22745 }
22746
22747 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
22748   return 0;
22749 }
22750
22751 /*
22752 ** Initialize and deinitialize the operating system interface.
22753 */
22754 SQLITE_API int sqlite3_os_init(void){
22755   static sqlite3_vfs os2Vfs = {
22756     1,                 /* iVersion */
22757     sizeof(os2File),   /* szOsFile */
22758     CCHMAXPATH,        /* mxPathname */
22759     0,                 /* pNext */
22760     "os2",             /* zName */
22761     0,                 /* pAppData */
22762
22763     os2Open,           /* xOpen */
22764     os2Delete,         /* xDelete */
22765     os2Access,         /* xAccess */
22766     os2FullPathname,   /* xFullPathname */
22767     os2DlOpen,         /* xDlOpen */
22768     os2DlError,        /* xDlError */
22769     os2DlSym,          /* xDlSym */
22770     os2DlClose,        /* xDlClose */
22771     os2Randomness,     /* xRandomness */
22772     os2Sleep,          /* xSleep */
22773     os2CurrentTime,    /* xCurrentTime */
22774     os2GetLastError,   /* xGetLastError */
22775   };
22776   sqlite3_vfs_register(&os2Vfs, 1);
22777   initUconvObjects();
22778   return SQLITE_OK;
22779 }
22780 SQLITE_API int sqlite3_os_end(void){
22781   freeUconvObjects();
22782   return SQLITE_OK;
22783 }
22784
22785 #endif /* SQLITE_OS_OS2 */
22786
22787 /************** End of os_os2.c **********************************************/
22788 /************** Begin file os_unix.c *****************************************/
22789 /*
22790 ** 2004 May 22
22791 **
22792 ** The author disclaims copyright to this source code.  In place of
22793 ** a legal notice, here is a blessing:
22794 **
22795 **    May you do good and not evil.
22796 **    May you find forgiveness for yourself and forgive others.
22797 **    May you share freely, never taking more than you give.
22798 **
22799 ******************************************************************************
22800 **
22801 ** This file contains the VFS implementation for unix-like operating systems
22802 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22803 **
22804 ** There are actually several different VFS implementations in this file.
22805 ** The differences are in the way that file locking is done.  The default
22806 ** implementation uses Posix Advisory Locks.  Alternative implementations
22807 ** use flock(), dot-files, various proprietary locking schemas, or simply
22808 ** skip locking all together.
22809 **
22810 ** This source file is organized into divisions where the logic for various
22811 ** subfunctions is contained within the appropriate division.  PLEASE
22812 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22813 ** in the correct division and should be clearly labeled.
22814 **
22815 ** The layout of divisions is as follows:
22816 **
22817 **   *  General-purpose declarations and utility functions.
22818 **   *  Unique file ID logic used by VxWorks.
22819 **   *  Various locking primitive implementations (all except proxy locking):
22820 **      + for Posix Advisory Locks
22821 **      + for no-op locks
22822 **      + for dot-file locks
22823 **      + for flock() locking
22824 **      + for named semaphore locks (VxWorks only)
22825 **      + for AFP filesystem locks (MacOSX only)
22826 **   *  sqlite3_file methods not associated with locking.
22827 **   *  Definitions of sqlite3_io_methods objects for all locking
22828 **      methods plus "finder" functions for each locking method.
22829 **   *  sqlite3_vfs method implementations.
22830 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22831 **   *  Definitions of sqlite3_vfs objects for all locking methods
22832 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22833 */
22834 #if SQLITE_OS_UNIX              /* This file is used on unix only */
22835
22836 /*
22837 ** There are various methods for file locking used for concurrency
22838 ** control:
22839 **
22840 **   1. POSIX locking (the default),
22841 **   2. No locking,
22842 **   3. Dot-file locking,
22843 **   4. flock() locking,
22844 **   5. AFP locking (OSX only),
22845 **   6. Named POSIX semaphores (VXWorks only),
22846 **   7. proxy locking. (OSX only)
22847 **
22848 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22849 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22850 ** selection of the appropriate locking style based on the filesystem
22851 ** where the database is located.  
22852 */
22853 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22854 #  if defined(__APPLE__)
22855 #    define SQLITE_ENABLE_LOCKING_STYLE 1
22856 #  else
22857 #    define SQLITE_ENABLE_LOCKING_STYLE 0
22858 #  endif
22859 #endif
22860
22861 /*
22862 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
22863 ** vxworks, or 0 otherwise.
22864 */
22865 #ifndef OS_VXWORKS
22866 #  if defined(__RTP__) || defined(_WRS_KERNEL)
22867 #    define OS_VXWORKS 1
22868 #  else
22869 #    define OS_VXWORKS 0
22870 #  endif
22871 #endif
22872
22873 /*
22874 ** These #defines should enable >2GB file support on Posix if the
22875 ** underlying operating system supports it.  If the OS lacks
22876 ** large file support, these should be no-ops.
22877 **
22878 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22879 ** on the compiler command line.  This is necessary if you are compiling
22880 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22881 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22882 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22883 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22884 ** portability you should omit LFS.
22885 **
22886 ** The previous paragraph was written in 2005.  (This paragraph is written
22887 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22888 ** you should probably leave LFS enabled.  But some embedded platforms might
22889 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22890 */
22891 #ifndef SQLITE_DISABLE_LFS
22892 # define _LARGE_FILE       1
22893 # ifndef _FILE_OFFSET_BITS
22894 #   define _FILE_OFFSET_BITS 64
22895 # endif
22896 # define _LARGEFILE_SOURCE 1
22897 #endif
22898
22899 /*
22900 ** standard include files.
22901 */
22902 #include <sys/types.h>
22903 #include <sys/stat.h>
22904 #include <fcntl.h>
22905 #include <unistd.h>
22906 #include <sys/time.h>
22907 #include <errno.h>
22908 #include <sys/mman.h>
22909
22910 #if SQLITE_ENABLE_LOCKING_STYLE
22911 # include <sys/ioctl.h>
22912 # if OS_VXWORKS
22913 #  include <semaphore.h>
22914 #  include <limits.h>
22915 # else
22916 #  include <sys/file.h>
22917 #  include <sys/param.h>
22918 # endif
22919 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
22920
22921 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
22922 # include <sys/mount.h>
22923 #endif
22924
22925 /*
22926 ** Allowed values of unixFile.fsFlags
22927 */
22928 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
22929
22930 /*
22931 ** If we are to be thread-safe, include the pthreads header and define
22932 ** the SQLITE_UNIX_THREADS macro.
22933 */
22934 #if SQLITE_THREADSAFE
22935 # define SQLITE_UNIX_THREADS 1
22936 #endif
22937
22938 /*
22939 ** Default permissions when creating a new file
22940 */
22941 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
22942 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
22943 #endif
22944
22945 /*
22946  ** Default permissions when creating auto proxy dir
22947  */
22948 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
22949 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
22950 #endif
22951
22952 /*
22953 ** Maximum supported path-length.
22954 */
22955 #define MAX_PATHNAME 512
22956
22957 /*
22958 ** Only set the lastErrno if the error code is a real error and not 
22959 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
22960 */
22961 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
22962
22963 /* Forward references */
22964 typedef struct unixShm unixShm;               /* Connection shared memory */
22965 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
22966 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
22967 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
22968
22969 /*
22970 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
22971 ** cannot be closed immediately. In these cases, instances of the following
22972 ** structure are used to store the file descriptor while waiting for an
22973 ** opportunity to either close or reuse it.
22974 */
22975 struct UnixUnusedFd {
22976   int fd;                   /* File descriptor to close */
22977   int flags;                /* Flags this file descriptor was opened with */
22978   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
22979 };
22980
22981 /*
22982 ** The unixFile structure is subclass of sqlite3_file specific to the unix
22983 ** VFS implementations.
22984 */
22985 typedef struct unixFile unixFile;
22986 struct unixFile {
22987   sqlite3_io_methods const *pMethod;  /* Always the first entry */
22988   unixInodeInfo *pInode;              /* Info about locks on this inode */
22989   int h;                              /* The file descriptor */
22990   int dirfd;                          /* File descriptor for the directory */
22991   unsigned char eFileLock;            /* The type of lock held on this fd */
22992   int lastErrno;                      /* The unix errno from last I/O error */
22993   void *lockingContext;               /* Locking style specific state */
22994   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
22995   int fileFlags;                      /* Miscellanous flags */
22996   const char *zPath;                  /* Name of the file */
22997   unixShm *pShm;                      /* Shared memory segment information */
22998   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
22999 #if SQLITE_ENABLE_LOCKING_STYLE
23000   int openFlags;                      /* The flags specified at open() */
23001 #endif
23002 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
23003   unsigned fsFlags;                   /* cached details from statfs() */
23004 #endif
23005 #if OS_VXWORKS
23006   int isDelete;                       /* Delete on close if true */
23007   struct vxworksFileId *pId;          /* Unique file ID */
23008 #endif
23009 #ifndef NDEBUG
23010   /* The next group of variables are used to track whether or not the
23011   ** transaction counter in bytes 24-27 of database files are updated
23012   ** whenever any part of the database changes.  An assertion fault will
23013   ** occur if a file is updated without also updating the transaction
23014   ** counter.  This test is made to avoid new problems similar to the
23015   ** one described by ticket #3584. 
23016   */
23017   unsigned char transCntrChng;   /* True if the transaction counter changed */
23018   unsigned char dbUpdate;        /* True if any part of database file changed */
23019   unsigned char inNormalWrite;   /* True if in a normal write operation */
23020 #endif
23021 #ifdef SQLITE_TEST
23022   /* In test mode, increase the size of this structure a bit so that 
23023   ** it is larger than the struct CrashFile defined in test6.c.
23024   */
23025   char aPadding[32];
23026 #endif
23027 };
23028
23029 /*
23030 ** The following macros define bits in unixFile.fileFlags
23031 */
23032 #define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
23033
23034 /*
23035 ** Include code that is common to all os_*.c files
23036 */
23037 /************** Include os_common.h in the middle of os_unix.c ***************/
23038 /************** Begin file os_common.h ***************************************/
23039 /*
23040 ** 2004 May 22
23041 **
23042 ** The author disclaims copyright to this source code.  In place of
23043 ** a legal notice, here is a blessing:
23044 **
23045 **    May you do good and not evil.
23046 **    May you find forgiveness for yourself and forgive others.
23047 **    May you share freely, never taking more than you give.
23048 **
23049 ******************************************************************************
23050 **
23051 ** This file contains macros and a little bit of code that is common to
23052 ** all of the platform-specific files (os_*.c) and is #included into those
23053 ** files.
23054 **
23055 ** This file should be #included by the os_*.c files only.  It is not a
23056 ** general purpose header file.
23057 */
23058 #ifndef _OS_COMMON_H_
23059 #define _OS_COMMON_H_
23060
23061 /*
23062 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23063 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23064 ** switch.  The following code should catch this problem at compile-time.
23065 */
23066 #ifdef MEMORY_DEBUG
23067 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
23068 #endif
23069
23070 #ifdef SQLITE_DEBUG
23071 SQLITE_PRIVATE int sqlite3OSTrace = 0;
23072 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
23073 #else
23074 #define OSTRACE(X)
23075 #endif
23076
23077 /*
23078 ** Macros for performance tracing.  Normally turned off.  Only works
23079 ** on i486 hardware.
23080 */
23081 #ifdef SQLITE_PERFORMANCE_TRACE
23082
23083 /* 
23084 ** hwtime.h contains inline assembler code for implementing 
23085 ** high-performance timing routines.
23086 */
23087 /************** Include hwtime.h in the middle of os_common.h ****************/
23088 /************** Begin file hwtime.h ******************************************/
23089 /*
23090 ** 2008 May 27
23091 **
23092 ** The author disclaims copyright to this source code.  In place of
23093 ** a legal notice, here is a blessing:
23094 **
23095 **    May you do good and not evil.
23096 **    May you find forgiveness for yourself and forgive others.
23097 **    May you share freely, never taking more than you give.
23098 **
23099 ******************************************************************************
23100 **
23101 ** This file contains inline asm code for retrieving "high-performance"
23102 ** counters for x86 class CPUs.
23103 */
23104 #ifndef _HWTIME_H_
23105 #define _HWTIME_H_
23106
23107 /*
23108 ** The following routine only works on pentium-class (or newer) processors.
23109 ** It uses the RDTSC opcode to read the cycle count value out of the
23110 ** processor and returns that value.  This can be used for high-res
23111 ** profiling.
23112 */
23113 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23114       (defined(i386) || defined(__i386__) || defined(_M_IX86))
23115
23116   #if defined(__GNUC__)
23117
23118   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23119      unsigned int lo, hi;
23120      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23121      return (sqlite_uint64)hi << 32 | lo;
23122   }
23123
23124   #elif defined(_MSC_VER)
23125
23126   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23127      __asm {
23128         rdtsc
23129         ret       ; return value at EDX:EAX
23130      }
23131   }
23132
23133   #endif
23134
23135 #elif (defined(__GNUC__) && defined(__x86_64__))
23136
23137   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23138       unsigned long val;
23139       __asm__ __volatile__ ("rdtsc" : "=A" (val));
23140       return val;
23141   }
23142  
23143 #elif (defined(__GNUC__) && defined(__ppc__))
23144
23145   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23146       unsigned long long retval;
23147       unsigned long junk;
23148       __asm__ __volatile__ ("\n\
23149           1:      mftbu   %1\n\
23150                   mftb    %L0\n\
23151                   mftbu   %0\n\
23152                   cmpw    %0,%1\n\
23153                   bne     1b"
23154                   : "=r" (retval), "=r" (junk));
23155       return retval;
23156   }
23157
23158 #else
23159
23160   #error Need implementation of sqlite3Hwtime() for your platform.
23161
23162   /*
23163   ** To compile without implementing sqlite3Hwtime() for your platform,
23164   ** you can remove the above #error and use the following
23165   ** stub function.  You will lose timing support for many
23166   ** of the debugging and testing utilities, but it should at
23167   ** least compile and run.
23168   */
23169 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23170
23171 #endif
23172
23173 #endif /* !defined(_HWTIME_H_) */
23174
23175 /************** End of hwtime.h **********************************************/
23176 /************** Continuing where we left off in os_common.h ******************/
23177
23178 static sqlite_uint64 g_start;
23179 static sqlite_uint64 g_elapsed;
23180 #define TIMER_START       g_start=sqlite3Hwtime()
23181 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23182 #define TIMER_ELAPSED     g_elapsed
23183 #else
23184 #define TIMER_START
23185 #define TIMER_END
23186 #define TIMER_ELAPSED     ((sqlite_uint64)0)
23187 #endif
23188
23189 /*
23190 ** If we compile with the SQLITE_TEST macro set, then the following block
23191 ** of code will give us the ability to simulate a disk I/O error.  This
23192 ** is used for testing the I/O recovery logic.
23193 */
23194 #ifdef SQLITE_TEST
23195 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
23196 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
23197 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
23198 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
23199 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
23200 SQLITE_API int sqlite3_diskfull_pending = 0;
23201 SQLITE_API int sqlite3_diskfull = 0;
23202 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23203 #define SimulateIOError(CODE)  \
23204   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23205        || sqlite3_io_error_pending-- == 1 )  \
23206               { local_ioerr(); CODE; }
23207 static void local_ioerr(){
23208   IOTRACE(("IOERR\n"));
23209   sqlite3_io_error_hit++;
23210   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23211 }
23212 #define SimulateDiskfullError(CODE) \
23213    if( sqlite3_diskfull_pending ){ \
23214      if( sqlite3_diskfull_pending == 1 ){ \
23215        local_ioerr(); \
23216        sqlite3_diskfull = 1; \
23217        sqlite3_io_error_hit = 1; \
23218        CODE; \
23219      }else{ \
23220        sqlite3_diskfull_pending--; \
23221      } \
23222    }
23223 #else
23224 #define SimulateIOErrorBenign(X)
23225 #define SimulateIOError(A)
23226 #define SimulateDiskfullError(A)
23227 #endif
23228
23229 /*
23230 ** When testing, keep a count of the number of open files.
23231 */
23232 #ifdef SQLITE_TEST
23233 SQLITE_API int sqlite3_open_file_count = 0;
23234 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23235 #else
23236 #define OpenCounter(X)
23237 #endif
23238
23239 #endif /* !defined(_OS_COMMON_H_) */
23240
23241 /************** End of os_common.h *******************************************/
23242 /************** Continuing where we left off in os_unix.c ********************/
23243
23244 /*
23245 ** Define various macros that are missing from some systems.
23246 */
23247 #ifndef O_LARGEFILE
23248 # define O_LARGEFILE 0
23249 #endif
23250 #ifdef SQLITE_DISABLE_LFS
23251 # undef O_LARGEFILE
23252 # define O_LARGEFILE 0
23253 #endif
23254 #ifndef O_NOFOLLOW
23255 # define O_NOFOLLOW 0
23256 #endif
23257 #ifndef O_BINARY
23258 # define O_BINARY 0
23259 #endif
23260
23261 /*
23262 ** The DJGPP compiler environment looks mostly like Unix, but it
23263 ** lacks the fcntl() system call.  So redefine fcntl() to be something
23264 ** that always succeeds.  This means that locking does not occur under
23265 ** DJGPP.  But it is DOS - what did you expect?
23266 */
23267 #ifdef __DJGPP__
23268 # define fcntl(A,B,C) 0
23269 #endif
23270
23271 /*
23272 ** The threadid macro resolves to the thread-id or to 0.  Used for
23273 ** testing and debugging only.
23274 */
23275 #if SQLITE_THREADSAFE
23276 #define threadid pthread_self()
23277 #else
23278 #define threadid 0
23279 #endif
23280
23281
23282 /*
23283 ** Helper functions to obtain and relinquish the global mutex. The
23284 ** global mutex is used to protect the unixInodeInfo and
23285 ** vxworksFileId objects used by this file, all of which may be 
23286 ** shared by multiple threads.
23287 **
23288 ** Function unixMutexHeld() is used to assert() that the global mutex 
23289 ** is held when required. This function is only used as part of assert() 
23290 ** statements. e.g.
23291 **
23292 **   unixEnterMutex()
23293 **     assert( unixMutexHeld() );
23294 **   unixEnterLeave()
23295 */
23296 static void unixEnterMutex(void){
23297   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23298 }
23299 static void unixLeaveMutex(void){
23300   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23301 }
23302 #ifdef SQLITE_DEBUG
23303 static int unixMutexHeld(void) {
23304   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23305 }
23306 #endif
23307
23308
23309 #ifdef SQLITE_DEBUG
23310 /*
23311 ** Helper function for printing out trace information from debugging
23312 ** binaries. This returns the string represetation of the supplied
23313 ** integer lock-type.
23314 */
23315 static const char *azFileLock(int eFileLock){
23316   switch( eFileLock ){
23317     case NO_LOCK: return "NONE";
23318     case SHARED_LOCK: return "SHARED";
23319     case RESERVED_LOCK: return "RESERVED";
23320     case PENDING_LOCK: return "PENDING";
23321     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23322   }
23323   return "ERROR";
23324 }
23325 #endif
23326
23327 #ifdef SQLITE_LOCK_TRACE
23328 /*
23329 ** Print out information about all locking operations.
23330 **
23331 ** This routine is used for troubleshooting locks on multithreaded
23332 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
23333 ** command-line option on the compiler.  This code is normally
23334 ** turned off.
23335 */
23336 static int lockTrace(int fd, int op, struct flock *p){
23337   char *zOpName, *zType;
23338   int s;
23339   int savedErrno;
23340   if( op==F_GETLK ){
23341     zOpName = "GETLK";
23342   }else if( op==F_SETLK ){
23343     zOpName = "SETLK";
23344   }else{
23345     s = fcntl(fd, op, p);
23346     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23347     return s;
23348   }
23349   if( p->l_type==F_RDLCK ){
23350     zType = "RDLCK";
23351   }else if( p->l_type==F_WRLCK ){
23352     zType = "WRLCK";
23353   }else if( p->l_type==F_UNLCK ){
23354     zType = "UNLCK";
23355   }else{
23356     assert( 0 );
23357   }
23358   assert( p->l_whence==SEEK_SET );
23359   s = fcntl(fd, op, p);
23360   savedErrno = errno;
23361   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
23362      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
23363      (int)p->l_pid, s);
23364   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
23365     struct flock l2;
23366     l2 = *p;
23367     fcntl(fd, F_GETLK, &l2);
23368     if( l2.l_type==F_RDLCK ){
23369       zType = "RDLCK";
23370     }else if( l2.l_type==F_WRLCK ){
23371       zType = "WRLCK";
23372     }else if( l2.l_type==F_UNLCK ){
23373       zType = "UNLCK";
23374     }else{
23375       assert( 0 );
23376     }
23377     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23378        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23379   }
23380   errno = savedErrno;
23381   return s;
23382 }
23383 #define fcntl lockTrace
23384 #endif /* SQLITE_LOCK_TRACE */
23385
23386
23387
23388 /*
23389 ** This routine translates a standard POSIX errno code into something
23390 ** useful to the clients of the sqlite3 functions.  Specifically, it is
23391 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
23392 ** and a variety of "please close the file descriptor NOW" errors into 
23393 ** SQLITE_IOERR
23394 ** 
23395 ** Errors during initialization of locks, or file system support for locks,
23396 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23397 */
23398 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23399   switch (posixError) {
23400   case 0: 
23401     return SQLITE_OK;
23402     
23403   case EAGAIN:
23404   case ETIMEDOUT:
23405   case EBUSY:
23406   case EINTR:
23407   case ENOLCK:  
23408     /* random NFS retry error, unless during file system support 
23409      * introspection, in which it actually means what it says */
23410     return SQLITE_BUSY;
23411     
23412   case EACCES: 
23413     /* EACCES is like EAGAIN during locking operations, but not any other time*/
23414     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
23415         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
23416         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23417         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23418       return SQLITE_BUSY;
23419     }
23420     /* else fall through */
23421   case EPERM: 
23422     return SQLITE_PERM;
23423     
23424   case EDEADLK:
23425     return SQLITE_IOERR_BLOCKED;
23426     
23427 #if EOPNOTSUPP!=ENOTSUP
23428   case EOPNOTSUPP: 
23429     /* something went terribly awry, unless during file system support 
23430      * introspection, in which it actually means what it says */
23431 #endif
23432 #ifdef ENOTSUP
23433   case ENOTSUP: 
23434     /* invalid fd, unless during file system support introspection, in which 
23435      * it actually means what it says */
23436 #endif
23437   case EIO:
23438   case EBADF:
23439   case EINVAL:
23440   case ENOTCONN:
23441   case ENODEV:
23442   case ENXIO:
23443   case ENOENT:
23444   case ESTALE:
23445   case ENOSYS:
23446     /* these should force the client to close the file and reconnect */
23447     
23448   default: 
23449     return sqliteIOErr;
23450   }
23451 }
23452
23453
23454
23455 /******************************************************************************
23456 ****************** Begin Unique File ID Utility Used By VxWorks ***************
23457 **
23458 ** On most versions of unix, we can get a unique ID for a file by concatenating
23459 ** the device number and the inode number.  But this does not work on VxWorks.
23460 ** On VxWorks, a unique file id must be based on the canonical filename.
23461 **
23462 ** A pointer to an instance of the following structure can be used as a
23463 ** unique file ID in VxWorks.  Each instance of this structure contains
23464 ** a copy of the canonical filename.  There is also a reference count.  
23465 ** The structure is reclaimed when the number of pointers to it drops to
23466 ** zero.
23467 **
23468 ** There are never very many files open at one time and lookups are not
23469 ** a performance-critical path, so it is sufficient to put these
23470 ** structures on a linked list.
23471 */
23472 struct vxworksFileId {
23473   struct vxworksFileId *pNext;  /* Next in a list of them all */
23474   int nRef;                     /* Number of references to this one */
23475   int nName;                    /* Length of the zCanonicalName[] string */
23476   char *zCanonicalName;         /* Canonical filename */
23477 };
23478
23479 #if OS_VXWORKS
23480 /* 
23481 ** All unique filenames are held on a linked list headed by this
23482 ** variable:
23483 */
23484 static struct vxworksFileId *vxworksFileList = 0;
23485
23486 /*
23487 ** Simplify a filename into its canonical form
23488 ** by making the following changes:
23489 **
23490 **  * removing any trailing and duplicate /
23491 **  * convert /./ into just /
23492 **  * convert /A/../ where A is any simple name into just /
23493 **
23494 ** Changes are made in-place.  Return the new name length.
23495 **
23496 ** The original filename is in z[0..n-1].  Return the number of
23497 ** characters in the simplified name.
23498 */
23499 static int vxworksSimplifyName(char *z, int n){
23500   int i, j;
23501   while( n>1 && z[n-1]=='/' ){ n--; }
23502   for(i=j=0; i<n; i++){
23503     if( z[i]=='/' ){
23504       if( z[i+1]=='/' ) continue;
23505       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23506         i += 1;
23507         continue;
23508       }
23509       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23510         while( j>0 && z[j-1]!='/' ){ j--; }
23511         if( j>0 ){ j--; }
23512         i += 2;
23513         continue;
23514       }
23515     }
23516     z[j++] = z[i];
23517   }
23518   z[j] = 0;
23519   return j;
23520 }
23521
23522 /*
23523 ** Find a unique file ID for the given absolute pathname.  Return
23524 ** a pointer to the vxworksFileId object.  This pointer is the unique
23525 ** file ID.
23526 **
23527 ** The nRef field of the vxworksFileId object is incremented before
23528 ** the object is returned.  A new vxworksFileId object is created
23529 ** and added to the global list if necessary.
23530 **
23531 ** If a memory allocation error occurs, return NULL.
23532 */
23533 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23534   struct vxworksFileId *pNew;         /* search key and new file ID */
23535   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
23536   int n;                              /* Length of zAbsoluteName string */
23537
23538   assert( zAbsoluteName[0]=='/' );
23539   n = (int)strlen(zAbsoluteName);
23540   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23541   if( pNew==0 ) return 0;
23542   pNew->zCanonicalName = (char*)&pNew[1];
23543   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23544   n = vxworksSimplifyName(pNew->zCanonicalName, n);
23545
23546   /* Search for an existing entry that matching the canonical name.
23547   ** If found, increment the reference count and return a pointer to
23548   ** the existing file ID.
23549   */
23550   unixEnterMutex();
23551   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23552     if( pCandidate->nName==n 
23553      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23554     ){
23555        sqlite3_free(pNew);
23556        pCandidate->nRef++;
23557        unixLeaveMutex();
23558        return pCandidate;
23559     }
23560   }
23561
23562   /* No match was found.  We will make a new file ID */
23563   pNew->nRef = 1;
23564   pNew->nName = n;
23565   pNew->pNext = vxworksFileList;
23566   vxworksFileList = pNew;
23567   unixLeaveMutex();
23568   return pNew;
23569 }
23570
23571 /*
23572 ** Decrement the reference count on a vxworksFileId object.  Free
23573 ** the object when the reference count reaches zero.
23574 */
23575 static void vxworksReleaseFileId(struct vxworksFileId *pId){
23576   unixEnterMutex();
23577   assert( pId->nRef>0 );
23578   pId->nRef--;
23579   if( pId->nRef==0 ){
23580     struct vxworksFileId **pp;
23581     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
23582     assert( *pp==pId );
23583     *pp = pId->pNext;
23584     sqlite3_free(pId);
23585   }
23586   unixLeaveMutex();
23587 }
23588 #endif /* OS_VXWORKS */
23589 /*************** End of Unique File ID Utility Used By VxWorks ****************
23590 ******************************************************************************/
23591
23592
23593 /******************************************************************************
23594 *************************** Posix Advisory Locking ****************************
23595 **
23596 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
23597 ** section 6.5.2.2 lines 483 through 490 specify that when a process
23598 ** sets or clears a lock, that operation overrides any prior locks set
23599 ** by the same process.  It does not explicitly say so, but this implies
23600 ** that it overrides locks set by the same process using a different
23601 ** file descriptor.  Consider this test case:
23602 **
23603 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
23604 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
23605 **
23606 ** Suppose ./file1 and ./file2 are really the same file (because
23607 ** one is a hard or symbolic link to the other) then if you set
23608 ** an exclusive lock on fd1, then try to get an exclusive lock
23609 ** on fd2, it works.  I would have expected the second lock to
23610 ** fail since there was already a lock on the file due to fd1.
23611 ** But not so.  Since both locks came from the same process, the
23612 ** second overrides the first, even though they were on different
23613 ** file descriptors opened on different file names.
23614 **
23615 ** This means that we cannot use POSIX locks to synchronize file access
23616 ** among competing threads of the same process.  POSIX locks will work fine
23617 ** to synchronize access for threads in separate processes, but not
23618 ** threads within the same process.
23619 **
23620 ** To work around the problem, SQLite has to manage file locks internally
23621 ** on its own.  Whenever a new database is opened, we have to find the
23622 ** specific inode of the database file (the inode is determined by the
23623 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
23624 ** and check for locks already existing on that inode.  When locks are
23625 ** created or removed, we have to look at our own internal record of the
23626 ** locks to see if another thread has previously set a lock on that same
23627 ** inode.
23628 **
23629 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
23630 ** For VxWorks, we have to use the alternative unique ID system based on
23631 ** canonical filename and implemented in the previous division.)
23632 **
23633 ** The sqlite3_file structure for POSIX is no longer just an integer file
23634 ** descriptor.  It is now a structure that holds the integer file
23635 ** descriptor and a pointer to a structure that describes the internal
23636 ** locks on the corresponding inode.  There is one locking structure
23637 ** per inode, so if the same inode is opened twice, both unixFile structures
23638 ** point to the same locking structure.  The locking structure keeps
23639 ** a reference count (so we will know when to delete it) and a "cnt"
23640 ** field that tells us its internal lock status.  cnt==0 means the
23641 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
23642 ** cnt>0 means there are cnt shared locks on the file.
23643 **
23644 ** Any attempt to lock or unlock a file first checks the locking
23645 ** structure.  The fcntl() system call is only invoked to set a 
23646 ** POSIX lock if the internal lock structure transitions between
23647 ** a locked and an unlocked state.
23648 **
23649 ** But wait:  there are yet more problems with POSIX advisory locks.
23650 **
23651 ** If you close a file descriptor that points to a file that has locks,
23652 ** all locks on that file that are owned by the current process are
23653 ** released.  To work around this problem, each unixInodeInfo object
23654 ** maintains a count of the number of pending locks on tha inode.
23655 ** When an attempt is made to close an unixFile, if there are
23656 ** other unixFile open on the same inode that are holding locks, the call
23657 ** to close() the file descriptor is deferred until all of the locks clear.
23658 ** The unixInodeInfo structure keeps a list of file descriptors that need to
23659 ** be closed and that list is walked (and cleared) when the last lock
23660 ** clears.
23661 **
23662 ** Yet another problem:  LinuxThreads do not play well with posix locks.
23663 **
23664 ** Many older versions of linux use the LinuxThreads library which is
23665 ** not posix compliant.  Under LinuxThreads, a lock created by thread
23666 ** A cannot be modified or overridden by a different thread B.
23667 ** Only thread A can modify the lock.  Locking behavior is correct
23668 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
23669 ** on linux - with NPTL a lock created by thread A can override locks
23670 ** in thread B.  But there is no way to know at compile-time which
23671 ** threading library is being used.  So there is no way to know at
23672 ** compile-time whether or not thread A can override locks on thread B.
23673 ** One has to do a run-time check to discover the behavior of the
23674 ** current process.
23675 **
23676 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
23677 ** was dropped beginning with version 3.7.0.  SQLite will still work with
23678 ** LinuxThreads provided that (1) there is no more than one connection 
23679 ** per database file in the same process and (2) database connections
23680 ** do not move across threads.
23681 */
23682
23683 /*
23684 ** An instance of the following structure serves as the key used
23685 ** to locate a particular unixInodeInfo object.
23686 */
23687 struct unixFileId {
23688   dev_t dev;                  /* Device number */
23689 #if OS_VXWORKS
23690   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
23691 #else
23692   ino_t ino;                  /* Inode number */
23693 #endif
23694 };
23695
23696 /*
23697 ** An instance of the following structure is allocated for each open
23698 ** inode.  Or, on LinuxThreads, there is one of these structures for
23699 ** each inode opened by each thread.
23700 **
23701 ** A single inode can have multiple file descriptors, so each unixFile
23702 ** structure contains a pointer to an instance of this object and this
23703 ** object keeps a count of the number of unixFile pointing to it.
23704 */
23705 struct unixInodeInfo {
23706   struct unixFileId fileId;       /* The lookup key */
23707   int nShared;                    /* Number of SHARED locks held */
23708   int eFileLock;                  /* One of SHARED_LOCK, RESERVED_LOCK etc. */
23709   int nRef;                       /* Number of pointers to this structure */
23710   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
23711   int nLock;                      /* Number of outstanding file locks */
23712   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
23713   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
23714   unixInodeInfo *pPrev;           /*    .... doubly linked */
23715 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
23716   unsigned long long sharedByte;  /* for AFP simulated shared lock */
23717 #endif
23718 #if OS_VXWORKS
23719   sem_t *pSem;                    /* Named POSIX semaphore */
23720   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
23721 #endif
23722 };
23723
23724 /*
23725 ** A lists of all unixInodeInfo objects.
23726 */
23727 static unixInodeInfo *inodeList = 0;
23728
23729 /*
23730 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
23731 ** If all such file descriptors are closed without error, the list is
23732 ** cleared and SQLITE_OK returned.
23733 **
23734 ** Otherwise, if an error occurs, then successfully closed file descriptor
23735 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned. 
23736 ** not deleted and SQLITE_IOERR_CLOSE returned.
23737 */ 
23738 static int closePendingFds(unixFile *pFile){
23739   int rc = SQLITE_OK;
23740   unixInodeInfo *pInode = pFile->pInode;
23741   UnixUnusedFd *pError = 0;
23742   UnixUnusedFd *p;
23743   UnixUnusedFd *pNext;
23744   for(p=pInode->pUnused; p; p=pNext){
23745     pNext = p->pNext;
23746     if( close(p->fd) ){
23747       pFile->lastErrno = errno;
23748       rc = SQLITE_IOERR_CLOSE;
23749       p->pNext = pError;
23750       pError = p;
23751     }else{
23752       sqlite3_free(p);
23753     }
23754   }
23755   pInode->pUnused = pError;
23756   return rc;
23757 }
23758
23759 /*
23760 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
23761 **
23762 ** The mutex entered using the unixEnterMutex() function must be held
23763 ** when this function is called.
23764 */
23765 static void releaseInodeInfo(unixFile *pFile){
23766   unixInodeInfo *pInode = pFile->pInode;
23767   assert( unixMutexHeld() );
23768   if( pInode ){
23769     pInode->nRef--;
23770     if( pInode->nRef==0 ){
23771       assert( pInode->pShmNode==0 );
23772       closePendingFds(pFile);
23773       if( pInode->pPrev ){
23774         assert( pInode->pPrev->pNext==pInode );
23775         pInode->pPrev->pNext = pInode->pNext;
23776       }else{
23777         assert( inodeList==pInode );
23778         inodeList = pInode->pNext;
23779       }
23780       if( pInode->pNext ){
23781         assert( pInode->pNext->pPrev==pInode );
23782         pInode->pNext->pPrev = pInode->pPrev;
23783       }
23784       sqlite3_free(pInode);
23785     }
23786   }
23787 }
23788
23789 /*
23790 ** Given a file descriptor, locate the unixInodeInfo object that
23791 ** describes that file descriptor.  Create a new one if necessary.  The
23792 ** return value might be uninitialized if an error occurs.
23793 **
23794 ** The mutex entered using the unixEnterMutex() function must be held
23795 ** when this function is called.
23796 **
23797 ** Return an appropriate error code.
23798 */
23799 static int findInodeInfo(
23800   unixFile *pFile,               /* Unix file with file desc used in the key */
23801   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
23802 ){
23803   int rc;                        /* System call return code */
23804   int fd;                        /* The file descriptor for pFile */
23805   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
23806   struct stat statbuf;           /* Low-level file information */
23807   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
23808
23809   assert( unixMutexHeld() );
23810
23811   /* Get low-level information about the file that we can used to
23812   ** create a unique name for the file.
23813   */
23814   fd = pFile->h;
23815   rc = fstat(fd, &statbuf);
23816   if( rc!=0 ){
23817     pFile->lastErrno = errno;
23818 #ifdef EOVERFLOW
23819     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
23820 #endif
23821     return SQLITE_IOERR;
23822   }
23823
23824 #ifdef __APPLE__
23825   /* On OS X on an msdos filesystem, the inode number is reported
23826   ** incorrectly for zero-size files.  See ticket #3260.  To work
23827   ** around this problem (we consider it a bug in OS X, not SQLite)
23828   ** we always increase the file size to 1 by writing a single byte
23829   ** prior to accessing the inode number.  The one byte written is
23830   ** an ASCII 'S' character which also happens to be the first byte
23831   ** in the header of every SQLite database.  In this way, if there
23832   ** is a race condition such that another thread has already populated
23833   ** the first page of the database, no damage is done.
23834   */
23835   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
23836     rc = write(fd, "S", 1);
23837     if( rc!=1 ){
23838       pFile->lastErrno = errno;
23839       return SQLITE_IOERR;
23840     }
23841     rc = fstat(fd, &statbuf);
23842     if( rc!=0 ){
23843       pFile->lastErrno = errno;
23844       return SQLITE_IOERR;
23845     }
23846   }
23847 #endif
23848
23849   memset(&fileId, 0, sizeof(fileId));
23850   fileId.dev = statbuf.st_dev;
23851 #if OS_VXWORKS
23852   fileId.pId = pFile->pId;
23853 #else
23854   fileId.ino = statbuf.st_ino;
23855 #endif
23856   pInode = inodeList;
23857   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
23858     pInode = pInode->pNext;
23859   }
23860   if( pInode==0 ){
23861     pInode = sqlite3_malloc( sizeof(*pInode) );
23862     if( pInode==0 ){
23863       return SQLITE_NOMEM;
23864     }
23865     memset(pInode, 0, sizeof(*pInode));
23866     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
23867     pInode->nRef = 1;
23868     pInode->pNext = inodeList;
23869     pInode->pPrev = 0;
23870     if( inodeList ) inodeList->pPrev = pInode;
23871     inodeList = pInode;
23872   }else{
23873     pInode->nRef++;
23874   }
23875   *ppInode = pInode;
23876   return SQLITE_OK;
23877 }
23878
23879
23880 /*
23881 ** This routine checks if there is a RESERVED lock held on the specified
23882 ** file by this or any other process. If such a lock is held, set *pResOut
23883 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23884 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23885 */
23886 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23887   int rc = SQLITE_OK;
23888   int reserved = 0;
23889   unixFile *pFile = (unixFile*)id;
23890
23891   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23892
23893   assert( pFile );
23894   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
23895
23896   /* Check if a thread in this process holds such a lock */
23897   if( pFile->pInode->eFileLock>SHARED_LOCK ){
23898     reserved = 1;
23899   }
23900
23901   /* Otherwise see if some other process holds it.
23902   */
23903 #ifndef __DJGPP__
23904   if( !reserved ){
23905     struct flock lock;
23906     lock.l_whence = SEEK_SET;
23907     lock.l_start = RESERVED_BYTE;
23908     lock.l_len = 1;
23909     lock.l_type = F_WRLCK;
23910     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23911       int tErrno = errno;
23912       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23913       pFile->lastErrno = tErrno;
23914     } else if( lock.l_type!=F_UNLCK ){
23915       reserved = 1;
23916     }
23917   }
23918 #endif
23919   
23920   unixLeaveMutex();
23921   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
23922
23923   *pResOut = reserved;
23924   return rc;
23925 }
23926
23927 /*
23928 ** Lock the file with the lock specified by parameter eFileLock - one
23929 ** of the following:
23930 **
23931 **     (1) SHARED_LOCK
23932 **     (2) RESERVED_LOCK
23933 **     (3) PENDING_LOCK
23934 **     (4) EXCLUSIVE_LOCK
23935 **
23936 ** Sometimes when requesting one lock state, additional lock states
23937 ** are inserted in between.  The locking might fail on one of the later
23938 ** transitions leaving the lock state different from what it started but
23939 ** still short of its goal.  The following chart shows the allowed
23940 ** transitions and the inserted intermediate states:
23941 **
23942 **    UNLOCKED -> SHARED
23943 **    SHARED -> RESERVED
23944 **    SHARED -> (PENDING) -> EXCLUSIVE
23945 **    RESERVED -> (PENDING) -> EXCLUSIVE
23946 **    PENDING -> EXCLUSIVE
23947 **
23948 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23949 ** routine to lower a locking level.
23950 */
23951 static int unixLock(sqlite3_file *id, int eFileLock){
23952   /* The following describes the implementation of the various locks and
23953   ** lock transitions in terms of the POSIX advisory shared and exclusive
23954   ** lock primitives (called read-locks and write-locks below, to avoid
23955   ** confusion with SQLite lock names). The algorithms are complicated
23956   ** slightly in order to be compatible with windows systems simultaneously
23957   ** accessing the same database file, in case that is ever required.
23958   **
23959   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
23960   ** byte', each single bytes at well known offsets, and the 'shared byte
23961   ** range', a range of 510 bytes at a well known offset.
23962   **
23963   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
23964   ** byte'.  If this is successful, a random byte from the 'shared byte
23965   ** range' is read-locked and the lock on the 'pending byte' released.
23966   **
23967   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
23968   ** A RESERVED lock is implemented by grabbing a write-lock on the
23969   ** 'reserved byte'. 
23970   **
23971   ** A process may only obtain a PENDING lock after it has obtained a
23972   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
23973   ** on the 'pending byte'. This ensures that no new SHARED locks can be
23974   ** obtained, but existing SHARED locks are allowed to persist. A process
23975   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
23976   ** This property is used by the algorithm for rolling back a journal file
23977   ** after a crash.
23978   **
23979   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
23980   ** implemented by obtaining a write-lock on the entire 'shared byte
23981   ** range'. Since all other locks require a read-lock on one of the bytes
23982   ** within this range, this ensures that no other locks are held on the
23983   ** database. 
23984   **
23985   ** The reason a single byte cannot be used instead of the 'shared byte
23986   ** range' is that some versions of windows do not support read-locks. By
23987   ** locking a random byte from a range, concurrent SHARED locks may exist
23988   ** even if the locking primitive used is always a write-lock.
23989   */
23990   int rc = SQLITE_OK;
23991   unixFile *pFile = (unixFile*)id;
23992   unixInodeInfo *pInode = pFile->pInode;
23993   struct flock lock;
23994   int s = 0;
23995   int tErrno = 0;
23996
23997   assert( pFile );
23998   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
23999       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24000       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
24001
24002   /* If there is already a lock of this type or more restrictive on the
24003   ** unixFile, do nothing. Don't use the end_lock: exit path, as
24004   ** unixEnterMutex() hasn't been called yet.
24005   */
24006   if( pFile->eFileLock>=eFileLock ){
24007     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
24008             azFileLock(eFileLock)));
24009     return SQLITE_OK;
24010   }
24011
24012   /* Make sure the locking sequence is correct.
24013   **  (1) We never move from unlocked to anything higher than shared lock.
24014   **  (2) SQLite never explicitly requests a pendig lock.
24015   **  (3) A shared lock is always held when a reserve lock is requested.
24016   */
24017   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24018   assert( eFileLock!=PENDING_LOCK );
24019   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24020
24021   /* This mutex is needed because pFile->pInode is shared across threads
24022   */
24023   unixEnterMutex();
24024   pInode = pFile->pInode;
24025
24026   /* If some thread using this PID has a lock via a different unixFile*
24027   ** handle that precludes the requested lock, return BUSY.
24028   */
24029   if( (pFile->eFileLock!=pInode->eFileLock && 
24030           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24031   ){
24032     rc = SQLITE_BUSY;
24033     goto end_lock;
24034   }
24035
24036   /* If a SHARED lock is requested, and some thread using this PID already
24037   ** has a SHARED or RESERVED lock, then increment reference counts and
24038   ** return SQLITE_OK.
24039   */
24040   if( eFileLock==SHARED_LOCK && 
24041       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24042     assert( eFileLock==SHARED_LOCK );
24043     assert( pFile->eFileLock==0 );
24044     assert( pInode->nShared>0 );
24045     pFile->eFileLock = SHARED_LOCK;
24046     pInode->nShared++;
24047     pInode->nLock++;
24048     goto end_lock;
24049   }
24050
24051
24052   /* A PENDING lock is needed before acquiring a SHARED lock and before
24053   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24054   ** be released.
24055   */
24056   lock.l_len = 1L;
24057   lock.l_whence = SEEK_SET;
24058   if( eFileLock==SHARED_LOCK 
24059       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24060   ){
24061     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
24062     lock.l_start = PENDING_BYTE;
24063     s = fcntl(pFile->h, F_SETLK, &lock);
24064     if( s==(-1) ){
24065       tErrno = errno;
24066       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24067       if( IS_LOCK_ERROR(rc) ){
24068         pFile->lastErrno = tErrno;
24069       }
24070       goto end_lock;
24071     }
24072   }
24073
24074
24075   /* If control gets to this point, then actually go ahead and make
24076   ** operating system calls for the specified lock.
24077   */
24078   if( eFileLock==SHARED_LOCK ){
24079     assert( pInode->nShared==0 );
24080     assert( pInode->eFileLock==0 );
24081
24082     /* Now get the read-lock */
24083     lock.l_start = SHARED_FIRST;
24084     lock.l_len = SHARED_SIZE;
24085     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
24086       tErrno = errno;
24087     }
24088     /* Drop the temporary PENDING lock */
24089     lock.l_start = PENDING_BYTE;
24090     lock.l_len = 1L;
24091     lock.l_type = F_UNLCK;
24092     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
24093       if( s != -1 ){
24094         /* This could happen with a network mount */
24095         tErrno = errno; 
24096         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
24097         if( IS_LOCK_ERROR(rc) ){
24098           pFile->lastErrno = tErrno;
24099         }
24100         goto end_lock;
24101       }
24102     }
24103     if( s==(-1) ){
24104       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24105       if( IS_LOCK_ERROR(rc) ){
24106         pFile->lastErrno = tErrno;
24107       }
24108     }else{
24109       pFile->eFileLock = SHARED_LOCK;
24110       pInode->nLock++;
24111       pInode->nShared = 1;
24112     }
24113   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24114     /* We are trying for an exclusive lock but another thread in this
24115     ** same process is still holding a shared lock. */
24116     rc = SQLITE_BUSY;
24117   }else{
24118     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24119     ** assumed that there is a SHARED or greater lock on the file
24120     ** already.
24121     */
24122     assert( 0!=pFile->eFileLock );
24123     lock.l_type = F_WRLCK;
24124     switch( eFileLock ){
24125       case RESERVED_LOCK:
24126         lock.l_start = RESERVED_BYTE;
24127         break;
24128       case EXCLUSIVE_LOCK:
24129         lock.l_start = SHARED_FIRST;
24130         lock.l_len = SHARED_SIZE;
24131         break;
24132       default:
24133         assert(0);
24134     }
24135     s = fcntl(pFile->h, F_SETLK, &lock);
24136     if( s==(-1) ){
24137       tErrno = errno;
24138       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24139       if( IS_LOCK_ERROR(rc) ){
24140         pFile->lastErrno = tErrno;
24141       }
24142     }
24143   }
24144   
24145
24146 #ifndef NDEBUG
24147   /* Set up the transaction-counter change checking flags when
24148   ** transitioning from a SHARED to a RESERVED lock.  The change
24149   ** from SHARED to RESERVED marks the beginning of a normal
24150   ** write operation (not a hot journal rollback).
24151   */
24152   if( rc==SQLITE_OK
24153    && pFile->eFileLock<=SHARED_LOCK
24154    && eFileLock==RESERVED_LOCK
24155   ){
24156     pFile->transCntrChng = 0;
24157     pFile->dbUpdate = 0;
24158     pFile->inNormalWrite = 1;
24159   }
24160 #endif
24161
24162
24163   if( rc==SQLITE_OK ){
24164     pFile->eFileLock = eFileLock;
24165     pInode->eFileLock = eFileLock;
24166   }else if( eFileLock==EXCLUSIVE_LOCK ){
24167     pFile->eFileLock = PENDING_LOCK;
24168     pInode->eFileLock = PENDING_LOCK;
24169   }
24170
24171 end_lock:
24172   unixLeaveMutex();
24173   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
24174       rc==SQLITE_OK ? "ok" : "failed"));
24175   return rc;
24176 }
24177
24178 /*
24179 ** Add the file descriptor used by file handle pFile to the corresponding
24180 ** pUnused list.
24181 */
24182 static void setPendingFd(unixFile *pFile){
24183   unixInodeInfo *pInode = pFile->pInode;
24184   UnixUnusedFd *p = pFile->pUnused;
24185   p->pNext = pInode->pUnused;
24186   pInode->pUnused = p;
24187   pFile->h = -1;
24188   pFile->pUnused = 0;
24189 }
24190
24191 /*
24192 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24193 ** must be either NO_LOCK or SHARED_LOCK.
24194 **
24195 ** If the locking level of the file descriptor is already at or below
24196 ** the requested locking level, this routine is a no-op.
24197 ** 
24198 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
24199 ** the byte range is divided into 2 parts and the first part is unlocked then
24200 ** set to a read lock, then the other part is simply unlocked.  This works 
24201 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
24202 ** remove the write lock on a region when a read lock is set.
24203 */
24204 static int _posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
24205   unixFile *pFile = (unixFile*)id;
24206   unixInodeInfo *pInode;
24207   struct flock lock;
24208   int rc = SQLITE_OK;
24209   int h;
24210   int tErrno;                      /* Error code from system call errors */
24211
24212   assert( pFile );
24213   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
24214       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24215       getpid()));
24216
24217   assert( eFileLock<=SHARED_LOCK );
24218   if( pFile->eFileLock<=eFileLock ){
24219     return SQLITE_OK;
24220   }
24221   unixEnterMutex();
24222   h = pFile->h;
24223   pInode = pFile->pInode;
24224   assert( pInode->nShared!=0 );
24225   if( pFile->eFileLock>SHARED_LOCK ){
24226     assert( pInode->eFileLock==pFile->eFileLock );
24227     SimulateIOErrorBenign(1);
24228     SimulateIOError( h=(-1) )
24229     SimulateIOErrorBenign(0);
24230
24231 #ifndef NDEBUG
24232     /* When reducing a lock such that other processes can start
24233     ** reading the database file again, make sure that the
24234     ** transaction counter was updated if any part of the database
24235     ** file changed.  If the transaction counter is not updated,
24236     ** other connections to the same file might not realize that
24237     ** the file has changed and hence might not know to flush their
24238     ** cache.  The use of a stale cache can lead to database corruption.
24239     */
24240 #if 0
24241     assert( pFile->inNormalWrite==0
24242          || pFile->dbUpdate==0
24243          || pFile->transCntrChng==1 );
24244 #endif
24245     pFile->inNormalWrite = 0;
24246 #endif
24247
24248     /* downgrading to a shared lock on NFS involves clearing the write lock
24249     ** before establishing the readlock - to avoid a race condition we downgrade
24250     ** the lock in 2 blocks, so that part of the range will be covered by a 
24251     ** write lock until the rest is covered by a read lock:
24252     **  1:   [WWWWW]
24253     **  2:   [....W]
24254     **  3:   [RRRRW]
24255     **  4:   [RRRR.]
24256     */
24257     if( eFileLock==SHARED_LOCK ){
24258       if( handleNFSUnlock ){
24259         off_t divSize = SHARED_SIZE - 1;
24260         
24261         lock.l_type = F_UNLCK;
24262         lock.l_whence = SEEK_SET;
24263         lock.l_start = SHARED_FIRST;
24264         lock.l_len = divSize;
24265         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24266           tErrno = errno;
24267           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24268           if( IS_LOCK_ERROR(rc) ){
24269             pFile->lastErrno = tErrno;
24270           }
24271           goto end_unlock;
24272         }
24273         lock.l_type = F_RDLCK;
24274         lock.l_whence = SEEK_SET;
24275         lock.l_start = SHARED_FIRST;
24276         lock.l_len = divSize;
24277         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24278           tErrno = errno;
24279           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24280           if( IS_LOCK_ERROR(rc) ){
24281             pFile->lastErrno = tErrno;
24282           }
24283           goto end_unlock;
24284         }
24285         lock.l_type = F_UNLCK;
24286         lock.l_whence = SEEK_SET;
24287         lock.l_start = SHARED_FIRST+divSize;
24288         lock.l_len = SHARED_SIZE-divSize;
24289         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24290           tErrno = errno;
24291           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24292           if( IS_LOCK_ERROR(rc) ){
24293             pFile->lastErrno = tErrno;
24294           }
24295           goto end_unlock;
24296         }
24297       }else{
24298         lock.l_type = F_RDLCK;
24299         lock.l_whence = SEEK_SET;
24300         lock.l_start = SHARED_FIRST;
24301         lock.l_len = SHARED_SIZE;
24302         if( fcntl(h, F_SETLK, &lock)==(-1) ){
24303           tErrno = errno;
24304           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24305           if( IS_LOCK_ERROR(rc) ){
24306             pFile->lastErrno = tErrno;
24307           }
24308           goto end_unlock;
24309         }
24310       }
24311     }
24312     lock.l_type = F_UNLCK;
24313     lock.l_whence = SEEK_SET;
24314     lock.l_start = PENDING_BYTE;
24315     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
24316     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
24317       pInode->eFileLock = SHARED_LOCK;
24318     }else{
24319       tErrno = errno;
24320       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24321       if( IS_LOCK_ERROR(rc) ){
24322         pFile->lastErrno = tErrno;
24323       }
24324       goto end_unlock;
24325     }
24326   }
24327   if( eFileLock==NO_LOCK ){
24328     /* Decrement the shared lock counter.  Release the lock using an
24329     ** OS call only when all threads in this same process have released
24330     ** the lock.
24331     */
24332     pInode->nShared--;
24333     if( pInode->nShared==0 ){
24334       lock.l_type = F_UNLCK;
24335       lock.l_whence = SEEK_SET;
24336       lock.l_start = lock.l_len = 0L;
24337       SimulateIOErrorBenign(1);
24338       SimulateIOError( h=(-1) )
24339       SimulateIOErrorBenign(0);
24340       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
24341         pInode->eFileLock = NO_LOCK;
24342       }else{
24343         tErrno = errno;
24344         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24345         if( IS_LOCK_ERROR(rc) ){
24346           pFile->lastErrno = tErrno;
24347         }
24348         pInode->eFileLock = NO_LOCK;
24349         pFile->eFileLock = NO_LOCK;
24350       }
24351     }
24352
24353     /* Decrement the count of locks against this same file.  When the
24354     ** count reaches zero, close any other file descriptors whose close
24355     ** was deferred because of outstanding locks.
24356     */
24357     pInode->nLock--;
24358     assert( pInode->nLock>=0 );
24359     if( pInode->nLock==0 ){
24360       int rc2 = closePendingFds(pFile);
24361       if( rc==SQLITE_OK ){
24362         rc = rc2;
24363       }
24364     }
24365   }
24366         
24367 end_unlock:
24368   unixLeaveMutex();
24369   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24370   return rc;
24371 }
24372
24373 /*
24374 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24375 ** must be either NO_LOCK or SHARED_LOCK.
24376 **
24377 ** If the locking level of the file descriptor is already at or below
24378 ** the requested locking level, this routine is a no-op.
24379 */
24380 static int unixUnlock(sqlite3_file *id, int eFileLock){
24381   return _posixUnlock(id, eFileLock, 0);
24382 }
24383
24384 /*
24385 ** This function performs the parts of the "close file" operation 
24386 ** common to all locking schemes. It closes the directory and file
24387 ** handles, if they are valid, and sets all fields of the unixFile
24388 ** structure to 0.
24389 **
24390 ** It is *not* necessary to hold the mutex when this routine is called,
24391 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
24392 ** vxworksReleaseFileId() routine.
24393 */
24394 static int closeUnixFile(sqlite3_file *id){
24395   unixFile *pFile = (unixFile*)id;
24396   if( pFile ){
24397     if( pFile->dirfd>=0 ){
24398       int err = close(pFile->dirfd);
24399       if( err ){
24400         pFile->lastErrno = errno;
24401         return SQLITE_IOERR_DIR_CLOSE;
24402       }else{
24403         pFile->dirfd=-1;
24404       }
24405     }
24406     if( pFile->h>=0 ){
24407       int err = close(pFile->h);
24408       if( err ){
24409         pFile->lastErrno = errno;
24410         return SQLITE_IOERR_CLOSE;
24411       }
24412     }
24413 #if OS_VXWORKS
24414     if( pFile->pId ){
24415       if( pFile->isDelete ){
24416         unlink(pFile->pId->zCanonicalName);
24417       }
24418       vxworksReleaseFileId(pFile->pId);
24419       pFile->pId = 0;
24420     }
24421 #endif
24422     OSTRACE(("CLOSE   %-3d\n", pFile->h));
24423     OpenCounter(-1);
24424     sqlite3_free(pFile->pUnused);
24425     memset(pFile, 0, sizeof(unixFile));
24426   }
24427   return SQLITE_OK;
24428 }
24429
24430 /*
24431 ** Close a file.
24432 */
24433 static int unixClose(sqlite3_file *id){
24434   int rc = SQLITE_OK;
24435   if( id ){
24436     unixFile *pFile = (unixFile *)id;
24437     unixUnlock(id, NO_LOCK);
24438     unixEnterMutex();
24439     if( pFile->pInode && pFile->pInode->nLock ){
24440       /* If there are outstanding locks, do not actually close the file just
24441       ** yet because that would clear those locks.  Instead, add the file
24442       ** descriptor to pInode->pUnused list.  It will be automatically closed 
24443       ** when the last lock is cleared.
24444       */
24445       setPendingFd(pFile);
24446     }
24447     releaseInodeInfo(pFile);
24448     rc = closeUnixFile(id);
24449     unixLeaveMutex();
24450   }
24451   return rc;
24452 }
24453
24454 /************** End of the posix advisory lock implementation *****************
24455 ******************************************************************************/
24456
24457 /******************************************************************************
24458 ****************************** No-op Locking **********************************
24459 **
24460 ** Of the various locking implementations available, this is by far the
24461 ** simplest:  locking is ignored.  No attempt is made to lock the database
24462 ** file for reading or writing.
24463 **
24464 ** This locking mode is appropriate for use on read-only databases
24465 ** (ex: databases that are burned into CD-ROM, for example.)  It can
24466 ** also be used if the application employs some external mechanism to
24467 ** prevent simultaneous access of the same database by two or more
24468 ** database connections.  But there is a serious risk of database
24469 ** corruption if this locking mode is used in situations where multiple
24470 ** database connections are accessing the same database file at the same
24471 ** time and one or more of those connections are writing.
24472 */
24473
24474 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
24475   UNUSED_PARAMETER(NotUsed);
24476   *pResOut = 0;
24477   return SQLITE_OK;
24478 }
24479 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
24480   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24481   return SQLITE_OK;
24482 }
24483 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
24484   UNUSED_PARAMETER2(NotUsed, NotUsed2);
24485   return SQLITE_OK;
24486 }
24487
24488 /*
24489 ** Close the file.
24490 */
24491 static int nolockClose(sqlite3_file *id) {
24492   return closeUnixFile(id);
24493 }
24494
24495 /******************* End of the no-op lock implementation *********************
24496 ******************************************************************************/
24497
24498 /******************************************************************************
24499 ************************* Begin dot-file Locking ******************************
24500 **
24501 ** The dotfile locking implementation uses the existance of separate lock
24502 ** files in order to control access to the database.  This works on just
24503 ** about every filesystem imaginable.  But there are serious downsides:
24504 **
24505 **    (1)  There is zero concurrency.  A single reader blocks all other
24506 **         connections from reading or writing the database.
24507 **
24508 **    (2)  An application crash or power loss can leave stale lock files
24509 **         sitting around that need to be cleared manually.
24510 **
24511 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
24512 ** other locking strategy is available.
24513 **
24514 ** Dotfile locking works by creating a file in the same directory as the
24515 ** database and with the same name but with a ".lock" extension added.
24516 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
24517 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
24518 */
24519
24520 /*
24521 ** The file suffix added to the data base filename in order to create the
24522 ** lock file.
24523 */
24524 #define DOTLOCK_SUFFIX ".lock"
24525
24526 /*
24527 ** This routine checks if there is a RESERVED lock held on the specified
24528 ** file by this or any other process. If such a lock is held, set *pResOut
24529 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24530 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24531 **
24532 ** In dotfile locking, either a lock exists or it does not.  So in this
24533 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
24534 ** is held on the file and false if the file is unlocked.
24535 */
24536 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
24537   int rc = SQLITE_OK;
24538   int reserved = 0;
24539   unixFile *pFile = (unixFile*)id;
24540
24541   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24542   
24543   assert( pFile );
24544
24545   /* Check if a thread in this process holds such a lock */
24546   if( pFile->eFileLock>SHARED_LOCK ){
24547     /* Either this connection or some other connection in the same process
24548     ** holds a lock on the file.  No need to check further. */
24549     reserved = 1;
24550   }else{
24551     /* The lock is held if and only if the lockfile exists */
24552     const char *zLockFile = (const char*)pFile->lockingContext;
24553     reserved = access(zLockFile, 0)==0;
24554   }
24555   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
24556   *pResOut = reserved;
24557   return rc;
24558 }
24559
24560 /*
24561 ** Lock the file with the lock specified by parameter eFileLock - one
24562 ** of the following:
24563 **
24564 **     (1) SHARED_LOCK
24565 **     (2) RESERVED_LOCK
24566 **     (3) PENDING_LOCK
24567 **     (4) EXCLUSIVE_LOCK
24568 **
24569 ** Sometimes when requesting one lock state, additional lock states
24570 ** are inserted in between.  The locking might fail on one of the later
24571 ** transitions leaving the lock state different from what it started but
24572 ** still short of its goal.  The following chart shows the allowed
24573 ** transitions and the inserted intermediate states:
24574 **
24575 **    UNLOCKED -> SHARED
24576 **    SHARED -> RESERVED
24577 **    SHARED -> (PENDING) -> EXCLUSIVE
24578 **    RESERVED -> (PENDING) -> EXCLUSIVE
24579 **    PENDING -> EXCLUSIVE
24580 **
24581 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24582 ** routine to lower a locking level.
24583 **
24584 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
24585 ** But we track the other locking levels internally.
24586 */
24587 static int dotlockLock(sqlite3_file *id, int eFileLock) {
24588   unixFile *pFile = (unixFile*)id;
24589   int fd;
24590   char *zLockFile = (char *)pFile->lockingContext;
24591   int rc = SQLITE_OK;
24592
24593
24594   /* If we have any lock, then the lock file already exists.  All we have
24595   ** to do is adjust our internal record of the lock level.
24596   */
24597   if( pFile->eFileLock > NO_LOCK ){
24598     pFile->eFileLock = eFileLock;
24599 #if !OS_VXWORKS
24600     /* Always update the timestamp on the old file */
24601     utimes(zLockFile, NULL);
24602 #endif
24603     return SQLITE_OK;
24604   }
24605   
24606   /* grab an exclusive lock */
24607   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
24608   if( fd<0 ){
24609     /* failed to open/create the file, someone else may have stolen the lock */
24610     int tErrno = errno;
24611     if( EEXIST == tErrno ){
24612       rc = SQLITE_BUSY;
24613     } else {
24614       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24615       if( IS_LOCK_ERROR(rc) ){
24616         pFile->lastErrno = tErrno;
24617       }
24618     }
24619     return rc;
24620   } 
24621   if( close(fd) ){
24622     pFile->lastErrno = errno;
24623     rc = SQLITE_IOERR_CLOSE;
24624   }
24625   
24626   /* got it, set the type and return ok */
24627   pFile->eFileLock = eFileLock;
24628   return rc;
24629 }
24630
24631 /*
24632 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24633 ** must be either NO_LOCK or SHARED_LOCK.
24634 **
24635 ** If the locking level of the file descriptor is already at or below
24636 ** the requested locking level, this routine is a no-op.
24637 **
24638 ** When the locking level reaches NO_LOCK, delete the lock file.
24639 */
24640 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
24641   unixFile *pFile = (unixFile*)id;
24642   char *zLockFile = (char *)pFile->lockingContext;
24643
24644   assert( pFile );
24645   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
24646            pFile->eFileLock, getpid()));
24647   assert( eFileLock<=SHARED_LOCK );
24648   
24649   /* no-op if possible */
24650   if( pFile->eFileLock==eFileLock ){
24651     return SQLITE_OK;
24652   }
24653
24654   /* To downgrade to shared, simply update our internal notion of the
24655   ** lock state.  No need to mess with the file on disk.
24656   */
24657   if( eFileLock==SHARED_LOCK ){
24658     pFile->eFileLock = SHARED_LOCK;
24659     return SQLITE_OK;
24660   }
24661   
24662   /* To fully unlock the database, delete the lock file */
24663   assert( eFileLock==NO_LOCK );
24664   if( unlink(zLockFile) ){
24665     int rc = 0;
24666     int tErrno = errno;
24667     if( ENOENT != tErrno ){
24668       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24669     }
24670     if( IS_LOCK_ERROR(rc) ){
24671       pFile->lastErrno = tErrno;
24672     }
24673     return rc; 
24674   }
24675   pFile->eFileLock = NO_LOCK;
24676   return SQLITE_OK;
24677 }
24678
24679 /*
24680 ** Close a file.  Make sure the lock has been released before closing.
24681 */
24682 static int dotlockClose(sqlite3_file *id) {
24683   int rc;
24684   if( id ){
24685     unixFile *pFile = (unixFile*)id;
24686     dotlockUnlock(id, NO_LOCK);
24687     sqlite3_free(pFile->lockingContext);
24688   }
24689   rc = closeUnixFile(id);
24690   return rc;
24691 }
24692 /****************** End of the dot-file lock implementation *******************
24693 ******************************************************************************/
24694
24695 /******************************************************************************
24696 ************************** Begin flock Locking ********************************
24697 **
24698 ** Use the flock() system call to do file locking.
24699 **
24700 ** flock() locking is like dot-file locking in that the various
24701 ** fine-grain locking levels supported by SQLite are collapsed into
24702 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
24703 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
24704 ** still works when you do this, but concurrency is reduced since
24705 ** only a single process can be reading the database at a time.
24706 **
24707 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
24708 ** compiling for VXWORKS.
24709 */
24710 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24711
24712 /*
24713 ** This routine checks if there is a RESERVED lock held on the specified
24714 ** file by this or any other process. If such a lock is held, set *pResOut
24715 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24716 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24717 */
24718 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
24719   int rc = SQLITE_OK;
24720   int reserved = 0;
24721   unixFile *pFile = (unixFile*)id;
24722   
24723   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24724   
24725   assert( pFile );
24726   
24727   /* Check if a thread in this process holds such a lock */
24728   if( pFile->eFileLock>SHARED_LOCK ){
24729     reserved = 1;
24730   }
24731   
24732   /* Otherwise see if some other process holds it. */
24733   if( !reserved ){
24734     /* attempt to get the lock */
24735     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
24736     if( !lrc ){
24737       /* got the lock, unlock it */
24738       lrc = flock(pFile->h, LOCK_UN);
24739       if ( lrc ) {
24740         int tErrno = errno;
24741         /* unlock failed with an error */
24742         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
24743         if( IS_LOCK_ERROR(lrc) ){
24744           pFile->lastErrno = tErrno;
24745           rc = lrc;
24746         }
24747       }
24748     } else {
24749       int tErrno = errno;
24750       reserved = 1;
24751       /* someone else might have it reserved */
24752       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
24753       if( IS_LOCK_ERROR(lrc) ){
24754         pFile->lastErrno = tErrno;
24755         rc = lrc;
24756       }
24757     }
24758   }
24759   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
24760
24761 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24762   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24763     rc = SQLITE_OK;
24764     reserved=1;
24765   }
24766 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24767   *pResOut = reserved;
24768   return rc;
24769 }
24770
24771 /*
24772 ** Lock the file with the lock specified by parameter eFileLock - one
24773 ** of the following:
24774 **
24775 **     (1) SHARED_LOCK
24776 **     (2) RESERVED_LOCK
24777 **     (3) PENDING_LOCK
24778 **     (4) EXCLUSIVE_LOCK
24779 **
24780 ** Sometimes when requesting one lock state, additional lock states
24781 ** are inserted in between.  The locking might fail on one of the later
24782 ** transitions leaving the lock state different from what it started but
24783 ** still short of its goal.  The following chart shows the allowed
24784 ** transitions and the inserted intermediate states:
24785 **
24786 **    UNLOCKED -> SHARED
24787 **    SHARED -> RESERVED
24788 **    SHARED -> (PENDING) -> EXCLUSIVE
24789 **    RESERVED -> (PENDING) -> EXCLUSIVE
24790 **    PENDING -> EXCLUSIVE
24791 **
24792 ** flock() only really support EXCLUSIVE locks.  We track intermediate
24793 ** lock states in the sqlite3_file structure, but all locks SHARED or
24794 ** above are really EXCLUSIVE locks and exclude all other processes from
24795 ** access the file.
24796 **
24797 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24798 ** routine to lower a locking level.
24799 */
24800 static int flockLock(sqlite3_file *id, int eFileLock) {
24801   int rc = SQLITE_OK;
24802   unixFile *pFile = (unixFile*)id;
24803
24804   assert( pFile );
24805
24806   /* if we already have a lock, it is exclusive.  
24807   ** Just adjust level and punt on outta here. */
24808   if (pFile->eFileLock > NO_LOCK) {
24809     pFile->eFileLock = eFileLock;
24810     return SQLITE_OK;
24811   }
24812   
24813   /* grab an exclusive lock */
24814   
24815   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
24816     int tErrno = errno;
24817     /* didn't get, must be busy */
24818     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24819     if( IS_LOCK_ERROR(rc) ){
24820       pFile->lastErrno = tErrno;
24821     }
24822   } else {
24823     /* got it, set the type and return ok */
24824     pFile->eFileLock = eFileLock;
24825   }
24826   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
24827            rc==SQLITE_OK ? "ok" : "failed"));
24828 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24829   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24830     rc = SQLITE_BUSY;
24831   }
24832 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24833   return rc;
24834 }
24835
24836
24837 /*
24838 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24839 ** must be either NO_LOCK or SHARED_LOCK.
24840 **
24841 ** If the locking level of the file descriptor is already at or below
24842 ** the requested locking level, this routine is a no-op.
24843 */
24844 static int flockUnlock(sqlite3_file *id, int eFileLock) {
24845   unixFile *pFile = (unixFile*)id;
24846   
24847   assert( pFile );
24848   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
24849            pFile->eFileLock, getpid()));
24850   assert( eFileLock<=SHARED_LOCK );
24851   
24852   /* no-op if possible */
24853   if( pFile->eFileLock==eFileLock ){
24854     return SQLITE_OK;
24855   }
24856   
24857   /* shared can just be set because we always have an exclusive */
24858   if (eFileLock==SHARED_LOCK) {
24859     pFile->eFileLock = eFileLock;
24860     return SQLITE_OK;
24861   }
24862   
24863   /* no, really, unlock. */
24864   int rc = flock(pFile->h, LOCK_UN);
24865   if (rc) {
24866     int r, tErrno = errno;
24867     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24868     if( IS_LOCK_ERROR(r) ){
24869       pFile->lastErrno = tErrno;
24870     }
24871 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24872     if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
24873       r = SQLITE_BUSY;
24874     }
24875 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24876     
24877     return r;
24878   } else {
24879     pFile->eFileLock = NO_LOCK;
24880     return SQLITE_OK;
24881   }
24882 }
24883
24884 /*
24885 ** Close a file.
24886 */
24887 static int flockClose(sqlite3_file *id) {
24888   if( id ){
24889     flockUnlock(id, NO_LOCK);
24890   }
24891   return closeUnixFile(id);
24892 }
24893
24894 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
24895
24896 /******************* End of the flock lock implementation *********************
24897 ******************************************************************************/
24898
24899 /******************************************************************************
24900 ************************ Begin Named Semaphore Locking ************************
24901 **
24902 ** Named semaphore locking is only supported on VxWorks.
24903 **
24904 ** Semaphore locking is like dot-lock and flock in that it really only
24905 ** supports EXCLUSIVE locking.  Only a single process can read or write
24906 ** the database file at a time.  This reduces potential concurrency, but
24907 ** makes the lock implementation much easier.
24908 */
24909 #if OS_VXWORKS
24910
24911 /*
24912 ** This routine checks if there is a RESERVED lock held on the specified
24913 ** file by this or any other process. If such a lock is held, set *pResOut
24914 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24915 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24916 */
24917 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
24918   int rc = SQLITE_OK;
24919   int reserved = 0;
24920   unixFile *pFile = (unixFile*)id;
24921
24922   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24923   
24924   assert( pFile );
24925
24926   /* Check if a thread in this process holds such a lock */
24927   if( pFile->eFileLock>SHARED_LOCK ){
24928     reserved = 1;
24929   }
24930   
24931   /* Otherwise see if some other process holds it. */
24932   if( !reserved ){
24933     sem_t *pSem = pFile->pInode->pSem;
24934     struct stat statBuf;
24935
24936     if( sem_trywait(pSem)==-1 ){
24937       int tErrno = errno;
24938       if( EAGAIN != tErrno ){
24939         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
24940         pFile->lastErrno = tErrno;
24941       } else {
24942         /* someone else has the lock when we are in NO_LOCK */
24943         reserved = (pFile->eFileLock < SHARED_LOCK);
24944       }
24945     }else{
24946       /* we could have it if we want it */
24947       sem_post(pSem);
24948     }
24949   }
24950   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
24951
24952   *pResOut = reserved;
24953   return rc;
24954 }
24955
24956 /*
24957 ** Lock the file with the lock specified by parameter eFileLock - one
24958 ** of the following:
24959 **
24960 **     (1) SHARED_LOCK
24961 **     (2) RESERVED_LOCK
24962 **     (3) PENDING_LOCK
24963 **     (4) EXCLUSIVE_LOCK
24964 **
24965 ** Sometimes when requesting one lock state, additional lock states
24966 ** are inserted in between.  The locking might fail on one of the later
24967 ** transitions leaving the lock state different from what it started but
24968 ** still short of its goal.  The following chart shows the allowed
24969 ** transitions and the inserted intermediate states:
24970 **
24971 **    UNLOCKED -> SHARED
24972 **    SHARED -> RESERVED
24973 **    SHARED -> (PENDING) -> EXCLUSIVE
24974 **    RESERVED -> (PENDING) -> EXCLUSIVE
24975 **    PENDING -> EXCLUSIVE
24976 **
24977 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
24978 ** lock states in the sqlite3_file structure, but all locks SHARED or
24979 ** above are really EXCLUSIVE locks and exclude all other processes from
24980 ** access the file.
24981 **
24982 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24983 ** routine to lower a locking level.
24984 */
24985 static int semLock(sqlite3_file *id, int eFileLock) {
24986   unixFile *pFile = (unixFile*)id;
24987   int fd;
24988   sem_t *pSem = pFile->pInode->pSem;
24989   int rc = SQLITE_OK;
24990
24991   /* if we already have a lock, it is exclusive.  
24992   ** Just adjust level and punt on outta here. */
24993   if (pFile->eFileLock > NO_LOCK) {
24994     pFile->eFileLock = eFileLock;
24995     rc = SQLITE_OK;
24996     goto sem_end_lock;
24997   }
24998   
24999   /* lock semaphore now but bail out when already locked. */
25000   if( sem_trywait(pSem)==-1 ){
25001     rc = SQLITE_BUSY;
25002     goto sem_end_lock;
25003   }
25004
25005   /* got it, set the type and return ok */
25006   pFile->eFileLock = eFileLock;
25007
25008  sem_end_lock:
25009   return rc;
25010 }
25011
25012 /*
25013 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25014 ** must be either NO_LOCK or SHARED_LOCK.
25015 **
25016 ** If the locking level of the file descriptor is already at or below
25017 ** the requested locking level, this routine is a no-op.
25018 */
25019 static int semUnlock(sqlite3_file *id, int eFileLock) {
25020   unixFile *pFile = (unixFile*)id;
25021   sem_t *pSem = pFile->pInode->pSem;
25022
25023   assert( pFile );
25024   assert( pSem );
25025   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
25026            pFile->eFileLock, getpid()));
25027   assert( eFileLock<=SHARED_LOCK );
25028   
25029   /* no-op if possible */
25030   if( pFile->eFileLock==eFileLock ){
25031     return SQLITE_OK;
25032   }
25033   
25034   /* shared can just be set because we always have an exclusive */
25035   if (eFileLock==SHARED_LOCK) {
25036     pFile->eFileLock = eFileLock;
25037     return SQLITE_OK;
25038   }
25039   
25040   /* no, really unlock. */
25041   if ( sem_post(pSem)==-1 ) {
25042     int rc, tErrno = errno;
25043     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
25044     if( IS_LOCK_ERROR(rc) ){
25045       pFile->lastErrno = tErrno;
25046     }
25047     return rc; 
25048   }
25049   pFile->eFileLock = NO_LOCK;
25050   return SQLITE_OK;
25051 }
25052
25053 /*
25054  ** Close a file.
25055  */
25056 static int semClose(sqlite3_file *id) {
25057   if( id ){
25058     unixFile *pFile = (unixFile*)id;
25059     semUnlock(id, NO_LOCK);
25060     assert( pFile );
25061     unixEnterMutex();
25062     releaseInodeInfo(pFile);
25063     unixLeaveMutex();
25064     closeUnixFile(id);
25065   }
25066   return SQLITE_OK;
25067 }
25068
25069 #endif /* OS_VXWORKS */
25070 /*
25071 ** Named semaphore locking is only available on VxWorks.
25072 **
25073 *************** End of the named semaphore lock implementation ****************
25074 ******************************************************************************/
25075
25076
25077 /******************************************************************************
25078 *************************** Begin AFP Locking *********************************
25079 **
25080 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
25081 ** on Apple Macintosh computers - both OS9 and OSX.
25082 **
25083 ** Third-party implementations of AFP are available.  But this code here
25084 ** only works on OSX.
25085 */
25086
25087 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25088 /*
25089 ** The afpLockingContext structure contains all afp lock specific state
25090 */
25091 typedef struct afpLockingContext afpLockingContext;
25092 struct afpLockingContext {
25093   int reserved;
25094   const char *dbPath;             /* Name of the open file */
25095 };
25096
25097 struct ByteRangeLockPB2
25098 {
25099   unsigned long long offset;        /* offset to first byte to lock */
25100   unsigned long long length;        /* nbr of bytes to lock */
25101   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
25102   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
25103   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
25104   int fd;                           /* file desc to assoc this lock with */
25105 };
25106
25107 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
25108
25109 /*
25110 ** This is a utility for setting or clearing a bit-range lock on an
25111 ** AFP filesystem.
25112 ** 
25113 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25114 */
25115 static int afpSetLock(
25116   const char *path,              /* Name of the file to be locked or unlocked */
25117   unixFile *pFile,               /* Open file descriptor on path */
25118   unsigned long long offset,     /* First byte to be locked */
25119   unsigned long long length,     /* Number of bytes to lock */
25120   int setLockFlag                /* True to set lock.  False to clear lock */
25121 ){
25122   struct ByteRangeLockPB2 pb;
25123   int err;
25124   
25125   pb.unLockFlag = setLockFlag ? 0 : 1;
25126   pb.startEndFlag = 0;
25127   pb.offset = offset;
25128   pb.length = length; 
25129   pb.fd = pFile->h;
25130   
25131   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
25132     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25133     offset, length));
25134   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25135   if ( err==-1 ) {
25136     int rc;
25137     int tErrno = errno;
25138     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25139              path, tErrno, strerror(tErrno)));
25140 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25141     rc = SQLITE_BUSY;
25142 #else
25143     rc = sqliteErrorFromPosixError(tErrno,
25144                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25145 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25146     if( IS_LOCK_ERROR(rc) ){
25147       pFile->lastErrno = tErrno;
25148     }
25149     return rc;
25150   } else {
25151     return SQLITE_OK;
25152   }
25153 }
25154
25155 /*
25156 ** This routine checks if there is a RESERVED lock held on the specified
25157 ** file by this or any other process. If such a lock is held, set *pResOut
25158 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25159 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25160 */
25161 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25162   int rc = SQLITE_OK;
25163   int reserved = 0;
25164   unixFile *pFile = (unixFile*)id;
25165   
25166   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25167   
25168   assert( pFile );
25169   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25170   if( context->reserved ){
25171     *pResOut = 1;
25172     return SQLITE_OK;
25173   }
25174   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25175   
25176   /* Check if a thread in this process holds such a lock */
25177   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25178     reserved = 1;
25179   }
25180   
25181   /* Otherwise see if some other process holds it.
25182    */
25183   if( !reserved ){
25184     /* lock the RESERVED byte */
25185     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
25186     if( SQLITE_OK==lrc ){
25187       /* if we succeeded in taking the reserved lock, unlock it to restore
25188       ** the original state */
25189       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25190     } else {
25191       /* if we failed to get the lock then someone else must have it */
25192       reserved = 1;
25193     }
25194     if( IS_LOCK_ERROR(lrc) ){
25195       rc=lrc;
25196     }
25197   }
25198   
25199   unixLeaveMutex();
25200   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
25201   
25202   *pResOut = reserved;
25203   return rc;
25204 }
25205
25206 /*
25207 ** Lock the file with the lock specified by parameter eFileLock - one
25208 ** of the following:
25209 **
25210 **     (1) SHARED_LOCK
25211 **     (2) RESERVED_LOCK
25212 **     (3) PENDING_LOCK
25213 **     (4) EXCLUSIVE_LOCK
25214 **
25215 ** Sometimes when requesting one lock state, additional lock states
25216 ** are inserted in between.  The locking might fail on one of the later
25217 ** transitions leaving the lock state different from what it started but
25218 ** still short of its goal.  The following chart shows the allowed
25219 ** transitions and the inserted intermediate states:
25220 **
25221 **    UNLOCKED -> SHARED
25222 **    SHARED -> RESERVED
25223 **    SHARED -> (PENDING) -> EXCLUSIVE
25224 **    RESERVED -> (PENDING) -> EXCLUSIVE
25225 **    PENDING -> EXCLUSIVE
25226 **
25227 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25228 ** routine to lower a locking level.
25229 */
25230 static int afpLock(sqlite3_file *id, int eFileLock){
25231   int rc = SQLITE_OK;
25232   unixFile *pFile = (unixFile*)id;
25233   unixInodeInfo *pInode = pFile->pInode;
25234   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25235   
25236   assert( pFile );
25237   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
25238            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25239            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25240
25241   /* If there is already a lock of this type or more restrictive on the
25242   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
25243   ** unixEnterMutex() hasn't been called yet.
25244   */
25245   if( pFile->eFileLock>=eFileLock ){
25246     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
25247            azFileLock(eFileLock)));
25248     return SQLITE_OK;
25249   }
25250
25251   /* Make sure the locking sequence is correct
25252   **  (1) We never move from unlocked to anything higher than shared lock.
25253   **  (2) SQLite never explicitly requests a pendig lock.
25254   **  (3) A shared lock is always held when a reserve lock is requested.
25255   */
25256   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25257   assert( eFileLock!=PENDING_LOCK );
25258   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25259   
25260   /* This mutex is needed because pFile->pInode is shared across threads
25261   */
25262   unixEnterMutex();
25263   pInode = pFile->pInode;
25264
25265   /* If some thread using this PID has a lock via a different unixFile*
25266   ** handle that precludes the requested lock, return BUSY.
25267   */
25268   if( (pFile->eFileLock!=pInode->eFileLock && 
25269        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25270      ){
25271     rc = SQLITE_BUSY;
25272     goto afp_end_lock;
25273   }
25274   
25275   /* If a SHARED lock is requested, and some thread using this PID already
25276   ** has a SHARED or RESERVED lock, then increment reference counts and
25277   ** return SQLITE_OK.
25278   */
25279   if( eFileLock==SHARED_LOCK && 
25280      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25281     assert( eFileLock==SHARED_LOCK );
25282     assert( pFile->eFileLock==0 );
25283     assert( pInode->nShared>0 );
25284     pFile->eFileLock = SHARED_LOCK;
25285     pInode->nShared++;
25286     pInode->nLock++;
25287     goto afp_end_lock;
25288   }
25289     
25290   /* A PENDING lock is needed before acquiring a SHARED lock and before
25291   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25292   ** be released.
25293   */
25294   if( eFileLock==SHARED_LOCK 
25295       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25296   ){
25297     int failed;
25298     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
25299     if (failed) {
25300       rc = failed;
25301       goto afp_end_lock;
25302     }
25303   }
25304   
25305   /* If control gets to this point, then actually go ahead and make
25306   ** operating system calls for the specified lock.
25307   */
25308   if( eFileLock==SHARED_LOCK ){
25309     int lrc1, lrc2, lrc1Errno;
25310     long lk, mask;
25311     
25312     assert( pInode->nShared==0 );
25313     assert( pInode->eFileLock==0 );
25314         
25315     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
25316     /* Now get the read-lock SHARED_LOCK */
25317     /* note that the quality of the randomness doesn't matter that much */
25318     lk = random(); 
25319     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
25320     lrc1 = afpSetLock(context->dbPath, pFile, 
25321           SHARED_FIRST+pInode->sharedByte, 1, 1);
25322     if( IS_LOCK_ERROR(lrc1) ){
25323       lrc1Errno = pFile->lastErrno;
25324     }
25325     /* Drop the temporary PENDING lock */
25326     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25327     
25328     if( IS_LOCK_ERROR(lrc1) ) {
25329       pFile->lastErrno = lrc1Errno;
25330       rc = lrc1;
25331       goto afp_end_lock;
25332     } else if( IS_LOCK_ERROR(lrc2) ){
25333       rc = lrc2;
25334       goto afp_end_lock;
25335     } else if( lrc1 != SQLITE_OK ) {
25336       rc = lrc1;
25337     } else {
25338       pFile->eFileLock = SHARED_LOCK;
25339       pInode->nLock++;
25340       pInode->nShared = 1;
25341     }
25342   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25343     /* We are trying for an exclusive lock but another thread in this
25344      ** same process is still holding a shared lock. */
25345     rc = SQLITE_BUSY;
25346   }else{
25347     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25348     ** assumed that there is a SHARED or greater lock on the file
25349     ** already.
25350     */
25351     int failed = 0;
25352     assert( 0!=pFile->eFileLock );
25353     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
25354         /* Acquire a RESERVED lock */
25355         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25356       if( !failed ){
25357         context->reserved = 1;
25358       }
25359     }
25360     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
25361       /* Acquire an EXCLUSIVE lock */
25362         
25363       /* Remove the shared lock before trying the range.  we'll need to 
25364       ** reestablish the shared lock if we can't get the  afpUnlock
25365       */
25366       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
25367                          pInode->sharedByte, 1, 0)) ){
25368         int failed2 = SQLITE_OK;
25369         /* now attemmpt to get the exclusive lock range */
25370         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
25371                                SHARED_SIZE, 1);
25372         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
25373                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25374           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25375           ** a critical I/O error
25376           */
25377           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
25378                SQLITE_IOERR_LOCK;
25379           goto afp_end_lock;
25380         } 
25381       }else{
25382         rc = failed; 
25383       }
25384     }
25385     if( failed ){
25386       rc = failed;
25387     }
25388   }
25389   
25390   if( rc==SQLITE_OK ){
25391     pFile->eFileLock = eFileLock;
25392     pInode->eFileLock = eFileLock;
25393   }else if( eFileLock==EXCLUSIVE_LOCK ){
25394     pFile->eFileLock = PENDING_LOCK;
25395     pInode->eFileLock = PENDING_LOCK;
25396   }
25397   
25398 afp_end_lock:
25399   unixLeaveMutex();
25400   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
25401          rc==SQLITE_OK ? "ok" : "failed"));
25402   return rc;
25403 }
25404
25405 /*
25406 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25407 ** must be either NO_LOCK or SHARED_LOCK.
25408 **
25409 ** If the locking level of the file descriptor is already at or below
25410 ** the requested locking level, this routine is a no-op.
25411 */
25412 static int afpUnlock(sqlite3_file *id, int eFileLock) {
25413   int rc = SQLITE_OK;
25414   unixFile *pFile = (unixFile*)id;
25415   unixInodeInfo *pInode;
25416   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25417   int skipShared = 0;
25418 #ifdef SQLITE_TEST
25419   int h = pFile->h;
25420 #endif
25421
25422   assert( pFile );
25423   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
25424            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25425            getpid()));
25426
25427   assert( eFileLock<=SHARED_LOCK );
25428   if( pFile->eFileLock<=eFileLock ){
25429     return SQLITE_OK;
25430   }
25431   unixEnterMutex();
25432   pInode = pFile->pInode;
25433   assert( pInode->nShared!=0 );
25434   if( pFile->eFileLock>SHARED_LOCK ){
25435     assert( pInode->eFileLock==pFile->eFileLock );
25436     SimulateIOErrorBenign(1);
25437     SimulateIOError( h=(-1) )
25438     SimulateIOErrorBenign(0);
25439     
25440 #ifndef NDEBUG
25441     /* When reducing a lock such that other processes can start
25442     ** reading the database file again, make sure that the
25443     ** transaction counter was updated if any part of the database
25444     ** file changed.  If the transaction counter is not updated,
25445     ** other connections to the same file might not realize that
25446     ** the file has changed and hence might not know to flush their
25447     ** cache.  The use of a stale cache can lead to database corruption.
25448     */
25449     assert( pFile->inNormalWrite==0
25450            || pFile->dbUpdate==0
25451            || pFile->transCntrChng==1 );
25452     pFile->inNormalWrite = 0;
25453 #endif
25454     
25455     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
25456       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
25457       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
25458         /* only re-establish the shared lock if necessary */
25459         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25460         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
25461       } else {
25462         skipShared = 1;
25463       }
25464     }
25465     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
25466       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25467     } 
25468     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
25469       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25470       if( !rc ){ 
25471         context->reserved = 0; 
25472       }
25473     }
25474     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
25475       pInode->eFileLock = SHARED_LOCK;
25476     }
25477   }
25478   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
25479
25480     /* Decrement the shared lock counter.  Release the lock using an
25481     ** OS call only when all threads in this same process have released
25482     ** the lock.
25483     */
25484     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
25485     pInode->nShared--;
25486     if( pInode->nShared==0 ){
25487       SimulateIOErrorBenign(1);
25488       SimulateIOError( h=(-1) )
25489       SimulateIOErrorBenign(0);
25490       if( !skipShared ){
25491         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
25492       }
25493       if( !rc ){
25494         pInode->eFileLock = NO_LOCK;
25495         pFile->eFileLock = NO_LOCK;
25496       }
25497     }
25498     if( rc==SQLITE_OK ){
25499       pInode->nLock--;
25500       assert( pInode->nLock>=0 );
25501       if( pInode->nLock==0 ){
25502         rc = closePendingFds(pFile);
25503       }
25504     }
25505   }
25506   
25507   unixLeaveMutex();
25508   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25509   return rc;
25510 }
25511
25512 /*
25513 ** Close a file & cleanup AFP specific locking context 
25514 */
25515 static int afpClose(sqlite3_file *id) {
25516   int rc = SQLITE_OK;
25517   if( id ){
25518     unixFile *pFile = (unixFile*)id;
25519     afpUnlock(id, NO_LOCK);
25520     unixEnterMutex();
25521     if( pFile->pInode && pFile->pInode->nLock ){
25522       /* If there are outstanding locks, do not actually close the file just
25523       ** yet because that would clear those locks.  Instead, add the file
25524       ** descriptor to pInode->aPending.  It will be automatically closed when
25525       ** the last lock is cleared.
25526       */
25527       setPendingFd(pFile);
25528     }
25529     releaseInodeInfo(pFile);
25530     sqlite3_free(pFile->lockingContext);
25531     rc = closeUnixFile(id);
25532     unixLeaveMutex();
25533   }
25534   return rc;
25535 }
25536
25537 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25538 /*
25539 ** The code above is the AFP lock implementation.  The code is specific
25540 ** to MacOSX and does not work on other unix platforms.  No alternative
25541 ** is available.  If you don't compile for a mac, then the "unix-afp"
25542 ** VFS is not available.
25543 **
25544 ********************* End of the AFP lock implementation **********************
25545 ******************************************************************************/
25546
25547 /******************************************************************************
25548 *************************** Begin NFS Locking ********************************/
25549
25550 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25551 /*
25552  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25553  ** must be either NO_LOCK or SHARED_LOCK.
25554  **
25555  ** If the locking level of the file descriptor is already at or below
25556  ** the requested locking level, this routine is a no-op.
25557  */
25558 static int nfsUnlock(sqlite3_file *id, int eFileLock){
25559   return _posixUnlock(id, eFileLock, 1);
25560 }
25561
25562 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25563 /*
25564 ** The code above is the NFS lock implementation.  The code is specific
25565 ** to MacOSX and does not work on other unix platforms.  No alternative
25566 ** is available.  
25567 **
25568 ********************* End of the NFS lock implementation **********************
25569 ******************************************************************************/
25570
25571 /******************************************************************************
25572 **************** Non-locking sqlite3_file methods *****************************
25573 **
25574 ** The next division contains implementations for all methods of the 
25575 ** sqlite3_file object other than the locking methods.  The locking
25576 ** methods were defined in divisions above (one locking method per
25577 ** division).  Those methods that are common to all locking modes
25578 ** are gather together into this division.
25579 */
25580
25581 /*
25582 ** Seek to the offset passed as the second argument, then read cnt 
25583 ** bytes into pBuf. Return the number of bytes actually read.
25584 **
25585 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
25586 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
25587 ** one system to another.  Since SQLite does not define USE_PREAD
25588 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
25589 ** See tickets #2741 and #2681.
25590 **
25591 ** To avoid stomping the errno value on a failed read the lastErrno value
25592 ** is set before returning.
25593 */
25594 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
25595   int got;
25596 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25597   i64 newOffset;
25598 #endif
25599   TIMER_START;
25600 #if defined(USE_PREAD)
25601   got = pread(id->h, pBuf, cnt, offset);
25602   SimulateIOError( got = -1 );
25603 #elif defined(USE_PREAD64)
25604   got = pread64(id->h, pBuf, cnt, offset);
25605   SimulateIOError( got = -1 );
25606 #else
25607   newOffset = lseek(id->h, offset, SEEK_SET);
25608   SimulateIOError( newOffset-- );
25609   if( newOffset!=offset ){
25610     if( newOffset == -1 ){
25611       ((unixFile*)id)->lastErrno = errno;
25612     }else{
25613       ((unixFile*)id)->lastErrno = 0;                   
25614     }
25615     return -1;
25616   }
25617   got = read(id->h, pBuf, cnt);
25618 #endif
25619   TIMER_END;
25620   if( got<0 ){
25621     ((unixFile*)id)->lastErrno = errno;
25622   }
25623   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25624   return got;
25625 }
25626
25627 /*
25628 ** Read data from a file into a buffer.  Return SQLITE_OK if all
25629 ** bytes were read successfully and SQLITE_IOERR if anything goes
25630 ** wrong.
25631 */
25632 static int unixRead(
25633   sqlite3_file *id, 
25634   void *pBuf, 
25635   int amt,
25636   sqlite3_int64 offset
25637 ){
25638   unixFile *pFile = (unixFile *)id;
25639   int got;
25640   assert( id );
25641
25642   /* If this is a database file (not a journal, master-journal or temp
25643   ** file), the bytes in the locking range should never be read or written. */
25644 #if 0
25645   assert( pFile->pUnused==0
25646        || offset>=PENDING_BYTE+512
25647        || offset+amt<=PENDING_BYTE 
25648   );
25649 #endif
25650
25651   got = seekAndRead(pFile, offset, pBuf, amt);
25652   if( got==amt ){
25653     return SQLITE_OK;
25654   }else if( got<0 ){
25655     /* lastErrno set by seekAndRead */
25656     return SQLITE_IOERR_READ;
25657   }else{
25658     pFile->lastErrno = 0; /* not a system error */
25659     /* Unread parts of the buffer must be zero-filled */
25660     memset(&((char*)pBuf)[got], 0, amt-got);
25661     return SQLITE_IOERR_SHORT_READ;
25662   }
25663 }
25664
25665 /*
25666 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
25667 ** Return the number of bytes actually read.  Update the offset.
25668 **
25669 ** To avoid stomping the errno value on a failed write the lastErrno value
25670 ** is set before returning.
25671 */
25672 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
25673   int got;
25674 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25675   i64 newOffset;
25676 #endif
25677   TIMER_START;
25678 #if defined(USE_PREAD)
25679   got = pwrite(id->h, pBuf, cnt, offset);
25680 #elif defined(USE_PREAD64)
25681   got = pwrite64(id->h, pBuf, cnt, offset);
25682 #else
25683   newOffset = lseek(id->h, offset, SEEK_SET);
25684   if( newOffset!=offset ){
25685     if( newOffset == -1 ){
25686       ((unixFile*)id)->lastErrno = errno;
25687     }else{
25688       ((unixFile*)id)->lastErrno = 0;                   
25689     }
25690     return -1;
25691   }
25692   got = write(id->h, pBuf, cnt);
25693 #endif
25694   TIMER_END;
25695   if( got<0 ){
25696     ((unixFile*)id)->lastErrno = errno;
25697   }
25698
25699   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
25700   return got;
25701 }
25702
25703
25704 /*
25705 ** Write data from a buffer into a file.  Return SQLITE_OK on success
25706 ** or some other error code on failure.
25707 */
25708 static int unixWrite(
25709   sqlite3_file *id, 
25710   const void *pBuf, 
25711   int amt,
25712   sqlite3_int64 offset 
25713 ){
25714   unixFile *pFile = (unixFile*)id;
25715   int wrote = 0;
25716   assert( id );
25717   assert( amt>0 );
25718
25719   /* If this is a database file (not a journal, master-journal or temp
25720   ** file), the bytes in the locking range should never be read or written. */
25721 #if 0
25722   assert( pFile->pUnused==0
25723        || offset>=PENDING_BYTE+512
25724        || offset+amt<=PENDING_BYTE 
25725   );
25726 #endif
25727
25728 #ifndef NDEBUG
25729   /* If we are doing a normal write to a database file (as opposed to
25730   ** doing a hot-journal rollback or a write to some file other than a
25731   ** normal database file) then record the fact that the database
25732   ** has changed.  If the transaction counter is modified, record that
25733   ** fact too.
25734   */
25735   if( pFile->inNormalWrite ){
25736     pFile->dbUpdate = 1;  /* The database has been modified */
25737     if( offset<=24 && offset+amt>=27 ){
25738       int rc;
25739       char oldCntr[4];
25740       SimulateIOErrorBenign(1);
25741       rc = seekAndRead(pFile, 24, oldCntr, 4);
25742       SimulateIOErrorBenign(0);
25743       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
25744         pFile->transCntrChng = 1;  /* The transaction counter has changed */
25745       }
25746     }
25747   }
25748 #endif
25749
25750   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
25751     amt -= wrote;
25752     offset += wrote;
25753     pBuf = &((char*)pBuf)[wrote];
25754   }
25755   SimulateIOError(( wrote=(-1), amt=1 ));
25756   SimulateDiskfullError(( wrote=0, amt=1 ));
25757
25758   if( amt>0 ){
25759     if( wrote<0 ){
25760       /* lastErrno set by seekAndWrite */
25761       return SQLITE_IOERR_WRITE;
25762     }else{
25763       pFile->lastErrno = 0; /* not a system error */
25764       return SQLITE_FULL;
25765     }
25766   }
25767
25768   return SQLITE_OK;
25769 }
25770
25771 #ifdef SQLITE_TEST
25772 /*
25773 ** Count the number of fullsyncs and normal syncs.  This is used to test
25774 ** that syncs and fullsyncs are occurring at the right times.
25775 */
25776 SQLITE_API int sqlite3_sync_count = 0;
25777 SQLITE_API int sqlite3_fullsync_count = 0;
25778 #endif
25779
25780 /*
25781 ** We do not trust systems to provide a working fdatasync().  Some do.
25782 ** Others do no.  To be safe, we will stick with the (slower) fsync().
25783 ** If you know that your system does support fdatasync() correctly,
25784 ** then simply compile with -Dfdatasync=fdatasync
25785 */
25786 #if !defined(fdatasync) && !defined(__linux__)
25787 # define fdatasync fsync
25788 #endif
25789
25790 /*
25791 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
25792 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
25793 ** only available on Mac OS X.  But that could change.
25794 */
25795 #ifdef F_FULLFSYNC
25796 # define HAVE_FULLFSYNC 1
25797 #else
25798 # define HAVE_FULLFSYNC 0
25799 #endif
25800
25801
25802 /*
25803 ** The fsync() system call does not work as advertised on many
25804 ** unix systems.  The following procedure is an attempt to make
25805 ** it work better.
25806 **
25807 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
25808 ** for testing when we want to run through the test suite quickly.
25809 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
25810 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
25811 ** or power failure will likely corrupt the database file.
25812 **
25813 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
25814 ** The idea behind dataOnly is that it should only write the file content
25815 ** to disk, not the inode.  We only set dataOnly if the file size is 
25816 ** unchanged since the file size is part of the inode.  However, 
25817 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
25818 ** file size has changed.  The only real difference between fdatasync()
25819 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
25820 ** inode if the mtime or owner or other inode attributes have changed.
25821 ** We only care about the file size, not the other file attributes, so
25822 ** as far as SQLite is concerned, an fdatasync() is always adequate.
25823 ** So, we always use fdatasync() if it is available, regardless of
25824 ** the value of the dataOnly flag.
25825 */
25826 static int full_fsync(int fd, int fullSync, int dataOnly){
25827   int rc;
25828
25829   /* The following "ifdef/elif/else/" block has the same structure as
25830   ** the one below. It is replicated here solely to avoid cluttering 
25831   ** up the real code with the UNUSED_PARAMETER() macros.
25832   */
25833 #ifdef SQLITE_NO_SYNC
25834   UNUSED_PARAMETER(fd);
25835   UNUSED_PARAMETER(fullSync);
25836   UNUSED_PARAMETER(dataOnly);
25837 #elif HAVE_FULLFSYNC
25838   UNUSED_PARAMETER(dataOnly);
25839 #else
25840   UNUSED_PARAMETER(fullSync);
25841   UNUSED_PARAMETER(dataOnly);
25842 #endif
25843
25844   /* Record the number of times that we do a normal fsync() and 
25845   ** FULLSYNC.  This is used during testing to verify that this procedure
25846   ** gets called with the correct arguments.
25847   */
25848 #ifdef SQLITE_TEST
25849   if( fullSync ) sqlite3_fullsync_count++;
25850   sqlite3_sync_count++;
25851 #endif
25852
25853   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
25854   ** no-op
25855   */
25856 #ifdef SQLITE_NO_SYNC
25857   rc = SQLITE_OK;
25858 #elif HAVE_FULLFSYNC
25859   if( fullSync ){
25860     rc = fcntl(fd, F_FULLFSYNC, 0);
25861   }else{
25862     rc = 1;
25863   }
25864   /* If the FULLFSYNC failed, fall back to attempting an fsync().
25865   ** It shouldn't be possible for fullfsync to fail on the local 
25866   ** file system (on OSX), so failure indicates that FULLFSYNC
25867   ** isn't supported for this file system. So, attempt an fsync 
25868   ** and (for now) ignore the overhead of a superfluous fcntl call.  
25869   ** It'd be better to detect fullfsync support once and avoid 
25870   ** the fcntl call every time sync is called.
25871   */
25872   if( rc ) rc = fsync(fd);
25873
25874 #elif defined(__APPLE__)
25875   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
25876   ** so currently we default to the macro that redefines fdatasync to fsync
25877   */
25878   rc = fsync(fd);
25879 #else 
25880   rc = fdatasync(fd);
25881 #if OS_VXWORKS
25882   if( rc==-1 && errno==ENOTSUP ){
25883     rc = fsync(fd);
25884   }
25885 #endif /* OS_VXWORKS */
25886 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
25887
25888   if( OS_VXWORKS && rc!= -1 ){
25889     rc = 0;
25890   }
25891   return rc;
25892 }
25893
25894 /*
25895 ** Make sure all writes to a particular file are committed to disk.
25896 **
25897 ** If dataOnly==0 then both the file itself and its metadata (file
25898 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
25899 ** file data is synced.
25900 **
25901 ** Under Unix, also make sure that the directory entry for the file
25902 ** has been created by fsync-ing the directory that contains the file.
25903 ** If we do not do this and we encounter a power failure, the directory
25904 ** entry for the journal might not exist after we reboot.  The next
25905 ** SQLite to access the file will not know that the journal exists (because
25906 ** the directory entry for the journal was never created) and the transaction
25907 ** will not roll back - possibly leading to database corruption.
25908 */
25909 static int unixSync(sqlite3_file *id, int flags){
25910   int rc;
25911   unixFile *pFile = (unixFile*)id;
25912
25913   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
25914   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
25915
25916   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
25917   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
25918       || (flags&0x0F)==SQLITE_SYNC_FULL
25919   );
25920
25921   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
25922   ** line is to test that doing so does not cause any problems.
25923   */
25924   SimulateDiskfullError( return SQLITE_FULL );
25925
25926   assert( pFile );
25927   OSTRACE(("SYNC    %-3d\n", pFile->h));
25928   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
25929   SimulateIOError( rc=1 );
25930   if( rc ){
25931     pFile->lastErrno = errno;
25932     return SQLITE_IOERR_FSYNC;
25933   }
25934   if( pFile->dirfd>=0 ){
25935     int err;
25936     OSTRACE(("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
25937             HAVE_FULLFSYNC, isFullsync));
25938 #ifndef SQLITE_DISABLE_DIRSYNC
25939     /* The directory sync is only attempted if full_fsync is
25940     ** turned off or unavailable.  If a full_fsync occurred above,
25941     ** then the directory sync is superfluous.
25942     */
25943     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
25944        /*
25945        ** We have received multiple reports of fsync() returning
25946        ** errors when applied to directories on certain file systems.
25947        ** A failed directory sync is not a big deal.  So it seems
25948        ** better to ignore the error.  Ticket #1657
25949        */
25950        /* pFile->lastErrno = errno; */
25951        /* return SQLITE_IOERR; */
25952     }
25953 #endif
25954     err = close(pFile->dirfd); /* Only need to sync once, so close the */
25955     if( err==0 ){              /* directory when we are done */
25956       pFile->dirfd = -1;
25957     }else{
25958       pFile->lastErrno = errno;
25959       rc = SQLITE_IOERR_DIR_CLOSE;
25960     }
25961   }
25962   return rc;
25963 }
25964
25965 /*
25966 ** Truncate an open file to a specified size
25967 */
25968 static int unixTruncate(sqlite3_file *id, i64 nByte){
25969   unixFile *pFile = (unixFile *)id;
25970   int rc;
25971   assert( pFile );
25972   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
25973
25974   /* If the user has configured a chunk-size for this file, truncate the
25975   ** file so that it consists of an integer number of chunks (i.e. the
25976   ** actual file size after the operation may be larger than the requested
25977   ** size).
25978   */
25979   if( pFile->szChunk ){
25980     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
25981   }
25982
25983   rc = ftruncate(pFile->h, (off_t)nByte);
25984   if( rc ){
25985     pFile->lastErrno = errno;
25986     return SQLITE_IOERR_TRUNCATE;
25987   }else{
25988 #ifndef NDEBUG
25989     /* If we are doing a normal write to a database file (as opposed to
25990     ** doing a hot-journal rollback or a write to some file other than a
25991     ** normal database file) and we truncate the file to zero length,
25992     ** that effectively updates the change counter.  This might happen
25993     ** when restoring a database using the backup API from a zero-length
25994     ** source.
25995     */
25996     if( pFile->inNormalWrite && nByte==0 ){
25997       pFile->transCntrChng = 1;
25998     }
25999 #endif
26000
26001     return SQLITE_OK;
26002   }
26003 }
26004
26005 /*
26006 ** Determine the current size of a file in bytes
26007 */
26008 static int unixFileSize(sqlite3_file *id, i64 *pSize){
26009   int rc;
26010   struct stat buf;
26011   assert( id );
26012   rc = fstat(((unixFile*)id)->h, &buf);
26013   SimulateIOError( rc=1 );
26014   if( rc!=0 ){
26015     ((unixFile*)id)->lastErrno = errno;
26016     return SQLITE_IOERR_FSTAT;
26017   }
26018   *pSize = buf.st_size;
26019
26020   /* When opening a zero-size database, the findInodeInfo() procedure
26021   ** writes a single byte into that file in order to work around a bug
26022   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
26023   ** layers, we need to report this file size as zero even though it is
26024   ** really 1.   Ticket #3260.
26025   */
26026   if( *pSize==1 ) *pSize = 0;
26027
26028
26029   return SQLITE_OK;
26030 }
26031
26032 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26033 /*
26034 ** Handler for proxy-locking file-control verbs.  Defined below in the
26035 ** proxying locking division.
26036 */
26037 static int proxyFileControl(sqlite3_file*,int,void*);
26038 #endif
26039
26040 /* 
26041 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
26042 ** file-control operation.
26043 **
26044 ** If the user has configured a chunk-size for this file, it could be
26045 ** that the file needs to be extended at this point. Otherwise, the
26046 ** SQLITE_FCNTL_SIZE_HINT operation is a no-op for Unix.
26047 */
26048 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
26049   if( pFile->szChunk ){
26050     i64 nSize;                    /* Required file size */
26051     struct stat buf;              /* Used to hold return values of fstat() */
26052    
26053     if( fstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
26054
26055     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
26056     if( nSize>(i64)buf.st_size ){
26057 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
26058       if( posix_fallocate(pFile->h, buf.st_size, nSize-buf.st_size) ){
26059         return SQLITE_IOERR_WRITE;
26060       }
26061 #else
26062       /* If the OS does not have posix_fallocate(), fake it. First use
26063       ** ftruncate() to set the file size, then write a single byte to
26064       ** the last byte in each block within the extended region. This
26065       ** is the same technique used by glibc to implement posix_fallocate()
26066       ** on systems that do not have a real fallocate() system call.
26067       */
26068       int nBlk = buf.st_blksize;  /* File-system block size */
26069       i64 iWrite;                 /* Next offset to write to */
26070       int nWrite;                 /* Return value from seekAndWrite() */
26071
26072       if( ftruncate(pFile->h, nSize) ){
26073         pFile->lastErrno = errno;
26074         return SQLITE_IOERR_TRUNCATE;
26075       }
26076       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
26077       do {
26078         nWrite = seekAndWrite(pFile, iWrite, "", 1);
26079         iWrite += nBlk;
26080       } while( nWrite==1 && iWrite<nSize );
26081       if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
26082 #endif
26083     }
26084   }
26085
26086   return SQLITE_OK;
26087 }
26088
26089 /*
26090 ** Information and control of an open file handle.
26091 */
26092 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
26093   switch( op ){
26094     case SQLITE_FCNTL_LOCKSTATE: {
26095       *(int*)pArg = ((unixFile*)id)->eFileLock;
26096       return SQLITE_OK;
26097     }
26098     case SQLITE_LAST_ERRNO: {
26099       *(int*)pArg = ((unixFile*)id)->lastErrno;
26100       return SQLITE_OK;
26101     }
26102     case SQLITE_FCNTL_CHUNK_SIZE: {
26103       ((unixFile*)id)->szChunk = *(int *)pArg;
26104       return SQLITE_OK;
26105     }
26106     case SQLITE_FCNTL_SIZE_HINT: {
26107       return fcntlSizeHint((unixFile *)id, *(i64 *)pArg);
26108     }
26109 #ifndef NDEBUG
26110     /* The pager calls this method to signal that it has done
26111     ** a rollback and that the database is therefore unchanged and
26112     ** it hence it is OK for the transaction change counter to be
26113     ** unchanged.
26114     */
26115     case SQLITE_FCNTL_DB_UNCHANGED: {
26116       ((unixFile*)id)->dbUpdate = 0;
26117       return SQLITE_OK;
26118     }
26119 #endif
26120 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26121     case SQLITE_SET_LOCKPROXYFILE:
26122     case SQLITE_GET_LOCKPROXYFILE: {
26123       return proxyFileControl(id,op,pArg);
26124     }
26125 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
26126   }
26127   return SQLITE_ERROR;
26128 }
26129
26130 /*
26131 ** Return the sector size in bytes of the underlying block device for
26132 ** the specified file. This is almost always 512 bytes, but may be
26133 ** larger for some devices.
26134 **
26135 ** SQLite code assumes this function cannot fail. It also assumes that
26136 ** if two files are created in the same file-system directory (i.e.
26137 ** a database and its journal file) that the sector size will be the
26138 ** same for both.
26139 */
26140 static int unixSectorSize(sqlite3_file *NotUsed){
26141   UNUSED_PARAMETER(NotUsed);
26142   return SQLITE_DEFAULT_SECTOR_SIZE;
26143 }
26144
26145 /*
26146 ** Return the device characteristics for the file. This is always 0 for unix.
26147 */
26148 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
26149   UNUSED_PARAMETER(NotUsed);
26150   return 0;
26151 }
26152
26153 #ifndef SQLITE_OMIT_WAL
26154
26155
26156 /*
26157 ** Object used to represent an shared memory buffer.  
26158 **
26159 ** When multiple threads all reference the same wal-index, each thread
26160 ** has its own unixShm object, but they all point to a single instance
26161 ** of this unixShmNode object.  In other words, each wal-index is opened
26162 ** only once per process.
26163 **
26164 ** Each unixShmNode object is connected to a single unixInodeInfo object.
26165 ** We could coalesce this object into unixInodeInfo, but that would mean
26166 ** every open file that does not use shared memory (in other words, most
26167 ** open files) would have to carry around this extra information.  So
26168 ** the unixInodeInfo object contains a pointer to this unixShmNode object
26169 ** and the unixShmNode object is created only when needed.
26170 **
26171 ** unixMutexHeld() must be true when creating or destroying
26172 ** this object or while reading or writing the following fields:
26173 **
26174 **      nRef
26175 **
26176 ** The following fields are read-only after the object is created:
26177 ** 
26178 **      fid
26179 **      zFilename
26180 **
26181 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
26182 ** unixMutexHeld() is true when reading or writing any other field
26183 ** in this structure.
26184 */
26185 struct unixShmNode {
26186   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
26187   sqlite3_mutex *mutex;      /* Mutex to access this object */
26188   char *zFilename;           /* Name of the mmapped file */
26189   int h;                     /* Open file descriptor */
26190   int szRegion;              /* Size of shared-memory regions */
26191   int nRegion;               /* Size of array apRegion */
26192   char **apRegion;           /* Array of mapped shared-memory regions */
26193   int nRef;                  /* Number of unixShm objects pointing to this */
26194   unixShm *pFirst;           /* All unixShm objects pointing to this */
26195 #ifdef SQLITE_DEBUG
26196   u8 exclMask;               /* Mask of exclusive locks held */
26197   u8 sharedMask;             /* Mask of shared locks held */
26198   u8 nextShmId;              /* Next available unixShm.id value */
26199 #endif
26200 };
26201
26202 /*
26203 ** Structure used internally by this VFS to record the state of an
26204 ** open shared memory connection.
26205 **
26206 ** The following fields are initialized when this object is created and
26207 ** are read-only thereafter:
26208 **
26209 **    unixShm.pFile
26210 **    unixShm.id
26211 **
26212 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
26213 ** while accessing any read/write fields.
26214 */
26215 struct unixShm {
26216   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
26217   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
26218   u8 hasMutex;               /* True if holding the unixShmNode mutex */
26219   u16 sharedMask;            /* Mask of shared locks held */
26220   u16 exclMask;              /* Mask of exclusive locks held */
26221 #ifdef SQLITE_DEBUG
26222   u8 id;                     /* Id of this connection within its unixShmNode */
26223 #endif
26224 };
26225
26226 /*
26227 ** Constants used for locking
26228 */
26229 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
26230 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
26231
26232 /*
26233 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
26234 **
26235 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
26236 ** otherwise.
26237 */
26238 static int unixShmSystemLock(
26239   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
26240   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
26241   int ofst,              /* First byte of the locking range */
26242   int n                  /* Number of bytes to lock */
26243 ){
26244   struct flock f;       /* The posix advisory locking structure */
26245   int rc = SQLITE_OK;   /* Result code form fcntl() */
26246
26247   /* Access to the unixShmNode object is serialized by the caller */
26248   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
26249
26250   /* Shared locks never span more than one byte */
26251   assert( n==1 || lockType!=F_RDLCK );
26252
26253   /* Locks are within range */
26254   assert( n>=1 && n<SQLITE_SHM_NLOCK );
26255
26256   /* Initialize the locking parameters */
26257   memset(&f, 0, sizeof(f));
26258   f.l_type = lockType;
26259   f.l_whence = SEEK_SET;
26260   f.l_start = ofst;
26261   f.l_len = n;
26262
26263   rc = fcntl(pShmNode->h, F_SETLK, &f);
26264   rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
26265
26266   /* Update the global lock state and do debug tracing */
26267 #ifdef SQLITE_DEBUG
26268   { u16 mask;
26269   OSTRACE(("SHM-LOCK "));
26270   mask = (1<<(ofst+n)) - (1<<ofst);
26271   if( rc==SQLITE_OK ){
26272     if( lockType==F_UNLCK ){
26273       OSTRACE(("unlock %d ok", ofst));
26274       pShmNode->exclMask &= ~mask;
26275       pShmNode->sharedMask &= ~mask;
26276     }else if( lockType==F_RDLCK ){
26277       OSTRACE(("read-lock %d ok", ofst));
26278       pShmNode->exclMask &= ~mask;
26279       pShmNode->sharedMask |= mask;
26280     }else{
26281       assert( lockType==F_WRLCK );
26282       OSTRACE(("write-lock %d ok", ofst));
26283       pShmNode->exclMask |= mask;
26284       pShmNode->sharedMask &= ~mask;
26285     }
26286   }else{
26287     if( lockType==F_UNLCK ){
26288       OSTRACE(("unlock %d failed", ofst));
26289     }else if( lockType==F_RDLCK ){
26290       OSTRACE(("read-lock failed"));
26291     }else{
26292       assert( lockType==F_WRLCK );
26293       OSTRACE(("write-lock %d failed", ofst));
26294     }
26295   }
26296   OSTRACE((" - afterwards %03x,%03x\n",
26297            pShmNode->sharedMask, pShmNode->exclMask));
26298   }
26299 #endif
26300
26301   return rc;        
26302 }
26303
26304
26305 /*
26306 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
26307 **
26308 ** This is not a VFS shared-memory method; it is a utility function called
26309 ** by VFS shared-memory methods.
26310 */
26311 static void unixShmPurge(unixFile *pFd){
26312   unixShmNode *p = pFd->pInode->pShmNode;
26313   assert( unixMutexHeld() );
26314   if( p && p->nRef==0 ){
26315     int i;
26316     assert( p->pInode==pFd->pInode );
26317     if( p->mutex ) sqlite3_mutex_free(p->mutex);
26318     for(i=0; i<p->nRegion; i++){
26319       munmap(p->apRegion[i], p->szRegion);
26320     }
26321     sqlite3_free(p->apRegion);
26322     if( p->h>=0 ) close(p->h);
26323     p->pInode->pShmNode = 0;
26324     sqlite3_free(p);
26325   }
26326 }
26327
26328 /*
26329 ** Open a shared-memory area associated with open database file pDbFd.  
26330 ** This particular implementation uses mmapped files.
26331 **
26332 ** The file used to implement shared-memory is in the same directory
26333 ** as the open database file and has the same name as the open database
26334 ** file with the "-shm" suffix added.  For example, if the database file
26335 ** is "/home/user1/config.db" then the file that is created and mmapped
26336 ** for shared memory will be called "/home/user1/config.db-shm".  
26337 **
26338 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
26339 ** some other tmpfs mount. But if a file in a different directory
26340 ** from the database file is used, then differing access permissions
26341 ** or a chroot() might cause two different processes on the same
26342 ** database to end up using different files for shared memory - 
26343 ** meaning that their memory would not really be shared - resulting
26344 ** in database corruption.  Nevertheless, this tmpfs file usage
26345 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
26346 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
26347 ** option results in an incompatible build of SQLite;  builds of SQLite
26348 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
26349 ** same database file at the same time, database corruption will likely
26350 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
26351 ** "unsupported" and may go away in a future SQLite release.
26352 **
26353 ** When opening a new shared-memory file, if no other instances of that
26354 ** file are currently open, in this process or in other processes, then
26355 ** the file must be truncated to zero length or have its header cleared.
26356 */
26357 static int unixOpenSharedMemory(unixFile *pDbFd){
26358   struct unixShm *p = 0;          /* The connection to be opened */
26359   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
26360   int rc;                         /* Result code */
26361   unixInodeInfo *pInode;          /* The inode of fd */
26362   char *zShmFilename;             /* Name of the file used for SHM */
26363   int nShmFilename;               /* Size of the SHM filename in bytes */
26364
26365   /* Allocate space for the new unixShm object. */
26366   p = sqlite3_malloc( sizeof(*p) );
26367   if( p==0 ) return SQLITE_NOMEM;
26368   memset(p, 0, sizeof(*p));
26369   assert( pDbFd->pShm==0 );
26370
26371   /* Check to see if a unixShmNode object already exists. Reuse an existing
26372   ** one if present. Create a new one if necessary.
26373   */
26374   unixEnterMutex();
26375   pInode = pDbFd->pInode;
26376   pShmNode = pInode->pShmNode;
26377   if( pShmNode==0 ){
26378     struct stat sStat;                 /* fstat() info for database file */
26379
26380     /* Call fstat() to figure out the permissions on the database file. If
26381     ** a new *-shm file is created, an attempt will be made to create it
26382     ** with the same permissions. The actual permissions the file is created
26383     ** with are subject to the current umask setting.
26384     */
26385     if( fstat(pDbFd->h, &sStat) ){
26386       rc = SQLITE_IOERR_FSTAT;
26387       goto shm_open_err;
26388     }
26389
26390 #ifdef SQLITE_SHM_DIRECTORY
26391     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
26392 #else
26393     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
26394 #endif
26395     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
26396     if( pShmNode==0 ){
26397       rc = SQLITE_NOMEM;
26398       goto shm_open_err;
26399     }
26400     memset(pShmNode, 0, sizeof(*pShmNode));
26401     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
26402 #ifdef SQLITE_SHM_DIRECTORY
26403     sqlite3_snprintf(nShmFilename, zShmFilename, 
26404                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
26405                      (u32)sStat.st_ino, (u32)sStat.st_dev);
26406 #else
26407     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
26408 #endif
26409     pShmNode->h = -1;
26410     pDbFd->pInode->pShmNode = pShmNode;
26411     pShmNode->pInode = pDbFd->pInode;
26412     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
26413     if( pShmNode->mutex==0 ){
26414       rc = SQLITE_NOMEM;
26415       goto shm_open_err;
26416     }
26417
26418     pShmNode->h = open(zShmFilename, O_RDWR|O_CREAT, (sStat.st_mode & 0777));
26419     if( pShmNode->h<0 ){
26420       rc = SQLITE_CANTOPEN_BKPT;
26421       goto shm_open_err;
26422     }
26423
26424     /* Check to see if another process is holding the dead-man switch.
26425     ** If not, truncate the file to zero length. 
26426     */
26427     rc = SQLITE_OK;
26428     if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
26429       if( ftruncate(pShmNode->h, 0) ){
26430         rc = SQLITE_IOERR_SHMOPEN;
26431       }
26432     }
26433     if( rc==SQLITE_OK ){
26434       rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
26435     }
26436     if( rc ) goto shm_open_err;
26437   }
26438
26439   /* Make the new connection a child of the unixShmNode */
26440   p->pShmNode = pShmNode;
26441 #ifdef SQLITE_DEBUG
26442   p->id = pShmNode->nextShmId++;
26443 #endif
26444   pShmNode->nRef++;
26445   pDbFd->pShm = p;
26446   unixLeaveMutex();
26447
26448   /* The reference count on pShmNode has already been incremented under
26449   ** the cover of the unixEnterMutex() mutex and the pointer from the
26450   ** new (struct unixShm) object to the pShmNode has been set. All that is
26451   ** left to do is to link the new object into the linked list starting
26452   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
26453   ** mutex.
26454   */
26455   sqlite3_mutex_enter(pShmNode->mutex);
26456   p->pNext = pShmNode->pFirst;
26457   pShmNode->pFirst = p;
26458   sqlite3_mutex_leave(pShmNode->mutex);
26459   return SQLITE_OK;
26460
26461   /* Jump here on any error */
26462 shm_open_err:
26463   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
26464   sqlite3_free(p);
26465   unixLeaveMutex();
26466   return rc;
26467 }
26468
26469 /*
26470 ** This function is called to obtain a pointer to region iRegion of the 
26471 ** shared-memory associated with the database file fd. Shared-memory regions 
26472 ** are numbered starting from zero. Each shared-memory region is szRegion 
26473 ** bytes in size.
26474 **
26475 ** If an error occurs, an error code is returned and *pp is set to NULL.
26476 **
26477 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
26478 ** region has not been allocated (by any client, including one running in a
26479 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
26480 ** bExtend is non-zero and the requested shared-memory region has not yet 
26481 ** been allocated, it is allocated by this function.
26482 **
26483 ** If the shared-memory region has already been allocated or is allocated by
26484 ** this call as described above, then it is mapped into this processes 
26485 ** address space (if it is not already), *pp is set to point to the mapped 
26486 ** memory and SQLITE_OK returned.
26487 */
26488 static int unixShmMap(
26489   sqlite3_file *fd,               /* Handle open on database file */
26490   int iRegion,                    /* Region to retrieve */
26491   int szRegion,                   /* Size of regions */
26492   int bExtend,                    /* True to extend file if necessary */
26493   void volatile **pp              /* OUT: Mapped memory */
26494 ){
26495   unixFile *pDbFd = (unixFile*)fd;
26496   unixShm *p;
26497   unixShmNode *pShmNode;
26498   int rc = SQLITE_OK;
26499
26500   /* If the shared-memory file has not yet been opened, open it now. */
26501   if( pDbFd->pShm==0 ){
26502     rc = unixOpenSharedMemory(pDbFd);
26503     if( rc!=SQLITE_OK ) return rc;
26504   }
26505
26506   p = pDbFd->pShm;
26507   pShmNode = p->pShmNode;
26508   sqlite3_mutex_enter(pShmNode->mutex);
26509   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
26510
26511   if( pShmNode->nRegion<=iRegion ){
26512     char **apNew;                      /* New apRegion[] array */
26513     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
26514     struct stat sStat;                 /* Used by fstat() */
26515
26516     pShmNode->szRegion = szRegion;
26517
26518     /* The requested region is not mapped into this processes address space.
26519     ** Check to see if it has been allocated (i.e. if the wal-index file is
26520     ** large enough to contain the requested region).
26521     */
26522     if( fstat(pShmNode->h, &sStat) ){
26523       rc = SQLITE_IOERR_SHMSIZE;
26524       goto shmpage_out;
26525     }
26526
26527     if( sStat.st_size<nByte ){
26528       /* The requested memory region does not exist. If bExtend is set to
26529       ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
26530       **
26531       ** Alternatively, if bExtend is true, use ftruncate() to allocate
26532       ** the requested memory region.
26533       */
26534       if( !bExtend ) goto shmpage_out;
26535       if( ftruncate(pShmNode->h, nByte) ){
26536         rc = SQLITE_IOERR_SHMSIZE;
26537         goto shmpage_out;
26538       }
26539     }
26540
26541     /* Map the requested memory region into this processes address space. */
26542     apNew = (char **)sqlite3_realloc(
26543         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
26544     );
26545     if( !apNew ){
26546       rc = SQLITE_IOERR_NOMEM;
26547       goto shmpage_out;
26548     }
26549     pShmNode->apRegion = apNew;
26550     while(pShmNode->nRegion<=iRegion){
26551       void *pMem = mmap(0, szRegion, PROT_READ|PROT_WRITE, 
26552           MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
26553       );
26554       if( pMem==MAP_FAILED ){
26555         rc = SQLITE_IOERR;
26556         goto shmpage_out;
26557       }
26558       pShmNode->apRegion[pShmNode->nRegion] = pMem;
26559       pShmNode->nRegion++;
26560     }
26561   }
26562
26563 shmpage_out:
26564   if( pShmNode->nRegion>iRegion ){
26565     *pp = pShmNode->apRegion[iRegion];
26566   }else{
26567     *pp = 0;
26568   }
26569   sqlite3_mutex_leave(pShmNode->mutex);
26570   return rc;
26571 }
26572
26573 /*
26574 ** Change the lock state for a shared-memory segment.
26575 **
26576 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
26577 ** different here than in posix.  In xShmLock(), one can go from unlocked
26578 ** to shared and back or from unlocked to exclusive and back.  But one may
26579 ** not go from shared to exclusive or from exclusive to shared.
26580 */
26581 static int unixShmLock(
26582   sqlite3_file *fd,          /* Database file holding the shared memory */
26583   int ofst,                  /* First lock to acquire or release */
26584   int n,                     /* Number of locks to acquire or release */
26585   int flags                  /* What to do with the lock */
26586 ){
26587   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
26588   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
26589   unixShm *pX;                          /* For looping over all siblings */
26590   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
26591   int rc = SQLITE_OK;                   /* Result code */
26592   u16 mask;                             /* Mask of locks to take or release */
26593
26594   assert( pShmNode==pDbFd->pInode->pShmNode );
26595   assert( pShmNode->pInode==pDbFd->pInode );
26596   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
26597   assert( n>=1 );
26598   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
26599        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
26600        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
26601        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
26602   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
26603
26604   mask = (1<<(ofst+n)) - (1<<ofst);
26605   assert( n>1 || mask==(1<<ofst) );
26606   sqlite3_mutex_enter(pShmNode->mutex);
26607   if( flags & SQLITE_SHM_UNLOCK ){
26608     u16 allMask = 0; /* Mask of locks held by siblings */
26609
26610     /* See if any siblings hold this same lock */
26611     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26612       if( pX==p ) continue;
26613       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
26614       allMask |= pX->sharedMask;
26615     }
26616
26617     /* Unlock the system-level locks */
26618     if( (mask & allMask)==0 ){
26619       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
26620     }else{
26621       rc = SQLITE_OK;
26622     }
26623
26624     /* Undo the local locks */
26625     if( rc==SQLITE_OK ){
26626       p->exclMask &= ~mask;
26627       p->sharedMask &= ~mask;
26628     } 
26629   }else if( flags & SQLITE_SHM_SHARED ){
26630     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
26631
26632     /* Find out which shared locks are already held by sibling connections.
26633     ** If any sibling already holds an exclusive lock, go ahead and return
26634     ** SQLITE_BUSY.
26635     */
26636     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26637       if( (pX->exclMask & mask)!=0 ){
26638         rc = SQLITE_BUSY;
26639         break;
26640       }
26641       allShared |= pX->sharedMask;
26642     }
26643
26644     /* Get shared locks at the system level, if necessary */
26645     if( rc==SQLITE_OK ){
26646       if( (allShared & mask)==0 ){
26647         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
26648       }else{
26649         rc = SQLITE_OK;
26650       }
26651     }
26652
26653     /* Get the local shared locks */
26654     if( rc==SQLITE_OK ){
26655       p->sharedMask |= mask;
26656     }
26657   }else{
26658     /* Make sure no sibling connections hold locks that will block this
26659     ** lock.  If any do, return SQLITE_BUSY right away.
26660     */
26661     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
26662       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
26663         rc = SQLITE_BUSY;
26664         break;
26665       }
26666     }
26667   
26668     /* Get the exclusive locks at the system level.  Then if successful
26669     ** also mark the local connection as being locked.
26670     */
26671     if( rc==SQLITE_OK ){
26672       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
26673       if( rc==SQLITE_OK ){
26674         assert( (p->sharedMask & mask)==0 );
26675         p->exclMask |= mask;
26676       }
26677     }
26678   }
26679   sqlite3_mutex_leave(pShmNode->mutex);
26680   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
26681            p->id, getpid(), p->sharedMask, p->exclMask));
26682   return rc;
26683 }
26684
26685 /*
26686 ** Implement a memory barrier or memory fence on shared memory.  
26687 **
26688 ** All loads and stores begun before the barrier must complete before
26689 ** any load or store begun after the barrier.
26690 */
26691 static void unixShmBarrier(
26692   sqlite3_file *fd                /* Database file holding the shared memory */
26693 ){
26694   UNUSED_PARAMETER(fd);
26695   unixEnterMutex();
26696   unixLeaveMutex();
26697 }
26698
26699 /*
26700 ** Close a connection to shared-memory.  Delete the underlying 
26701 ** storage if deleteFlag is true.
26702 **
26703 ** If there is no shared memory associated with the connection then this
26704 ** routine is a harmless no-op.
26705 */
26706 static int unixShmUnmap(
26707   sqlite3_file *fd,               /* The underlying database file */
26708   int deleteFlag                  /* Delete shared-memory if true */
26709 ){
26710   unixShm *p;                     /* The connection to be closed */
26711   unixShmNode *pShmNode;          /* The underlying shared-memory file */
26712   unixShm **pp;                   /* For looping over sibling connections */
26713   unixFile *pDbFd;                /* The underlying database file */
26714
26715   pDbFd = (unixFile*)fd;
26716   p = pDbFd->pShm;
26717   if( p==0 ) return SQLITE_OK;
26718   pShmNode = p->pShmNode;
26719
26720   assert( pShmNode==pDbFd->pInode->pShmNode );
26721   assert( pShmNode->pInode==pDbFd->pInode );
26722
26723   /* Remove connection p from the set of connections associated
26724   ** with pShmNode */
26725   sqlite3_mutex_enter(pShmNode->mutex);
26726   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
26727   *pp = p->pNext;
26728
26729   /* Free the connection p */
26730   sqlite3_free(p);
26731   pDbFd->pShm = 0;
26732   sqlite3_mutex_leave(pShmNode->mutex);
26733
26734   /* If pShmNode->nRef has reached 0, then close the underlying
26735   ** shared-memory file, too */
26736   unixEnterMutex();
26737   assert( pShmNode->nRef>0 );
26738   pShmNode->nRef--;
26739   if( pShmNode->nRef==0 ){
26740     if( deleteFlag ) unlink(pShmNode->zFilename);
26741     unixShmPurge(pDbFd);
26742   }
26743   unixLeaveMutex();
26744
26745   return SQLITE_OK;
26746 }
26747
26748
26749 #else
26750 # define unixShmMap     0
26751 # define unixShmLock    0
26752 # define unixShmBarrier 0
26753 # define unixShmUnmap   0
26754 #endif /* #ifndef SQLITE_OMIT_WAL */
26755
26756 /*
26757 ** Here ends the implementation of all sqlite3_file methods.
26758 **
26759 ********************** End sqlite3_file Methods *******************************
26760 ******************************************************************************/
26761
26762 /*
26763 ** This division contains definitions of sqlite3_io_methods objects that
26764 ** implement various file locking strategies.  It also contains definitions
26765 ** of "finder" functions.  A finder-function is used to locate the appropriate
26766 ** sqlite3_io_methods object for a particular database file.  The pAppData
26767 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
26768 ** the correct finder-function for that VFS.
26769 **
26770 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
26771 ** object.  The only interesting finder-function is autolockIoFinder, which
26772 ** looks at the filesystem type and tries to guess the best locking
26773 ** strategy from that.
26774 **
26775 ** For finder-funtion F, two objects are created:
26776 **
26777 **    (1) The real finder-function named "FImpt()".
26778 **
26779 **    (2) A constant pointer to this function named just "F".
26780 **
26781 **
26782 ** A pointer to the F pointer is used as the pAppData value for VFS
26783 ** objects.  We have to do this instead of letting pAppData point
26784 ** directly at the finder-function since C90 rules prevent a void*
26785 ** from be cast into a function pointer.
26786 **
26787 **
26788 ** Each instance of this macro generates two objects:
26789 **
26790 **   *  A constant sqlite3_io_methods object call METHOD that has locking
26791 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
26792 **
26793 **   *  An I/O method finder function called FINDER that returns a pointer
26794 **      to the METHOD object in the previous bullet.
26795 */
26796 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
26797 static const sqlite3_io_methods METHOD = {                                   \
26798    VERSION,                    /* iVersion */                                \
26799    CLOSE,                      /* xClose */                                  \
26800    unixRead,                   /* xRead */                                   \
26801    unixWrite,                  /* xWrite */                                  \
26802    unixTruncate,               /* xTruncate */                               \
26803    unixSync,                   /* xSync */                                   \
26804    unixFileSize,               /* xFileSize */                               \
26805    LOCK,                       /* xLock */                                   \
26806    UNLOCK,                     /* xUnlock */                                 \
26807    CKLOCK,                     /* xCheckReservedLock */                      \
26808    unixFileControl,            /* xFileControl */                            \
26809    unixSectorSize,             /* xSectorSize */                             \
26810    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
26811    unixShmMap,                 /* xShmMap */                                 \
26812    unixShmLock,                /* xShmLock */                                \
26813    unixShmBarrier,             /* xShmBarrier */                             \
26814    unixShmUnmap                /* xShmUnmap */                               \
26815 };                                                                           \
26816 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
26817   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
26818   return &METHOD;                                                            \
26819 }                                                                            \
26820 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
26821     = FINDER##Impl;
26822
26823 /*
26824 ** Here are all of the sqlite3_io_methods objects for each of the
26825 ** locking strategies.  Functions that return pointers to these methods
26826 ** are also created.
26827 */
26828 IOMETHODS(
26829   posixIoFinder,            /* Finder function name */
26830   posixIoMethods,           /* sqlite3_io_methods object name */
26831   2,                        /* shared memory is enabled */
26832   unixClose,                /* xClose method */
26833   unixLock,                 /* xLock method */
26834   unixUnlock,               /* xUnlock method */
26835   unixCheckReservedLock     /* xCheckReservedLock method */
26836 )
26837 IOMETHODS(
26838   nolockIoFinder,           /* Finder function name */
26839   nolockIoMethods,          /* sqlite3_io_methods object name */
26840   1,                        /* shared memory is disabled */
26841   nolockClose,              /* xClose method */
26842   nolockLock,               /* xLock method */
26843   nolockUnlock,             /* xUnlock method */
26844   nolockCheckReservedLock   /* xCheckReservedLock method */
26845 )
26846 IOMETHODS(
26847   dotlockIoFinder,          /* Finder function name */
26848   dotlockIoMethods,         /* sqlite3_io_methods object name */
26849   1,                        /* shared memory is disabled */
26850   dotlockClose,             /* xClose method */
26851   dotlockLock,              /* xLock method */
26852   dotlockUnlock,            /* xUnlock method */
26853   dotlockCheckReservedLock  /* xCheckReservedLock method */
26854 )
26855
26856 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26857 IOMETHODS(
26858   flockIoFinder,            /* Finder function name */
26859   flockIoMethods,           /* sqlite3_io_methods object name */
26860   1,                        /* shared memory is disabled */
26861   flockClose,               /* xClose method */
26862   flockLock,                /* xLock method */
26863   flockUnlock,              /* xUnlock method */
26864   flockCheckReservedLock    /* xCheckReservedLock method */
26865 )
26866 #endif
26867
26868 #if OS_VXWORKS
26869 IOMETHODS(
26870   semIoFinder,              /* Finder function name */
26871   semIoMethods,             /* sqlite3_io_methods object name */
26872   1,                        /* shared memory is disabled */
26873   semClose,                 /* xClose method */
26874   semLock,                  /* xLock method */
26875   semUnlock,                /* xUnlock method */
26876   semCheckReservedLock      /* xCheckReservedLock method */
26877 )
26878 #endif
26879
26880 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26881 IOMETHODS(
26882   afpIoFinder,              /* Finder function name */
26883   afpIoMethods,             /* sqlite3_io_methods object name */
26884   1,                        /* shared memory is disabled */
26885   afpClose,                 /* xClose method */
26886   afpLock,                  /* xLock method */
26887   afpUnlock,                /* xUnlock method */
26888   afpCheckReservedLock      /* xCheckReservedLock method */
26889 )
26890 #endif
26891
26892 /*
26893 ** The proxy locking method is a "super-method" in the sense that it
26894 ** opens secondary file descriptors for the conch and lock files and
26895 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
26896 ** secondary files.  For this reason, the division that implements
26897 ** proxy locking is located much further down in the file.  But we need
26898 ** to go ahead and define the sqlite3_io_methods and finder function
26899 ** for proxy locking here.  So we forward declare the I/O methods.
26900 */
26901 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26902 static int proxyClose(sqlite3_file*);
26903 static int proxyLock(sqlite3_file*, int);
26904 static int proxyUnlock(sqlite3_file*, int);
26905 static int proxyCheckReservedLock(sqlite3_file*, int*);
26906 IOMETHODS(
26907   proxyIoFinder,            /* Finder function name */
26908   proxyIoMethods,           /* sqlite3_io_methods object name */
26909   1,                        /* shared memory is disabled */
26910   proxyClose,               /* xClose method */
26911   proxyLock,                /* xLock method */
26912   proxyUnlock,              /* xUnlock method */
26913   proxyCheckReservedLock    /* xCheckReservedLock method */
26914 )
26915 #endif
26916
26917 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
26918 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26919 IOMETHODS(
26920   nfsIoFinder,               /* Finder function name */
26921   nfsIoMethods,              /* sqlite3_io_methods object name */
26922   1,                         /* shared memory is disabled */
26923   unixClose,                 /* xClose method */
26924   unixLock,                  /* xLock method */
26925   nfsUnlock,                 /* xUnlock method */
26926   unixCheckReservedLock      /* xCheckReservedLock method */
26927 )
26928 #endif
26929
26930 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26931 /* 
26932 ** This "finder" function attempts to determine the best locking strategy 
26933 ** for the database file "filePath".  It then returns the sqlite3_io_methods
26934 ** object that implements that strategy.
26935 **
26936 ** This is for MacOSX only.
26937 */
26938 static const sqlite3_io_methods *autolockIoFinderImpl(
26939   const char *filePath,    /* name of the database file */
26940   unixFile *pNew           /* open file object for the database file */
26941 ){
26942   static const struct Mapping {
26943     const char *zFilesystem;              /* Filesystem type name */
26944     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
26945   } aMap[] = {
26946     { "hfs",    &posixIoMethods },
26947     { "ufs",    &posixIoMethods },
26948     { "afpfs",  &afpIoMethods },
26949     { "smbfs",  &afpIoMethods },
26950     { "webdav", &nolockIoMethods },
26951     { 0, 0 }
26952   };
26953   int i;
26954   struct statfs fsInfo;
26955   struct flock lockInfo;
26956
26957   if( !filePath ){
26958     /* If filePath==NULL that means we are dealing with a transient file
26959     ** that does not need to be locked. */
26960     return &nolockIoMethods;
26961   }
26962   if( statfs(filePath, &fsInfo) != -1 ){
26963     if( fsInfo.f_flags & MNT_RDONLY ){
26964       return &nolockIoMethods;
26965     }
26966     for(i=0; aMap[i].zFilesystem; i++){
26967       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
26968         return aMap[i].pMethods;
26969       }
26970     }
26971   }
26972
26973   /* Default case. Handles, amongst others, "nfs".
26974   ** Test byte-range lock using fcntl(). If the call succeeds, 
26975   ** assume that the file-system supports POSIX style locks. 
26976   */
26977   lockInfo.l_len = 1;
26978   lockInfo.l_start = 0;
26979   lockInfo.l_whence = SEEK_SET;
26980   lockInfo.l_type = F_RDLCK;
26981   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
26982     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
26983       return &nfsIoMethods;
26984     } else {
26985       return &posixIoMethods;
26986     }
26987   }else{
26988     return &dotlockIoMethods;
26989   }
26990 }
26991 static const sqlite3_io_methods 
26992   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
26993
26994 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26995
26996 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
26997 /* 
26998 ** This "finder" function attempts to determine the best locking strategy 
26999 ** for the database file "filePath".  It then returns the sqlite3_io_methods
27000 ** object that implements that strategy.
27001 **
27002 ** This is for VXWorks only.
27003 */
27004 static const sqlite3_io_methods *autolockIoFinderImpl(
27005   const char *filePath,    /* name of the database file */
27006   unixFile *pNew           /* the open file object */
27007 ){
27008   struct flock lockInfo;
27009
27010   if( !filePath ){
27011     /* If filePath==NULL that means we are dealing with a transient file
27012     ** that does not need to be locked. */
27013     return &nolockIoMethods;
27014   }
27015
27016   /* Test if fcntl() is supported and use POSIX style locks.
27017   ** Otherwise fall back to the named semaphore method.
27018   */
27019   lockInfo.l_len = 1;
27020   lockInfo.l_start = 0;
27021   lockInfo.l_whence = SEEK_SET;
27022   lockInfo.l_type = F_RDLCK;
27023   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
27024     return &posixIoMethods;
27025   }else{
27026     return &semIoMethods;
27027   }
27028 }
27029 static const sqlite3_io_methods 
27030   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
27031
27032 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
27033
27034 /*
27035 ** An abstract type for a pointer to a IO method finder function:
27036 */
27037 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
27038
27039
27040 /****************************************************************************
27041 **************************** sqlite3_vfs methods ****************************
27042 **
27043 ** This division contains the implementation of methods on the
27044 ** sqlite3_vfs object.
27045 */
27046
27047 /*
27048 ** Initialize the contents of the unixFile structure pointed to by pId.
27049 */
27050 static int fillInUnixFile(
27051   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
27052   int h,                  /* Open file descriptor of file being opened */
27053   int dirfd,              /* Directory file descriptor */
27054   sqlite3_file *pId,      /* Write to the unixFile structure here */
27055   const char *zFilename,  /* Name of the file being opened */
27056   int noLock,             /* Omit locking if true */
27057   int isDelete            /* Delete on close if true */
27058 ){
27059   const sqlite3_io_methods *pLockingStyle;
27060   unixFile *pNew = (unixFile *)pId;
27061   int rc = SQLITE_OK;
27062
27063   assert( pNew->pInode==NULL );
27064
27065   /* Parameter isDelete is only used on vxworks. Express this explicitly 
27066   ** here to prevent compiler warnings about unused parameters.
27067   */
27068   UNUSED_PARAMETER(isDelete);
27069
27070   /* Usually the path zFilename should not be a relative pathname. The
27071   ** exception is when opening the proxy "conch" file in builds that
27072   ** include the special Apple locking styles.
27073   */
27074 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27075   assert( zFilename==0 || zFilename[0]=='/' 
27076     || pVfs->pAppData==(void*)&autolockIoFinder );
27077 #else
27078   assert( zFilename==0 || zFilename[0]=='/' );
27079 #endif
27080
27081   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
27082   pNew->h = h;
27083   pNew->dirfd = dirfd;
27084   pNew->fileFlags = 0;
27085   pNew->zPath = zFilename;
27086
27087 #if OS_VXWORKS
27088   pNew->pId = vxworksFindFileId(zFilename);
27089   if( pNew->pId==0 ){
27090     noLock = 1;
27091     rc = SQLITE_NOMEM;
27092   }
27093 #endif
27094
27095   if( noLock ){
27096     pLockingStyle = &nolockIoMethods;
27097   }else{
27098     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
27099 #if SQLITE_ENABLE_LOCKING_STYLE
27100     /* Cache zFilename in the locking context (AFP and dotlock override) for
27101     ** proxyLock activation is possible (remote proxy is based on db name)
27102     ** zFilename remains valid until file is closed, to support */
27103     pNew->lockingContext = (void*)zFilename;
27104 #endif
27105   }
27106
27107   if( pLockingStyle == &posixIoMethods
27108 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27109     || pLockingStyle == &nfsIoMethods
27110 #endif
27111   ){
27112     unixEnterMutex();
27113     rc = findInodeInfo(pNew, &pNew->pInode);
27114     if( rc!=SQLITE_OK ){
27115       /* If an error occured in findInodeInfo(), close the file descriptor
27116       ** immediately, before releasing the mutex. findInodeInfo() may fail
27117       ** in two scenarios:
27118       **
27119       **   (a) A call to fstat() failed.
27120       **   (b) A malloc failed.
27121       **
27122       ** Scenario (b) may only occur if the process is holding no other
27123       ** file descriptors open on the same file. If there were other file
27124       ** descriptors on this file, then no malloc would be required by
27125       ** findInodeInfo(). If this is the case, it is quite safe to close
27126       ** handle h - as it is guaranteed that no posix locks will be released
27127       ** by doing so.
27128       **
27129       ** If scenario (a) caused the error then things are not so safe. The
27130       ** implicit assumption here is that if fstat() fails, things are in
27131       ** such bad shape that dropping a lock or two doesn't matter much.
27132       */
27133       close(h);
27134       h = -1;
27135     }
27136     unixLeaveMutex();
27137   }
27138
27139 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27140   else if( pLockingStyle == &afpIoMethods ){
27141     /* AFP locking uses the file path so it needs to be included in
27142     ** the afpLockingContext.
27143     */
27144     afpLockingContext *pCtx;
27145     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
27146     if( pCtx==0 ){
27147       rc = SQLITE_NOMEM;
27148     }else{
27149       /* NB: zFilename exists and remains valid until the file is closed
27150       ** according to requirement F11141.  So we do not need to make a
27151       ** copy of the filename. */
27152       pCtx->dbPath = zFilename;
27153       pCtx->reserved = 0;
27154       srandomdev();
27155       unixEnterMutex();
27156       rc = findInodeInfo(pNew, &pNew->pInode);
27157       if( rc!=SQLITE_OK ){
27158         sqlite3_free(pNew->lockingContext);
27159         close(h);
27160         h = -1;
27161       }
27162       unixLeaveMutex();        
27163     }
27164   }
27165 #endif
27166
27167   else if( pLockingStyle == &dotlockIoMethods ){
27168     /* Dotfile locking uses the file path so it needs to be included in
27169     ** the dotlockLockingContext 
27170     */
27171     char *zLockFile;
27172     int nFilename;
27173     nFilename = (int)strlen(zFilename) + 6;
27174     zLockFile = (char *)sqlite3_malloc(nFilename);
27175     if( zLockFile==0 ){
27176       rc = SQLITE_NOMEM;
27177     }else{
27178       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
27179     }
27180     pNew->lockingContext = zLockFile;
27181   }
27182
27183 #if OS_VXWORKS
27184   else if( pLockingStyle == &semIoMethods ){
27185     /* Named semaphore locking uses the file path so it needs to be
27186     ** included in the semLockingContext
27187     */
27188     unixEnterMutex();
27189     rc = findInodeInfo(pNew, &pNew->pInode);
27190     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
27191       char *zSemName = pNew->pInode->aSemName;
27192       int n;
27193       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
27194                        pNew->pId->zCanonicalName);
27195       for( n=1; zSemName[n]; n++ )
27196         if( zSemName[n]=='/' ) zSemName[n] = '_';
27197       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
27198       if( pNew->pInode->pSem == SEM_FAILED ){
27199         rc = SQLITE_NOMEM;
27200         pNew->pInode->aSemName[0] = '\0';
27201       }
27202     }
27203     unixLeaveMutex();
27204   }
27205 #endif
27206   
27207   pNew->lastErrno = 0;
27208 #if OS_VXWORKS
27209   if( rc!=SQLITE_OK ){
27210     if( h>=0 ) close(h);
27211     h = -1;
27212     unlink(zFilename);
27213     isDelete = 0;
27214   }
27215   pNew->isDelete = isDelete;
27216 #endif
27217   if( rc!=SQLITE_OK ){
27218     if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
27219     if( h>=0 ) close(h);
27220   }else{
27221     pNew->pMethod = pLockingStyle;
27222     OpenCounter(+1);
27223   }
27224   return rc;
27225 }
27226
27227 /*
27228 ** Open a file descriptor to the directory containing file zFilename.
27229 ** If successful, *pFd is set to the opened file descriptor and
27230 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
27231 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
27232 ** value.
27233 **
27234 ** If SQLITE_OK is returned, the caller is responsible for closing
27235 ** the file descriptor *pFd using close().
27236 */
27237 static int openDirectory(const char *zFilename, int *pFd){
27238   int ii;
27239   int fd = -1;
27240   char zDirname[MAX_PATHNAME+1];
27241
27242   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
27243   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
27244   if( ii>0 ){
27245     zDirname[ii] = '\0';
27246     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
27247     if( fd>=0 ){
27248 #ifdef FD_CLOEXEC
27249       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27250 #endif
27251       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
27252     }
27253   }
27254   *pFd = fd;
27255   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
27256 }
27257
27258 /*
27259 ** Return the name of a directory in which to put temporary files.
27260 ** If no suitable temporary file directory can be found, return NULL.
27261 */
27262 static const char *unixTempFileDir(void){
27263   static const char *azDirs[] = {
27264      0,
27265      0,
27266      "/var/tmp",
27267      "/usr/tmp",
27268      "/tmp",
27269      0        /* List terminator */
27270   };
27271   unsigned int i;
27272   struct stat buf;
27273   const char *zDir = 0;
27274
27275   azDirs[0] = sqlite3_temp_directory;
27276   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
27277   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
27278     if( zDir==0 ) continue;
27279     if( stat(zDir, &buf) ) continue;
27280     if( !S_ISDIR(buf.st_mode) ) continue;
27281     if( access(zDir, 07) ) continue;
27282     break;
27283   }
27284   return zDir;
27285 }
27286
27287 /*
27288 ** Create a temporary file name in zBuf.  zBuf must be allocated
27289 ** by the calling process and must be big enough to hold at least
27290 ** pVfs->mxPathname bytes.
27291 */
27292 static int unixGetTempname(int nBuf, char *zBuf){
27293   static const unsigned char zChars[] =
27294     "abcdefghijklmnopqrstuvwxyz"
27295     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
27296     "0123456789";
27297   unsigned int i, j;
27298   const char *zDir;
27299
27300   /* It's odd to simulate an io-error here, but really this is just
27301   ** using the io-error infrastructure to test that SQLite handles this
27302   ** function failing. 
27303   */
27304   SimulateIOError( return SQLITE_IOERR );
27305
27306   zDir = unixTempFileDir();
27307   if( zDir==0 ) zDir = ".";
27308
27309   /* Check that the output buffer is large enough for the temporary file 
27310   ** name. If it is not, return SQLITE_ERROR.
27311   */
27312   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
27313     return SQLITE_ERROR;
27314   }
27315
27316   do{
27317     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
27318     j = (int)strlen(zBuf);
27319     sqlite3_randomness(15, &zBuf[j]);
27320     for(i=0; i<15; i++, j++){
27321       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
27322     }
27323     zBuf[j] = 0;
27324   }while( access(zBuf,0)==0 );
27325   return SQLITE_OK;
27326 }
27327
27328 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27329 /*
27330 ** Routine to transform a unixFile into a proxy-locking unixFile.
27331 ** Implementation in the proxy-lock division, but used by unixOpen()
27332 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
27333 */
27334 static int proxyTransformUnixFile(unixFile*, const char*);
27335 #endif
27336
27337 /*
27338 ** Search for an unused file descriptor that was opened on the database 
27339 ** file (not a journal or master-journal file) identified by pathname
27340 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
27341 ** argument to this function.
27342 **
27343 ** Such a file descriptor may exist if a database connection was closed
27344 ** but the associated file descriptor could not be closed because some
27345 ** other file descriptor open on the same file is holding a file-lock.
27346 ** Refer to comments in the unixClose() function and the lengthy comment
27347 ** describing "Posix Advisory Locking" at the start of this file for 
27348 ** further details. Also, ticket #4018.
27349 **
27350 ** If a suitable file descriptor is found, then it is returned. If no
27351 ** such file descriptor is located, -1 is returned.
27352 */
27353 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
27354   UnixUnusedFd *pUnused = 0;
27355
27356   /* Do not search for an unused file descriptor on vxworks. Not because
27357   ** vxworks would not benefit from the change (it might, we're not sure),
27358   ** but because no way to test it is currently available. It is better 
27359   ** not to risk breaking vxworks support for the sake of such an obscure 
27360   ** feature.  */
27361 #if !OS_VXWORKS
27362   struct stat sStat;                   /* Results of stat() call */
27363
27364   /* A stat() call may fail for various reasons. If this happens, it is
27365   ** almost certain that an open() call on the same path will also fail.
27366   ** For this reason, if an error occurs in the stat() call here, it is
27367   ** ignored and -1 is returned. The caller will try to open a new file
27368   ** descriptor on the same path, fail, and return an error to SQLite.
27369   **
27370   ** Even if a subsequent open() call does succeed, the consequences of
27371   ** not searching for a resusable file descriptor are not dire.  */
27372   if( 0==stat(zPath, &sStat) ){
27373     unixInodeInfo *pInode;
27374
27375     unixEnterMutex();
27376     pInode = inodeList;
27377     while( pInode && (pInode->fileId.dev!=sStat.st_dev
27378                      || pInode->fileId.ino!=sStat.st_ino) ){
27379        pInode = pInode->pNext;
27380     }
27381     if( pInode ){
27382       UnixUnusedFd **pp;
27383       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
27384       pUnused = *pp;
27385       if( pUnused ){
27386         *pp = pUnused->pNext;
27387       }
27388     }
27389     unixLeaveMutex();
27390   }
27391 #endif    /* if !OS_VXWORKS */
27392   return pUnused;
27393 }
27394
27395 /*
27396 ** This function is called by unixOpen() to determine the unix permissions
27397 ** to create new files with. If no error occurs, then SQLITE_OK is returned
27398 ** and a value suitable for passing as the third argument to open(2) is
27399 ** written to *pMode. If an IO error occurs, an SQLite error code is 
27400 ** returned and the value of *pMode is not modified.
27401 **
27402 ** If the file being opened is a temporary file, it is always created with
27403 ** the octal permissions 0600 (read/writable by owner only). If the file
27404 ** is a database or master journal file, it is created with the permissions 
27405 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
27406 **
27407 ** Finally, if the file being opened is a WAL or regular journal file, then 
27408 ** this function queries the file-system for the permissions on the 
27409 ** corresponding database file and sets *pMode to this value. Whenever 
27410 ** possible, WAL and journal files are created using the same permissions 
27411 ** as the associated database file.
27412 */
27413 static int findCreateFileMode(
27414   const char *zPath,              /* Path of file (possibly) being created */
27415   int flags,                      /* Flags passed as 4th argument to xOpen() */
27416   mode_t *pMode                   /* OUT: Permissions to open file with */
27417 ){
27418   int rc = SQLITE_OK;             /* Return Code */
27419   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
27420     char zDb[MAX_PATHNAME+1];     /* Database file path */
27421     int nDb;                      /* Number of valid bytes in zDb */
27422     struct stat sStat;            /* Output of stat() on database file */
27423
27424     /* zPath is a path to a WAL or journal file. The following block derives
27425     ** the path to the associated database file from zPath. This block handles
27426     ** the following naming conventions:
27427     **
27428     **   "<path to db>-journal"
27429     **   "<path to db>-wal"
27430     **   "<path to db>-journal-NNNN"
27431     **   "<path to db>-wal-NNNN"
27432     **
27433     ** where NNNN is a 4 digit decimal number. The NNNN naming schemes are 
27434     ** used by the test_multiplex.c module.
27435     */
27436     nDb = sqlite3Strlen30(zPath) - 1; 
27437     while( nDb>0 && zPath[nDb]!='l' ) nDb--;
27438     nDb -= ((flags & SQLITE_OPEN_WAL) ? 3 : 7);
27439     memcpy(zDb, zPath, nDb);
27440     zDb[nDb] = '\0';
27441
27442     if( 0==stat(zDb, &sStat) ){
27443       *pMode = sStat.st_mode & 0777;
27444     }else{
27445       rc = SQLITE_IOERR_FSTAT;
27446     }
27447   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
27448     *pMode = 0600;
27449   }else{
27450     *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
27451   }
27452   return rc;
27453 }
27454
27455 /*
27456 ** Open the file zPath.
27457 ** 
27458 ** Previously, the SQLite OS layer used three functions in place of this
27459 ** one:
27460 **
27461 **     sqlite3OsOpenReadWrite();
27462 **     sqlite3OsOpenReadOnly();
27463 **     sqlite3OsOpenExclusive();
27464 **
27465 ** These calls correspond to the following combinations of flags:
27466 **
27467 **     ReadWrite() ->     (READWRITE | CREATE)
27468 **     ReadOnly()  ->     (READONLY) 
27469 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
27470 **
27471 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
27472 ** true, the file was configured to be automatically deleted when the
27473 ** file handle closed. To achieve the same effect using this new 
27474 ** interface, add the DELETEONCLOSE flag to those specified above for 
27475 ** OpenExclusive().
27476 */
27477 static int unixOpen(
27478   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
27479   const char *zPath,           /* Pathname of file to be opened */
27480   sqlite3_file *pFile,         /* The file descriptor to be filled in */
27481   int flags,                   /* Input flags to control the opening */
27482   int *pOutFlags               /* Output flags returned to SQLite core */
27483 ){
27484   unixFile *p = (unixFile *)pFile;
27485   int fd = -1;                   /* File descriptor returned by open() */
27486   int dirfd = -1;                /* Directory file descriptor */
27487   int openFlags = 0;             /* Flags to pass to open() */
27488   int eType = flags&0xFFFFFF00;  /* Type of file to open */
27489   int noLock;                    /* True to omit locking primitives */
27490   int rc = SQLITE_OK;            /* Function Return Code */
27491
27492   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
27493   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
27494   int isCreate     = (flags & SQLITE_OPEN_CREATE);
27495   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
27496   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
27497 #if SQLITE_ENABLE_LOCKING_STYLE
27498   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
27499 #endif
27500
27501   /* If creating a master or main-file journal, this function will open
27502   ** a file-descriptor on the directory too. The first time unixSync()
27503   ** is called the directory file descriptor will be fsync()ed and close()d.
27504   */
27505   int isOpenDirectory = (isCreate && (
27506         eType==SQLITE_OPEN_MASTER_JOURNAL 
27507      || eType==SQLITE_OPEN_MAIN_JOURNAL 
27508      || eType==SQLITE_OPEN_WAL
27509   ));
27510
27511   /* If argument zPath is a NULL pointer, this function is required to open
27512   ** a temporary file. Use this buffer to store the file name in.
27513   */
27514   char zTmpname[MAX_PATHNAME+1];
27515   const char *zName = zPath;
27516
27517   /* Check the following statements are true: 
27518   **
27519   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
27520   **   (b) if CREATE is set, then READWRITE must also be set, and
27521   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
27522   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
27523   */
27524   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
27525   assert(isCreate==0 || isReadWrite);
27526   assert(isExclusive==0 || isCreate);
27527   assert(isDelete==0 || isCreate);
27528
27529   /* The main DB, main journal, WAL file and master journal are never 
27530   ** automatically deleted. Nor are they ever temporary files.  */
27531   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
27532   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
27533   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
27534   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
27535
27536   /* Assert that the upper layer has set one of the "file-type" flags. */
27537   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
27538        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
27539        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
27540        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
27541   );
27542
27543   memset(p, 0, sizeof(unixFile));
27544
27545   if( eType==SQLITE_OPEN_MAIN_DB ){
27546     UnixUnusedFd *pUnused;
27547     pUnused = findReusableFd(zName, flags);
27548     if( pUnused ){
27549       fd = pUnused->fd;
27550     }else{
27551       pUnused = sqlite3_malloc(sizeof(*pUnused));
27552       if( !pUnused ){
27553         return SQLITE_NOMEM;
27554       }
27555     }
27556     p->pUnused = pUnused;
27557   }else if( !zName ){
27558     /* If zName is NULL, the upper layer is requesting a temp file. */
27559     assert(isDelete && !isOpenDirectory);
27560     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
27561     if( rc!=SQLITE_OK ){
27562       return rc;
27563     }
27564     zName = zTmpname;
27565   }
27566
27567   /* Determine the value of the flags parameter passed to POSIX function
27568   ** open(). These must be calculated even if open() is not called, as
27569   ** they may be stored as part of the file handle and used by the 
27570   ** 'conch file' locking functions later on.  */
27571   if( isReadonly )  openFlags |= O_RDONLY;
27572   if( isReadWrite ) openFlags |= O_RDWR;
27573   if( isCreate )    openFlags |= O_CREAT;
27574   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
27575   openFlags |= (O_LARGEFILE|O_BINARY);
27576
27577   if( fd<0 ){
27578     mode_t openMode;              /* Permissions to create file with */
27579     rc = findCreateFileMode(zName, flags, &openMode);
27580     if( rc!=SQLITE_OK ){
27581       assert( !p->pUnused );
27582       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
27583       return rc;
27584     }
27585     fd = open(zName, openFlags, openMode);
27586     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
27587     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
27588       /* Failed to open the file for read/write access. Try read-only. */
27589       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
27590       openFlags &= ~(O_RDWR|O_CREAT);
27591       flags |= SQLITE_OPEN_READONLY;
27592       openFlags |= O_RDONLY;
27593       fd = open(zName, openFlags, openMode);
27594     }
27595     if( fd<0 ){
27596       rc = SQLITE_CANTOPEN_BKPT;
27597       goto open_finished;
27598     }
27599   }
27600   assert( fd>=0 );
27601   if( pOutFlags ){
27602     *pOutFlags = flags;
27603   }
27604
27605   if( p->pUnused ){
27606     p->pUnused->fd = fd;
27607     p->pUnused->flags = flags;
27608   }
27609
27610   if( isDelete ){
27611 #if OS_VXWORKS
27612     zPath = zName;
27613 #else
27614     unlink(zName);
27615 #endif
27616   }
27617 #if SQLITE_ENABLE_LOCKING_STYLE
27618   else{
27619     p->openFlags = openFlags;
27620   }
27621 #endif
27622
27623   if( isOpenDirectory ){
27624     rc = openDirectory(zPath, &dirfd);
27625     if( rc!=SQLITE_OK ){
27626       /* It is safe to close fd at this point, because it is guaranteed not
27627       ** to be open on a database file. If it were open on a database file,
27628       ** it would not be safe to close as this would release any locks held
27629       ** on the file by this process.  */
27630       assert( eType!=SQLITE_OPEN_MAIN_DB );
27631       close(fd);             /* silently leak if fail, already in error */
27632       goto open_finished;
27633     }
27634   }
27635
27636 #ifdef FD_CLOEXEC
27637   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27638 #endif
27639
27640   noLock = eType!=SQLITE_OPEN_MAIN_DB;
27641
27642   
27643 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
27644   struct statfs fsInfo;
27645   if( fstatfs(fd, &fsInfo) == -1 ){
27646     ((unixFile*)pFile)->lastErrno = errno;
27647     if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
27648     close(fd); /* silently leak if fail, in error */
27649     return SQLITE_IOERR_ACCESS;
27650   }
27651   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
27652     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
27653   }
27654 #endif
27655   
27656 #if SQLITE_ENABLE_LOCKING_STYLE
27657 #if SQLITE_PREFER_PROXY_LOCKING
27658   isAutoProxy = 1;
27659 #endif
27660   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
27661     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
27662     int useProxy = 0;
27663
27664     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
27665     ** never use proxy, NULL means use proxy for non-local files only.  */
27666     if( envforce!=NULL ){
27667       useProxy = atoi(envforce)>0;
27668     }else{
27669       struct statfs fsInfo;
27670       if( statfs(zPath, &fsInfo) == -1 ){
27671         /* In theory, the close(fd) call is sub-optimal. If the file opened
27672         ** with fd is a database file, and there are other connections open
27673         ** on that file that are currently holding advisory locks on it,
27674         ** then the call to close() will cancel those locks. In practice,
27675         ** we're assuming that statfs() doesn't fail very often. At least
27676         ** not while other file descriptors opened by the same process on
27677         ** the same file are working.  */
27678         p->lastErrno = errno;
27679         if( dirfd>=0 ){
27680           close(dirfd); /* silently leak if fail, in error */
27681         }
27682         close(fd); /* silently leak if fail, in error */
27683         rc = SQLITE_IOERR_ACCESS;
27684         goto open_finished;
27685       }
27686       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
27687     }
27688     if( useProxy ){
27689       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27690       if( rc==SQLITE_OK ){
27691         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
27692         if( rc!=SQLITE_OK ){
27693           /* Use unixClose to clean up the resources added in fillInUnixFile 
27694           ** and clear all the structure's references.  Specifically, 
27695           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
27696           */
27697           unixClose(pFile);
27698           return rc;
27699         }
27700       }
27701       goto open_finished;
27702     }
27703   }
27704 #endif
27705   
27706   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
27707 open_finished:
27708   if( rc!=SQLITE_OK ){
27709     sqlite3_free(p->pUnused);
27710   }
27711   return rc;
27712 }
27713
27714
27715 /*
27716 ** Delete the file at zPath. If the dirSync argument is true, fsync()
27717 ** the directory after deleting the file.
27718 */
27719 static int unixDelete(
27720   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
27721   const char *zPath,        /* Name of file to be deleted */
27722   int dirSync               /* If true, fsync() directory after deleting file */
27723 ){
27724   int rc = SQLITE_OK;
27725   UNUSED_PARAMETER(NotUsed);
27726   SimulateIOError(return SQLITE_IOERR_DELETE);
27727   if( unlink(zPath)==(-1) && errno!=ENOENT ){
27728     return SQLITE_IOERR_DELETE;
27729   }
27730 #ifndef SQLITE_DISABLE_DIRSYNC
27731   if( dirSync ){
27732     int fd;
27733     rc = openDirectory(zPath, &fd);
27734     if( rc==SQLITE_OK ){
27735 #if OS_VXWORKS
27736       if( fsync(fd)==-1 )
27737 #else
27738       if( fsync(fd) )
27739 #endif
27740       {
27741         rc = SQLITE_IOERR_DIR_FSYNC;
27742       }
27743       if( close(fd)&&!rc ){
27744         rc = SQLITE_IOERR_DIR_CLOSE;
27745       }
27746     }
27747   }
27748 #endif
27749   return rc;
27750 }
27751
27752 /*
27753 ** Test the existance of or access permissions of file zPath. The
27754 ** test performed depends on the value of flags:
27755 **
27756 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
27757 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
27758 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
27759 **
27760 ** Otherwise return 0.
27761 */
27762 static int unixAccess(
27763   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
27764   const char *zPath,      /* Path of the file to examine */
27765   int flags,              /* What do we want to learn about the zPath file? */
27766   int *pResOut            /* Write result boolean here */
27767 ){
27768   int amode = 0;
27769   UNUSED_PARAMETER(NotUsed);
27770   SimulateIOError( return SQLITE_IOERR_ACCESS; );
27771   switch( flags ){
27772     case SQLITE_ACCESS_EXISTS:
27773       amode = F_OK;
27774       break;
27775     case SQLITE_ACCESS_READWRITE:
27776       amode = W_OK|R_OK;
27777       break;
27778     case SQLITE_ACCESS_READ:
27779       amode = R_OK;
27780       break;
27781
27782     default:
27783       assert(!"Invalid flags argument");
27784   }
27785   *pResOut = (access(zPath, amode)==0);
27786   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
27787     struct stat buf;
27788     if( 0==stat(zPath, &buf) && buf.st_size==0 ){
27789       *pResOut = 0;
27790     }
27791   }
27792   return SQLITE_OK;
27793 }
27794
27795
27796 /*
27797 ** Turn a relative pathname into a full pathname. The relative path
27798 ** is stored as a nul-terminated string in the buffer pointed to by
27799 ** zPath. 
27800 **
27801 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
27802 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
27803 ** this buffer before returning.
27804 */
27805 static int unixFullPathname(
27806   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
27807   const char *zPath,            /* Possibly relative input path */
27808   int nOut,                     /* Size of output buffer in bytes */
27809   char *zOut                    /* Output buffer */
27810 ){
27811
27812   /* It's odd to simulate an io-error here, but really this is just
27813   ** using the io-error infrastructure to test that SQLite handles this
27814   ** function failing. This function could fail if, for example, the
27815   ** current working directory has been unlinked.
27816   */
27817   SimulateIOError( return SQLITE_ERROR );
27818
27819   assert( pVfs->mxPathname==MAX_PATHNAME );
27820   UNUSED_PARAMETER(pVfs);
27821
27822   zOut[nOut-1] = '\0';
27823   if( zPath[0]=='/' ){
27824     sqlite3_snprintf(nOut, zOut, "%s", zPath);
27825   }else{
27826     int nCwd;
27827     if( getcwd(zOut, nOut-1)==0 ){
27828       return SQLITE_CANTOPEN_BKPT;
27829     }
27830     nCwd = (int)strlen(zOut);
27831     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
27832   }
27833   return SQLITE_OK;
27834 }
27835
27836
27837 #ifndef SQLITE_OMIT_LOAD_EXTENSION
27838 /*
27839 ** Interfaces for opening a shared library, finding entry points
27840 ** within the shared library, and closing the shared library.
27841 */
27842 #include <dlfcn.h>
27843 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
27844   UNUSED_PARAMETER(NotUsed);
27845   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
27846 }
27847
27848 /*
27849 ** SQLite calls this function immediately after a call to unixDlSym() or
27850 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
27851 ** message is available, it is written to zBufOut. If no error message
27852 ** is available, zBufOut is left unmodified and SQLite uses a default
27853 ** error message.
27854 */
27855 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
27856   const char *zErr;
27857   UNUSED_PARAMETER(NotUsed);
27858   unixEnterMutex();
27859   zErr = dlerror();
27860   if( zErr ){
27861     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
27862   }
27863   unixLeaveMutex();
27864 }
27865 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
27866   /* 
27867   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
27868   ** cast into a pointer to a function.  And yet the library dlsym() routine
27869   ** returns a void* which is really a pointer to a function.  So how do we
27870   ** use dlsym() with -pedantic-errors?
27871   **
27872   ** Variable x below is defined to be a pointer to a function taking
27873   ** parameters void* and const char* and returning a pointer to a function.
27874   ** We initialize x by assigning it a pointer to the dlsym() function.
27875   ** (That assignment requires a cast.)  Then we call the function that
27876   ** x points to.  
27877   **
27878   ** This work-around is unlikely to work correctly on any system where
27879   ** you really cannot cast a function pointer into void*.  But then, on the
27880   ** other hand, dlsym() will not work on such a system either, so we have
27881   ** not really lost anything.
27882   */
27883   void (*(*x)(void*,const char*))(void);
27884   UNUSED_PARAMETER(NotUsed);
27885   x = (void(*(*)(void*,const char*))(void))dlsym;
27886   return (*x)(p, zSym);
27887 }
27888 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
27889   UNUSED_PARAMETER(NotUsed);
27890   dlclose(pHandle);
27891 }
27892 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
27893   #define unixDlOpen  0
27894   #define unixDlError 0
27895   #define unixDlSym   0
27896   #define unixDlClose 0
27897 #endif
27898
27899 /*
27900 ** Write nBuf bytes of random data to the supplied buffer zBuf.
27901 */
27902 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
27903   UNUSED_PARAMETER(NotUsed);
27904   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
27905
27906   /* We have to initialize zBuf to prevent valgrind from reporting
27907   ** errors.  The reports issued by valgrind are incorrect - we would
27908   ** prefer that the randomness be increased by making use of the
27909   ** uninitialized space in zBuf - but valgrind errors tend to worry
27910   ** some users.  Rather than argue, it seems easier just to initialize
27911   ** the whole array and silence valgrind, even if that means less randomness
27912   ** in the random seed.
27913   **
27914   ** When testing, initializing zBuf[] to zero is all we do.  That means
27915   ** that we always use the same random number sequence.  This makes the
27916   ** tests repeatable.
27917   */
27918   memset(zBuf, 0, nBuf);
27919 #if !defined(SQLITE_TEST)
27920   {
27921     int pid, fd;
27922     fd = open("/dev/urandom", O_RDONLY);
27923     if( fd<0 ){
27924       time_t t;
27925       time(&t);
27926       memcpy(zBuf, &t, sizeof(t));
27927       pid = getpid();
27928       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
27929       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
27930       nBuf = sizeof(t) + sizeof(pid);
27931     }else{
27932       nBuf = read(fd, zBuf, nBuf);
27933       close(fd);
27934     }
27935   }
27936 #endif
27937   return nBuf;
27938 }
27939
27940
27941 /*
27942 ** Sleep for a little while.  Return the amount of time slept.
27943 ** The argument is the number of microseconds we want to sleep.
27944 ** The return value is the number of microseconds of sleep actually
27945 ** requested from the underlying operating system, a number which
27946 ** might be greater than or equal to the argument, but not less
27947 ** than the argument.
27948 */
27949 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
27950 #if OS_VXWORKS
27951   struct timespec sp;
27952
27953   sp.tv_sec = microseconds / 1000000;
27954   sp.tv_nsec = (microseconds % 1000000) * 1000;
27955   nanosleep(&sp, NULL);
27956   UNUSED_PARAMETER(NotUsed);
27957   return microseconds;
27958 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
27959   usleep(microseconds);
27960   UNUSED_PARAMETER(NotUsed);
27961   return microseconds;
27962 #else
27963   int seconds = (microseconds+999999)/1000000;
27964   sleep(seconds);
27965   UNUSED_PARAMETER(NotUsed);
27966   return seconds*1000000;
27967 #endif
27968 }
27969
27970 /*
27971 ** The following variable, if set to a non-zero value, is interpreted as
27972 ** the number of seconds since 1970 and is used to set the result of
27973 ** sqlite3OsCurrentTime() during testing.
27974 */
27975 #ifdef SQLITE_TEST
27976 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
27977 #endif
27978
27979 /*
27980 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
27981 ** the current time and date as a Julian Day number times 86_400_000.  In
27982 ** other words, write into *piNow the number of milliseconds since the Julian
27983 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
27984 ** proleptic Gregorian calendar.
27985 **
27986 ** On success, return 0.  Return 1 if the time and date cannot be found.
27987 */
27988 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
27989   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
27990 #if defined(NO_GETTOD)
27991   time_t t;
27992   time(&t);
27993   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
27994 #elif OS_VXWORKS
27995   struct timespec sNow;
27996   clock_gettime(CLOCK_REALTIME, &sNow);
27997   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
27998 #else
27999   struct timeval sNow;
28000   gettimeofday(&sNow, 0);
28001   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
28002 #endif
28003
28004 #ifdef SQLITE_TEST
28005   if( sqlite3_current_time ){
28006     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
28007   }
28008 #endif
28009   UNUSED_PARAMETER(NotUsed);
28010   return 0;
28011 }
28012
28013 /*
28014 ** Find the current time (in Universal Coordinated Time).  Write the
28015 ** current time and date as a Julian Day number into *prNow and
28016 ** return 0.  Return 1 if the time and date cannot be found.
28017 */
28018 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
28019   sqlite3_int64 i;
28020   UNUSED_PARAMETER(NotUsed);
28021   unixCurrentTimeInt64(0, &i);
28022   *prNow = i/86400000.0;
28023   return 0;
28024 }
28025
28026 /*
28027 ** We added the xGetLastError() method with the intention of providing
28028 ** better low-level error messages when operating-system problems come up
28029 ** during SQLite operation.  But so far, none of that has been implemented
28030 ** in the core.  So this routine is never called.  For now, it is merely
28031 ** a place-holder.
28032 */
28033 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
28034   UNUSED_PARAMETER(NotUsed);
28035   UNUSED_PARAMETER(NotUsed2);
28036   UNUSED_PARAMETER(NotUsed3);
28037   return 0;
28038 }
28039
28040
28041 /*
28042 ************************ End of sqlite3_vfs methods ***************************
28043 ******************************************************************************/
28044
28045 /******************************************************************************
28046 ************************** Begin Proxy Locking ********************************
28047 **
28048 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
28049 ** other locking methods on secondary lock files.  Proxy locking is a
28050 ** meta-layer over top of the primitive locking implemented above.  For
28051 ** this reason, the division that implements of proxy locking is deferred
28052 ** until late in the file (here) after all of the other I/O methods have
28053 ** been defined - so that the primitive locking methods are available
28054 ** as services to help with the implementation of proxy locking.
28055 **
28056 ****
28057 **
28058 ** The default locking schemes in SQLite use byte-range locks on the
28059 ** database file to coordinate safe, concurrent access by multiple readers
28060 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
28061 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
28062 ** as POSIX read & write locks over fixed set of locations (via fsctl),
28063 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
28064 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
28065 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
28066 ** address in the shared range is taken for a SHARED lock, the entire
28067 ** shared range is taken for an EXCLUSIVE lock):
28068 **
28069 **      PENDING_BYTE        0x40000000                  
28070 **      RESERVED_BYTE       0x40000001
28071 **      SHARED_RANGE        0x40000002 -> 0x40000200
28072 **
28073 ** This works well on the local file system, but shows a nearly 100x
28074 ** slowdown in read performance on AFP because the AFP client disables
28075 ** the read cache when byte-range locks are present.  Enabling the read
28076 ** cache exposes a cache coherency problem that is present on all OS X
28077 ** supported network file systems.  NFS and AFP both observe the
28078 ** close-to-open semantics for ensuring cache coherency
28079 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
28080 ** address the requirements for concurrent database access by multiple
28081 ** readers and writers
28082 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
28083 **
28084 ** To address the performance and cache coherency issues, proxy file locking
28085 ** changes the way database access is controlled by limiting access to a
28086 ** single host at a time and moving file locks off of the database file
28087 ** and onto a proxy file on the local file system.  
28088 **
28089 **
28090 ** Using proxy locks
28091 ** -----------------
28092 **
28093 ** C APIs
28094 **
28095 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
28096 **                       <proxy_path> | ":auto:");
28097 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
28098 **
28099 **
28100 ** SQL pragmas
28101 **
28102 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
28103 **  PRAGMA [database.]lock_proxy_file
28104 **
28105 ** Specifying ":auto:" means that if there is a conch file with a matching
28106 ** host ID in it, the proxy path in the conch file will be used, otherwise
28107 ** a proxy path based on the user's temp dir
28108 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
28109 ** actual proxy file name is generated from the name and path of the
28110 ** database file.  For example:
28111 **
28112 **       For database path "/Users/me/foo.db" 
28113 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
28114 **
28115 ** Once a lock proxy is configured for a database connection, it can not
28116 ** be removed, however it may be switched to a different proxy path via
28117 ** the above APIs (assuming the conch file is not being held by another
28118 ** connection or process). 
28119 **
28120 **
28121 ** How proxy locking works
28122 ** -----------------------
28123 **
28124 ** Proxy file locking relies primarily on two new supporting files: 
28125 **
28126 **   *  conch file to limit access to the database file to a single host
28127 **      at a time
28128 **
28129 **   *  proxy file to act as a proxy for the advisory locks normally
28130 **      taken on the database
28131 **
28132 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
28133 ** by taking an sqlite-style shared lock on the conch file, reading the
28134 ** contents and comparing the host's unique host ID (see below) and lock
28135 ** proxy path against the values stored in the conch.  The conch file is
28136 ** stored in the same directory as the database file and the file name
28137 ** is patterned after the database file name as ".<databasename>-conch".
28138 ** If the conch file does not exist, or it's contents do not match the
28139 ** host ID and/or proxy path, then the lock is escalated to an exclusive
28140 ** lock and the conch file contents is updated with the host ID and proxy
28141 ** path and the lock is downgraded to a shared lock again.  If the conch
28142 ** is held by another process (with a shared lock), the exclusive lock
28143 ** will fail and SQLITE_BUSY is returned.
28144 **
28145 ** The proxy file - a single-byte file used for all advisory file locks
28146 ** normally taken on the database file.   This allows for safe sharing
28147 ** of the database file for multiple readers and writers on the same
28148 ** host (the conch ensures that they all use the same local lock file).
28149 **
28150 ** Requesting the lock proxy does not immediately take the conch, it is
28151 ** only taken when the first request to lock database file is made.  
28152 ** This matches the semantics of the traditional locking behavior, where
28153 ** opening a connection to a database file does not take a lock on it.
28154 ** The shared lock and an open file descriptor are maintained until 
28155 ** the connection to the database is closed. 
28156 **
28157 ** The proxy file and the lock file are never deleted so they only need
28158 ** to be created the first time they are used.
28159 **
28160 ** Configuration options
28161 ** ---------------------
28162 **
28163 **  SQLITE_PREFER_PROXY_LOCKING
28164 **
28165 **       Database files accessed on non-local file systems are
28166 **       automatically configured for proxy locking, lock files are
28167 **       named automatically using the same logic as
28168 **       PRAGMA lock_proxy_file=":auto:"
28169 **    
28170 **  SQLITE_PROXY_DEBUG
28171 **
28172 **       Enables the logging of error messages during host id file
28173 **       retrieval and creation
28174 **
28175 **  LOCKPROXYDIR
28176 **
28177 **       Overrides the default directory used for lock proxy files that
28178 **       are named automatically via the ":auto:" setting
28179 **
28180 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
28181 **
28182 **       Permissions to use when creating a directory for storing the
28183 **       lock proxy files, only used when LOCKPROXYDIR is not set.
28184 **    
28185 **    
28186 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
28187 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
28188 ** force proxy locking to be used for every database file opened, and 0
28189 ** will force automatic proxy locking to be disabled for all database
28190 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
28191 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
28192 */
28193
28194 /*
28195 ** Proxy locking is only available on MacOSX 
28196 */
28197 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28198
28199 /*
28200 ** The proxyLockingContext has the path and file structures for the remote 
28201 ** and local proxy files in it
28202 */
28203 typedef struct proxyLockingContext proxyLockingContext;
28204 struct proxyLockingContext {
28205   unixFile *conchFile;         /* Open conch file */
28206   char *conchFilePath;         /* Name of the conch file */
28207   unixFile *lockProxy;         /* Open proxy lock file */
28208   char *lockProxyPath;         /* Name of the proxy lock file */
28209   char *dbPath;                /* Name of the open file */
28210   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
28211   void *oldLockingContext;     /* Original lockingcontext to restore on close */
28212   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
28213 };
28214
28215 /* 
28216 ** The proxy lock file path for the database at dbPath is written into lPath, 
28217 ** which must point to valid, writable memory large enough for a maxLen length
28218 ** file path. 
28219 */
28220 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
28221   int len;
28222   int dbLen;
28223   int i;
28224
28225 #ifdef LOCKPROXYDIR
28226   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
28227 #else
28228 # ifdef _CS_DARWIN_USER_TEMP_DIR
28229   {
28230     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
28231       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
28232                lPath, errno, getpid()));
28233       return SQLITE_IOERR_LOCK;
28234     }
28235     len = strlcat(lPath, "sqliteplocks", maxLen);    
28236   }
28237 # else
28238   len = strlcpy(lPath, "/tmp/", maxLen);
28239 # endif
28240 #endif
28241
28242   if( lPath[len-1]!='/' ){
28243     len = strlcat(lPath, "/", maxLen);
28244   }
28245   
28246   /* transform the db path to a unique cache name */
28247   dbLen = (int)strlen(dbPath);
28248   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
28249     char c = dbPath[i];
28250     lPath[i+len] = (c=='/')?'_':c;
28251   }
28252   lPath[i+len]='\0';
28253   strlcat(lPath, ":auto:", maxLen);
28254   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
28255   return SQLITE_OK;
28256 }
28257
28258 /* 
28259  ** Creates the lock file and any missing directories in lockPath
28260  */
28261 static int proxyCreateLockPath(const char *lockPath){
28262   int i, len;
28263   char buf[MAXPATHLEN];
28264   int start = 0;
28265   
28266   assert(lockPath!=NULL);
28267   /* try to create all the intermediate directories */
28268   len = (int)strlen(lockPath);
28269   buf[0] = lockPath[0];
28270   for( i=1; i<len; i++ ){
28271     if( lockPath[i] == '/' && (i - start > 0) ){
28272       /* only mkdir if leaf dir != "." or "/" or ".." */
28273       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
28274          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
28275         buf[i]='\0';
28276         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
28277           int err=errno;
28278           if( err!=EEXIST ) {
28279             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
28280                      "'%s' proxy lock path=%s pid=%d\n",
28281                      buf, strerror(err), lockPath, getpid()));
28282             return err;
28283           }
28284         }
28285       }
28286       start=i+1;
28287     }
28288     buf[i] = lockPath[i];
28289   }
28290   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
28291   return 0;
28292 }
28293
28294 /*
28295 ** Create a new VFS file descriptor (stored in memory obtained from
28296 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
28297 **
28298 ** The caller is responsible not only for closing the file descriptor
28299 ** but also for freeing the memory associated with the file descriptor.
28300 */
28301 static int proxyCreateUnixFile(
28302     const char *path,        /* path for the new unixFile */
28303     unixFile **ppFile,       /* unixFile created and returned by ref */
28304     int islockfile           /* if non zero missing dirs will be created */
28305 ) {
28306   int fd = -1;
28307   int dirfd = -1;
28308   unixFile *pNew;
28309   int rc = SQLITE_OK;
28310   int openFlags = O_RDWR | O_CREAT;
28311   sqlite3_vfs dummyVfs;
28312   int terrno = 0;
28313   UnixUnusedFd *pUnused = NULL;
28314
28315   /* 1. first try to open/create the file
28316   ** 2. if that fails, and this is a lock file (not-conch), try creating
28317   ** the parent directories and then try again.
28318   ** 3. if that fails, try to open the file read-only
28319   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
28320   */
28321   pUnused = findReusableFd(path, openFlags);
28322   if( pUnused ){
28323     fd = pUnused->fd;
28324   }else{
28325     pUnused = sqlite3_malloc(sizeof(*pUnused));
28326     if( !pUnused ){
28327       return SQLITE_NOMEM;
28328     }
28329   }
28330   if( fd<0 ){
28331     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
28332     terrno = errno;
28333     if( fd<0 && errno==ENOENT && islockfile ){
28334       if( proxyCreateLockPath(path) == SQLITE_OK ){
28335         fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
28336       }
28337     }
28338   }
28339   if( fd<0 ){
28340     openFlags = O_RDONLY;
28341     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
28342     terrno = errno;
28343   }
28344   if( fd<0 ){
28345     if( islockfile ){
28346       return SQLITE_BUSY;
28347     }
28348     switch (terrno) {
28349       case EACCES:
28350         return SQLITE_PERM;
28351       case EIO: 
28352         return SQLITE_IOERR_LOCK; /* even though it is the conch */
28353       default:
28354         return SQLITE_CANTOPEN_BKPT;
28355     }
28356   }
28357   
28358   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
28359   if( pNew==NULL ){
28360     rc = SQLITE_NOMEM;
28361     goto end_create_proxy;
28362   }
28363   memset(pNew, 0, sizeof(unixFile));
28364   pNew->openFlags = openFlags;
28365   dummyVfs.pAppData = (void*)&autolockIoFinder;
28366   pUnused->fd = fd;
28367   pUnused->flags = openFlags;
28368   pNew->pUnused = pUnused;
28369   
28370   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
28371   if( rc==SQLITE_OK ){
28372     *ppFile = pNew;
28373     return SQLITE_OK;
28374   }
28375 end_create_proxy:    
28376   close(fd); /* silently leak fd if error, we're already in error */
28377   sqlite3_free(pNew);
28378   sqlite3_free(pUnused);
28379   return rc;
28380 }
28381
28382 #ifdef SQLITE_TEST
28383 /* simulate multiple hosts by creating unique hostid file paths */
28384 SQLITE_API int sqlite3_hostid_num = 0;
28385 #endif
28386
28387 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
28388
28389 /* Not always defined in the headers as it ought to be */
28390 extern int gethostuuid(uuid_t id, const struct timespec *wait);
28391
28392 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
28393 ** bytes of writable memory.
28394 */
28395 static int proxyGetHostID(unsigned char *pHostID, int *pError){
28396   struct timespec timeout = {1, 0}; /* 1 sec timeout */
28397   
28398   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
28399   memset(pHostID, 0, PROXY_HOSTIDLEN);
28400 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
28401                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
28402   if( gethostuuid(pHostID, &timeout) ){
28403     int err = errno;
28404     if( pError ){
28405       *pError = err;
28406     }
28407     return SQLITE_IOERR;
28408   }
28409 #endif
28410 #ifdef SQLITE_TEST
28411   /* simulate multiple hosts by creating unique hostid file paths */
28412   if( sqlite3_hostid_num != 0){
28413     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
28414   }
28415 #endif
28416   
28417   return SQLITE_OK;
28418 }
28419
28420 /* The conch file contains the header, host id and lock file path
28421  */
28422 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
28423 #define PROXY_HEADERLEN    1   /* conch file header length */
28424 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
28425 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
28426
28427 /* 
28428 ** Takes an open conch file, copies the contents to a new path and then moves 
28429 ** it back.  The newly created file's file descriptor is assigned to the
28430 ** conch file structure and finally the original conch file descriptor is 
28431 ** closed.  Returns zero if successful.
28432 */
28433 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
28434   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28435   unixFile *conchFile = pCtx->conchFile;
28436   char tPath[MAXPATHLEN];
28437   char buf[PROXY_MAXCONCHLEN];
28438   char *cPath = pCtx->conchFilePath;
28439   size_t readLen = 0;
28440   size_t pathLen = 0;
28441   char errmsg[64] = "";
28442   int fd = -1;
28443   int rc = -1;
28444   UNUSED_PARAMETER(myHostID);
28445
28446   /* create a new path by replace the trailing '-conch' with '-break' */
28447   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
28448   if( pathLen>MAXPATHLEN || pathLen<6 || 
28449      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
28450     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
28451     goto end_breaklock;
28452   }
28453   /* read the conch content */
28454   readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
28455   if( readLen<PROXY_PATHINDEX ){
28456     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
28457     goto end_breaklock;
28458   }
28459   /* write it out to the temporary break file */
28460   fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
28461   if( fd<0 ){
28462     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
28463     goto end_breaklock;
28464   }
28465   if( pwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
28466     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
28467     goto end_breaklock;
28468   }
28469   if( rename(tPath, cPath) ){
28470     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
28471     goto end_breaklock;
28472   }
28473   rc = 0;
28474   fprintf(stderr, "broke stale lock on %s\n", cPath);
28475   close(conchFile->h);
28476   conchFile->h = fd;
28477   conchFile->openFlags = O_RDWR | O_CREAT;
28478
28479 end_breaklock:
28480   if( rc ){
28481     if( fd>=0 ){
28482       unlink(tPath);
28483       close(fd);
28484     }
28485     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
28486   }
28487   return rc;
28488 }
28489
28490 /* Take the requested lock on the conch file and break a stale lock if the 
28491 ** host id matches.
28492 */
28493 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
28494   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28495   unixFile *conchFile = pCtx->conchFile;
28496   int rc = SQLITE_OK;
28497   int nTries = 0;
28498   struct timespec conchModTime;
28499   
28500   do {
28501     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
28502     nTries ++;
28503     if( rc==SQLITE_BUSY ){
28504       /* If the lock failed (busy):
28505        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
28506        * 2nd try: fail if the mod time changed or host id is different, wait 
28507        *           10 sec and try again
28508        * 3rd try: break the lock unless the mod time has changed.
28509        */
28510       struct stat buf;
28511       if( fstat(conchFile->h, &buf) ){
28512         pFile->lastErrno = errno;
28513         return SQLITE_IOERR_LOCK;
28514       }
28515       
28516       if( nTries==1 ){
28517         conchModTime = buf.st_mtimespec;
28518         usleep(500000); /* wait 0.5 sec and try the lock again*/
28519         continue;  
28520       }
28521
28522       assert( nTries>1 );
28523       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
28524          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
28525         return SQLITE_BUSY;
28526       }
28527       
28528       if( nTries==2 ){  
28529         char tBuf[PROXY_MAXCONCHLEN];
28530         int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
28531         if( len<0 ){
28532           pFile->lastErrno = errno;
28533           return SQLITE_IOERR_LOCK;
28534         }
28535         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
28536           /* don't break the lock if the host id doesn't match */
28537           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
28538             return SQLITE_BUSY;
28539           }
28540         }else{
28541           /* don't break the lock on short read or a version mismatch */
28542           return SQLITE_BUSY;
28543         }
28544         usleep(10000000); /* wait 10 sec and try the lock again */
28545         continue; 
28546       }
28547       
28548       assert( nTries==3 );
28549       if( 0==proxyBreakConchLock(pFile, myHostID) ){
28550         rc = SQLITE_OK;
28551         if( lockType==EXCLUSIVE_LOCK ){
28552           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
28553         }
28554         if( !rc ){
28555           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
28556         }
28557       }
28558     }
28559   } while( rc==SQLITE_BUSY && nTries<3 );
28560   
28561   return rc;
28562 }
28563
28564 /* Takes the conch by taking a shared lock and read the contents conch, if 
28565 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
28566 ** lockPath means that the lockPath in the conch file will be used if the 
28567 ** host IDs match, or a new lock path will be generated automatically 
28568 ** and written to the conch file.
28569 */
28570 static int proxyTakeConch(unixFile *pFile){
28571   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
28572   
28573   if( pCtx->conchHeld!=0 ){
28574     return SQLITE_OK;
28575   }else{
28576     unixFile *conchFile = pCtx->conchFile;
28577     uuid_t myHostID;
28578     int pError = 0;
28579     char readBuf[PROXY_MAXCONCHLEN];
28580     char lockPath[MAXPATHLEN];
28581     char *tempLockPath = NULL;
28582     int rc = SQLITE_OK;
28583     int createConch = 0;
28584     int hostIdMatch = 0;
28585     int readLen = 0;
28586     int tryOldLockPath = 0;
28587     int forceNewLockPath = 0;
28588     
28589     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
28590              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
28591
28592     rc = proxyGetHostID(myHostID, &pError);
28593     if( (rc&0xff)==SQLITE_IOERR ){
28594       pFile->lastErrno = pError;
28595       goto end_takeconch;
28596     }
28597     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
28598     if( rc!=SQLITE_OK ){
28599       goto end_takeconch;
28600     }
28601     /* read the existing conch file */
28602     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
28603     if( readLen<0 ){
28604       /* I/O error: lastErrno set by seekAndRead */
28605       pFile->lastErrno = conchFile->lastErrno;
28606       rc = SQLITE_IOERR_READ;
28607       goto end_takeconch;
28608     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
28609              readBuf[0]!=(char)PROXY_CONCHVERSION ){
28610       /* a short read or version format mismatch means we need to create a new 
28611       ** conch file. 
28612       */
28613       createConch = 1;
28614     }
28615     /* if the host id matches and the lock path already exists in the conch
28616     ** we'll try to use the path there, if we can't open that path, we'll 
28617     ** retry with a new auto-generated path 
28618     */
28619     do { /* in case we need to try again for an :auto: named lock file */
28620
28621       if( !createConch && !forceNewLockPath ){
28622         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
28623                                   PROXY_HOSTIDLEN);
28624         /* if the conch has data compare the contents */
28625         if( !pCtx->lockProxyPath ){
28626           /* for auto-named local lock file, just check the host ID and we'll
28627            ** use the local lock file path that's already in there
28628            */
28629           if( hostIdMatch ){
28630             size_t pathLen = (readLen - PROXY_PATHINDEX);
28631             
28632             if( pathLen>=MAXPATHLEN ){
28633               pathLen=MAXPATHLEN-1;
28634             }
28635             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
28636             lockPath[pathLen] = 0;
28637             tempLockPath = lockPath;
28638             tryOldLockPath = 1;
28639             /* create a copy of the lock path if the conch is taken */
28640             goto end_takeconch;
28641           }
28642         }else if( hostIdMatch
28643                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
28644                            readLen-PROXY_PATHINDEX)
28645         ){
28646           /* conch host and lock path match */
28647           goto end_takeconch; 
28648         }
28649       }
28650       
28651       /* if the conch isn't writable and doesn't match, we can't take it */
28652       if( (conchFile->openFlags&O_RDWR) == 0 ){
28653         rc = SQLITE_BUSY;
28654         goto end_takeconch;
28655       }
28656       
28657       /* either the conch didn't match or we need to create a new one */
28658       if( !pCtx->lockProxyPath ){
28659         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
28660         tempLockPath = lockPath;
28661         /* create a copy of the lock path _only_ if the conch is taken */
28662       }
28663       
28664       /* update conch with host and path (this will fail if other process
28665       ** has a shared lock already), if the host id matches, use the big
28666       ** stick.
28667       */
28668       futimes(conchFile->h, NULL);
28669       if( hostIdMatch && !createConch ){
28670         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
28671           /* We are trying for an exclusive lock but another thread in this
28672            ** same process is still holding a shared lock. */
28673           rc = SQLITE_BUSY;
28674         } else {          
28675           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
28676         }
28677       }else{
28678         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
28679       }
28680       if( rc==SQLITE_OK ){
28681         char writeBuffer[PROXY_MAXCONCHLEN];
28682         int writeSize = 0;
28683         
28684         writeBuffer[0] = (char)PROXY_CONCHVERSION;
28685         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
28686         if( pCtx->lockProxyPath!=NULL ){
28687           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
28688         }else{
28689           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
28690         }
28691         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
28692         ftruncate(conchFile->h, writeSize);
28693         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
28694         fsync(conchFile->h);
28695         /* If we created a new conch file (not just updated the contents of a 
28696          ** valid conch file), try to match the permissions of the database 
28697          */
28698         if( rc==SQLITE_OK && createConch ){
28699           struct stat buf;
28700           int err = fstat(pFile->h, &buf);
28701           if( err==0 ){
28702             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
28703                                         S_IROTH|S_IWOTH);
28704             /* try to match the database file R/W permissions, ignore failure */
28705 #ifndef SQLITE_PROXY_DEBUG
28706             fchmod(conchFile->h, cmode);
28707 #else
28708             if( fchmod(conchFile->h, cmode)!=0 ){
28709               int code = errno;
28710               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
28711                       cmode, code, strerror(code));
28712             } else {
28713               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
28714             }
28715           }else{
28716             int code = errno;
28717             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
28718                     err, code, strerror(code));
28719 #endif
28720           }
28721         }
28722       }
28723       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
28724       
28725     end_takeconch:
28726       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
28727       if( rc==SQLITE_OK && pFile->openFlags ){
28728         if( pFile->h>=0 ){
28729 #ifdef STRICT_CLOSE_ERROR
28730           if( close(pFile->h) ){
28731             pFile->lastErrno = errno;
28732             return SQLITE_IOERR_CLOSE;
28733           }
28734 #else
28735           close(pFile->h); /* silently leak fd if fail */
28736 #endif
28737         }
28738         pFile->h = -1;
28739         int fd = open(pCtx->dbPath, pFile->openFlags,
28740                       SQLITE_DEFAULT_FILE_PERMISSIONS);
28741         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
28742         if( fd>=0 ){
28743           pFile->h = fd;
28744         }else{
28745           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
28746            during locking */
28747         }
28748       }
28749       if( rc==SQLITE_OK && !pCtx->lockProxy ){
28750         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
28751         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
28752         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
28753           /* we couldn't create the proxy lock file with the old lock file path
28754            ** so try again via auto-naming 
28755            */
28756           forceNewLockPath = 1;
28757           tryOldLockPath = 0;
28758           continue; /* go back to the do {} while start point, try again */
28759         }
28760       }
28761       if( rc==SQLITE_OK ){
28762         /* Need to make a copy of path if we extracted the value
28763          ** from the conch file or the path was allocated on the stack
28764          */
28765         if( tempLockPath ){
28766           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
28767           if( !pCtx->lockProxyPath ){
28768             rc = SQLITE_NOMEM;
28769           }
28770         }
28771       }
28772       if( rc==SQLITE_OK ){
28773         pCtx->conchHeld = 1;
28774         
28775         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
28776           afpLockingContext *afpCtx;
28777           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
28778           afpCtx->dbPath = pCtx->lockProxyPath;
28779         }
28780       } else {
28781         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28782       }
28783       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
28784                rc==SQLITE_OK?"ok":"failed"));
28785       return rc;
28786     } while (1); /* in case we need to retry the :auto: lock file - 
28787                  ** we should never get here except via the 'continue' call. */
28788   }
28789 }
28790
28791 /*
28792 ** If pFile holds a lock on a conch file, then release that lock.
28793 */
28794 static int proxyReleaseConch(unixFile *pFile){
28795   int rc = SQLITE_OK;         /* Subroutine return code */
28796   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
28797   unixFile *conchFile;        /* Name of the conch file */
28798
28799   pCtx = (proxyLockingContext *)pFile->lockingContext;
28800   conchFile = pCtx->conchFile;
28801   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
28802            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
28803            getpid()));
28804   if( pCtx->conchHeld>0 ){
28805     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
28806   }
28807   pCtx->conchHeld = 0;
28808   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
28809            (rc==SQLITE_OK ? "ok" : "failed")));
28810   return rc;
28811 }
28812
28813 /*
28814 ** Given the name of a database file, compute the name of its conch file.
28815 ** Store the conch filename in memory obtained from sqlite3_malloc().
28816 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
28817 ** or SQLITE_NOMEM if unable to obtain memory.
28818 **
28819 ** The caller is responsible for ensuring that the allocated memory
28820 ** space is eventually freed.
28821 **
28822 ** *pConchPath is set to NULL if a memory allocation error occurs.
28823 */
28824 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
28825   int i;                        /* Loop counter */
28826   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
28827   char *conchPath;              /* buffer in which to construct conch name */
28828
28829   /* Allocate space for the conch filename and initialize the name to
28830   ** the name of the original database file. */  
28831   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
28832   if( conchPath==0 ){
28833     return SQLITE_NOMEM;
28834   }
28835   memcpy(conchPath, dbPath, len+1);
28836   
28837   /* now insert a "." before the last / character */
28838   for( i=(len-1); i>=0; i-- ){
28839     if( conchPath[i]=='/' ){
28840       i++;
28841       break;
28842     }
28843   }
28844   conchPath[i]='.';
28845   while ( i<len ){
28846     conchPath[i+1]=dbPath[i];
28847     i++;
28848   }
28849
28850   /* append the "-conch" suffix to the file */
28851   memcpy(&conchPath[i+1], "-conch", 7);
28852   assert( (int)strlen(conchPath) == len+7 );
28853
28854   return SQLITE_OK;
28855 }
28856
28857
28858 /* Takes a fully configured proxy locking-style unix file and switches
28859 ** the local lock file path 
28860 */
28861 static int switchLockProxyPath(unixFile *pFile, const char *path) {
28862   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
28863   char *oldPath = pCtx->lockProxyPath;
28864   int rc = SQLITE_OK;
28865
28866   if( pFile->eFileLock!=NO_LOCK ){
28867     return SQLITE_BUSY;
28868   }  
28869
28870   /* nothing to do if the path is NULL, :auto: or matches the existing path */
28871   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
28872     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
28873     return SQLITE_OK;
28874   }else{
28875     unixFile *lockProxy = pCtx->lockProxy;
28876     pCtx->lockProxy=NULL;
28877     pCtx->conchHeld = 0;
28878     if( lockProxy!=NULL ){
28879       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
28880       if( rc ) return rc;
28881       sqlite3_free(lockProxy);
28882     }
28883     sqlite3_free(oldPath);
28884     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
28885   }
28886   
28887   return rc;
28888 }
28889
28890 /*
28891 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
28892 ** is a string buffer at least MAXPATHLEN+1 characters in size.
28893 **
28894 ** This routine find the filename associated with pFile and writes it
28895 ** int dbPath.
28896 */
28897 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
28898 #if defined(__APPLE__)
28899   if( pFile->pMethod == &afpIoMethods ){
28900     /* afp style keeps a reference to the db path in the filePath field 
28901     ** of the struct */
28902     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28903     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
28904   } else
28905 #endif
28906   if( pFile->pMethod == &dotlockIoMethods ){
28907     /* dot lock style uses the locking context to store the dot lock
28908     ** file path */
28909     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
28910     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
28911   }else{
28912     /* all other styles use the locking context to store the db file path */
28913     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
28914     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
28915   }
28916   return SQLITE_OK;
28917 }
28918
28919 /*
28920 ** Takes an already filled in unix file and alters it so all file locking 
28921 ** will be performed on the local proxy lock file.  The following fields
28922 ** are preserved in the locking context so that they can be restored and 
28923 ** the unix structure properly cleaned up at close time:
28924 **  ->lockingContext
28925 **  ->pMethod
28926 */
28927 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
28928   proxyLockingContext *pCtx;
28929   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
28930   char *lockPath=NULL;
28931   int rc = SQLITE_OK;
28932   
28933   if( pFile->eFileLock!=NO_LOCK ){
28934     return SQLITE_BUSY;
28935   }
28936   proxyGetDbPathForUnixFile(pFile, dbPath);
28937   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
28938     lockPath=NULL;
28939   }else{
28940     lockPath=(char *)path;
28941   }
28942   
28943   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
28944            (lockPath ? lockPath : ":auto:"), getpid()));
28945
28946   pCtx = sqlite3_malloc( sizeof(*pCtx) );
28947   if( pCtx==0 ){
28948     return SQLITE_NOMEM;
28949   }
28950   memset(pCtx, 0, sizeof(*pCtx));
28951
28952   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
28953   if( rc==SQLITE_OK ){
28954     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
28955     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
28956       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
28957       ** (c) the file system is read-only, then enable no-locking access.
28958       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
28959       ** that openFlags will have only one of O_RDONLY or O_RDWR.
28960       */
28961       struct statfs fsInfo;
28962       struct stat conchInfo;
28963       int goLockless = 0;
28964
28965       if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
28966         int err = errno;
28967         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
28968           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
28969         }
28970       }
28971       if( goLockless ){
28972         pCtx->conchHeld = -1; /* read only FS/ lockless */
28973         rc = SQLITE_OK;
28974       }
28975     }
28976   }  
28977   if( rc==SQLITE_OK && lockPath ){
28978     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
28979   }
28980
28981   if( rc==SQLITE_OK ){
28982     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
28983     if( pCtx->dbPath==NULL ){
28984       rc = SQLITE_NOMEM;
28985     }
28986   }
28987   if( rc==SQLITE_OK ){
28988     /* all memory is allocated, proxys are created and assigned, 
28989     ** switch the locking context and pMethod then return.
28990     */
28991     pCtx->oldLockingContext = pFile->lockingContext;
28992     pFile->lockingContext = pCtx;
28993     pCtx->pOldMethod = pFile->pMethod;
28994     pFile->pMethod = &proxyIoMethods;
28995   }else{
28996     if( pCtx->conchFile ){ 
28997       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
28998       sqlite3_free(pCtx->conchFile);
28999     }
29000     sqlite3DbFree(0, pCtx->lockProxyPath);
29001     sqlite3_free(pCtx->conchFilePath); 
29002     sqlite3_free(pCtx);
29003   }
29004   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
29005            (rc==SQLITE_OK ? "ok" : "failed")));
29006   return rc;
29007 }
29008
29009
29010 /*
29011 ** This routine handles sqlite3_file_control() calls that are specific
29012 ** to proxy locking.
29013 */
29014 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
29015   switch( op ){
29016     case SQLITE_GET_LOCKPROXYFILE: {
29017       unixFile *pFile = (unixFile*)id;
29018       if( pFile->pMethod == &proxyIoMethods ){
29019         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
29020         proxyTakeConch(pFile);
29021         if( pCtx->lockProxyPath ){
29022           *(const char **)pArg = pCtx->lockProxyPath;
29023         }else{
29024           *(const char **)pArg = ":auto: (not held)";
29025         }
29026       } else {
29027         *(const char **)pArg = NULL;
29028       }
29029       return SQLITE_OK;
29030     }
29031     case SQLITE_SET_LOCKPROXYFILE: {
29032       unixFile *pFile = (unixFile*)id;
29033       int rc = SQLITE_OK;
29034       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
29035       if( pArg==NULL || (const char *)pArg==0 ){
29036         if( isProxyStyle ){
29037           /* turn off proxy locking - not supported */
29038           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
29039         }else{
29040           /* turn off proxy locking - already off - NOOP */
29041           rc = SQLITE_OK;
29042         }
29043       }else{
29044         const char *proxyPath = (const char *)pArg;
29045         if( isProxyStyle ){
29046           proxyLockingContext *pCtx = 
29047             (proxyLockingContext*)pFile->lockingContext;
29048           if( !strcmp(pArg, ":auto:") 
29049            || (pCtx->lockProxyPath &&
29050                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
29051           ){
29052             rc = SQLITE_OK;
29053           }else{
29054             rc = switchLockProxyPath(pFile, proxyPath);
29055           }
29056         }else{
29057           /* turn on proxy file locking */
29058           rc = proxyTransformUnixFile(pFile, proxyPath);
29059         }
29060       }
29061       return rc;
29062     }
29063     default: {
29064       assert( 0 );  /* The call assures that only valid opcodes are sent */
29065     }
29066   }
29067   /*NOTREACHED*/
29068   return SQLITE_ERROR;
29069 }
29070
29071 /*
29072 ** Within this division (the proxying locking implementation) the procedures
29073 ** above this point are all utilities.  The lock-related methods of the
29074 ** proxy-locking sqlite3_io_method object follow.
29075 */
29076
29077
29078 /*
29079 ** This routine checks if there is a RESERVED lock held on the specified
29080 ** file by this or any other process. If such a lock is held, set *pResOut
29081 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
29082 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
29083 */
29084 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
29085   unixFile *pFile = (unixFile*)id;
29086   int rc = proxyTakeConch(pFile);
29087   if( rc==SQLITE_OK ){
29088     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29089     if( pCtx->conchHeld>0 ){
29090       unixFile *proxy = pCtx->lockProxy;
29091       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
29092     }else{ /* conchHeld < 0 is lockless */
29093       pResOut=0;
29094     }
29095   }
29096   return rc;
29097 }
29098
29099 /*
29100 ** Lock the file with the lock specified by parameter eFileLock - one
29101 ** of the following:
29102 **
29103 **     (1) SHARED_LOCK
29104 **     (2) RESERVED_LOCK
29105 **     (3) PENDING_LOCK
29106 **     (4) EXCLUSIVE_LOCK
29107 **
29108 ** Sometimes when requesting one lock state, additional lock states
29109 ** are inserted in between.  The locking might fail on one of the later
29110 ** transitions leaving the lock state different from what it started but
29111 ** still short of its goal.  The following chart shows the allowed
29112 ** transitions and the inserted intermediate states:
29113 **
29114 **    UNLOCKED -> SHARED
29115 **    SHARED -> RESERVED
29116 **    SHARED -> (PENDING) -> EXCLUSIVE
29117 **    RESERVED -> (PENDING) -> EXCLUSIVE
29118 **    PENDING -> EXCLUSIVE
29119 **
29120 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
29121 ** routine to lower a locking level.
29122 */
29123 static int proxyLock(sqlite3_file *id, int eFileLock) {
29124   unixFile *pFile = (unixFile*)id;
29125   int rc = proxyTakeConch(pFile);
29126   if( rc==SQLITE_OK ){
29127     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29128     if( pCtx->conchHeld>0 ){
29129       unixFile *proxy = pCtx->lockProxy;
29130       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
29131       pFile->eFileLock = proxy->eFileLock;
29132     }else{
29133       /* conchHeld < 0 is lockless */
29134     }
29135   }
29136   return rc;
29137 }
29138
29139
29140 /*
29141 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
29142 ** must be either NO_LOCK or SHARED_LOCK.
29143 **
29144 ** If the locking level of the file descriptor is already at or below
29145 ** the requested locking level, this routine is a no-op.
29146 */
29147 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
29148   unixFile *pFile = (unixFile*)id;
29149   int rc = proxyTakeConch(pFile);
29150   if( rc==SQLITE_OK ){
29151     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29152     if( pCtx->conchHeld>0 ){
29153       unixFile *proxy = pCtx->lockProxy;
29154       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
29155       pFile->eFileLock = proxy->eFileLock;
29156     }else{
29157       /* conchHeld < 0 is lockless */
29158     }
29159   }
29160   return rc;
29161 }
29162
29163 /*
29164 ** Close a file that uses proxy locks.
29165 */
29166 static int proxyClose(sqlite3_file *id) {
29167   if( id ){
29168     unixFile *pFile = (unixFile*)id;
29169     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
29170     unixFile *lockProxy = pCtx->lockProxy;
29171     unixFile *conchFile = pCtx->conchFile;
29172     int rc = SQLITE_OK;
29173     
29174     if( lockProxy ){
29175       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
29176       if( rc ) return rc;
29177       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
29178       if( rc ) return rc;
29179       sqlite3_free(lockProxy);
29180       pCtx->lockProxy = 0;
29181     }
29182     if( conchFile ){
29183       if( pCtx->conchHeld ){
29184         rc = proxyReleaseConch(pFile);
29185         if( rc ) return rc;
29186       }
29187       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
29188       if( rc ) return rc;
29189       sqlite3_free(conchFile);
29190     }
29191     sqlite3DbFree(0, pCtx->lockProxyPath);
29192     sqlite3_free(pCtx->conchFilePath);
29193     sqlite3DbFree(0, pCtx->dbPath);
29194     /* restore the original locking context and pMethod then close it */
29195     pFile->lockingContext = pCtx->oldLockingContext;
29196     pFile->pMethod = pCtx->pOldMethod;
29197     sqlite3_free(pCtx);
29198     return pFile->pMethod->xClose(id);
29199   }
29200   return SQLITE_OK;
29201 }
29202
29203
29204
29205 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29206 /*
29207 ** The proxy locking style is intended for use with AFP filesystems.
29208 ** And since AFP is only supported on MacOSX, the proxy locking is also
29209 ** restricted to MacOSX.
29210 ** 
29211 **
29212 ******************* End of the proxy lock implementation **********************
29213 ******************************************************************************/
29214
29215 /*
29216 ** Initialize the operating system interface.
29217 **
29218 ** This routine registers all VFS implementations for unix-like operating
29219 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
29220 ** should be the only routines in this file that are visible from other
29221 ** files.
29222 **
29223 ** This routine is called once during SQLite initialization and by a
29224 ** single thread.  The memory allocation and mutex subsystems have not
29225 ** necessarily been initialized when this routine is called, and so they
29226 ** should not be used.
29227 */
29228 SQLITE_API int sqlite3_os_init(void){ 
29229   /* 
29230   ** The following macro defines an initializer for an sqlite3_vfs object.
29231   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
29232   ** to the "finder" function.  (pAppData is a pointer to a pointer because
29233   ** silly C90 rules prohibit a void* from being cast to a function pointer
29234   ** and so we have to go through the intermediate pointer to avoid problems
29235   ** when compiling with -pedantic-errors on GCC.)
29236   **
29237   ** The FINDER parameter to this macro is the name of the pointer to the
29238   ** finder-function.  The finder-function returns a pointer to the
29239   ** sqlite_io_methods object that implements the desired locking
29240   ** behaviors.  See the division above that contains the IOMETHODS
29241   ** macro for addition information on finder-functions.
29242   **
29243   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
29244   ** object.  But the "autolockIoFinder" available on MacOSX does a little
29245   ** more than that; it looks at the filesystem type that hosts the 
29246   ** database file and tries to choose an locking method appropriate for
29247   ** that filesystem time.
29248   */
29249   #define UNIXVFS(VFSNAME, FINDER) {                        \
29250     2,                    /* iVersion */                    \
29251     sizeof(unixFile),     /* szOsFile */                    \
29252     MAX_PATHNAME,         /* mxPathname */                  \
29253     0,                    /* pNext */                       \
29254     VFSNAME,              /* zName */                       \
29255     (void*)&FINDER,       /* pAppData */                    \
29256     unixOpen,             /* xOpen */                       \
29257     unixDelete,           /* xDelete */                     \
29258     unixAccess,           /* xAccess */                     \
29259     unixFullPathname,     /* xFullPathname */               \
29260     unixDlOpen,           /* xDlOpen */                     \
29261     unixDlError,          /* xDlError */                    \
29262     unixDlSym,            /* xDlSym */                      \
29263     unixDlClose,          /* xDlClose */                    \
29264     unixRandomness,       /* xRandomness */                 \
29265     unixSleep,            /* xSleep */                      \
29266     unixCurrentTime,      /* xCurrentTime */                \
29267     unixGetLastError,     /* xGetLastError */               \
29268     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
29269   }
29270
29271   /*
29272   ** All default VFSes for unix are contained in the following array.
29273   **
29274   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
29275   ** by the SQLite core when the VFS is registered.  So the following
29276   ** array cannot be const.
29277   */
29278   static sqlite3_vfs aVfs[] = {
29279 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
29280     UNIXVFS("unix",          autolockIoFinder ),
29281 #else
29282     UNIXVFS("unix",          posixIoFinder ),
29283 #endif
29284     UNIXVFS("unix-none",     nolockIoFinder ),
29285     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
29286 #if OS_VXWORKS
29287     UNIXVFS("unix-namedsem", semIoFinder ),
29288 #endif
29289 #if SQLITE_ENABLE_LOCKING_STYLE
29290     UNIXVFS("unix-posix",    posixIoFinder ),
29291 #if !OS_VXWORKS
29292     UNIXVFS("unix-flock",    flockIoFinder ),
29293 #endif
29294 #endif
29295 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29296     UNIXVFS("unix-afp",      afpIoFinder ),
29297     UNIXVFS("unix-nfs",      nfsIoFinder ),
29298     UNIXVFS("unix-proxy",    proxyIoFinder ),
29299 #endif
29300   };
29301   unsigned int i;          /* Loop counter */
29302
29303   /* Register all VFSes defined in the aVfs[] array */
29304   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
29305     sqlite3_vfs_register(&aVfs[i], i==0);
29306   }
29307   return SQLITE_OK; 
29308 }
29309
29310 /*
29311 ** Shutdown the operating system interface.
29312 **
29313 ** Some operating systems might need to do some cleanup in this routine,
29314 ** to release dynamically allocated objects.  But not on unix.
29315 ** This routine is a no-op for unix.
29316 */
29317 SQLITE_API int sqlite3_os_end(void){ 
29318   return SQLITE_OK; 
29319 }
29320  
29321 #endif /* SQLITE_OS_UNIX */
29322
29323 /************** End of os_unix.c *********************************************/
29324 /************** Begin file os_win.c ******************************************/
29325 /*
29326 ** 2004 May 22
29327 **
29328 ** The author disclaims copyright to this source code.  In place of
29329 ** a legal notice, here is a blessing:
29330 **
29331 **    May you do good and not evil.
29332 **    May you find forgiveness for yourself and forgive others.
29333 **    May you share freely, never taking more than you give.
29334 **
29335 ******************************************************************************
29336 **
29337 ** This file contains code that is specific to windows.
29338 */
29339 #if SQLITE_OS_WIN               /* This file is used for windows only */
29340
29341
29342 /*
29343 ** A Note About Memory Allocation:
29344 **
29345 ** This driver uses malloc()/free() directly rather than going through
29346 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
29347 ** are designed for use on embedded systems where memory is scarce and
29348 ** malloc failures happen frequently.  Win32 does not typically run on
29349 ** embedded systems, and when it does the developers normally have bigger
29350 ** problems to worry about than running out of memory.  So there is not
29351 ** a compelling need to use the wrappers.
29352 **
29353 ** But there is a good reason to not use the wrappers.  If we use the
29354 ** wrappers then we will get simulated malloc() failures within this
29355 ** driver.  And that causes all kinds of problems for our tests.  We
29356 ** could enhance SQLite to deal with simulated malloc failures within
29357 ** the OS driver, but the code to deal with those failure would not
29358 ** be exercised on Linux (which does not need to malloc() in the driver)
29359 ** and so we would have difficulty writing coverage tests for that
29360 ** code.  Better to leave the code out, we think.
29361 **
29362 ** The point of this discussion is as follows:  When creating a new
29363 ** OS layer for an embedded system, if you use this file as an example,
29364 ** avoid the use of malloc()/free().  Those routines work ok on windows
29365 ** desktops but not so well in embedded systems.
29366 */
29367
29368 #include <winbase.h>
29369
29370 #ifdef __CYGWIN__
29371 # include <sys/cygwin.h>
29372 #endif
29373
29374 /*
29375 ** Macros used to determine whether or not to use threads.
29376 */
29377 #if defined(THREADSAFE) && THREADSAFE
29378 # define SQLITE_W32_THREADS 1
29379 #endif
29380
29381 /*
29382 ** Include code that is common to all os_*.c files
29383 */
29384 /************** Include os_common.h in the middle of os_win.c ****************/
29385 /************** Begin file os_common.h ***************************************/
29386 /*
29387 ** 2004 May 22
29388 **
29389 ** The author disclaims copyright to this source code.  In place of
29390 ** a legal notice, here is a blessing:
29391 **
29392 **    May you do good and not evil.
29393 **    May you find forgiveness for yourself and forgive others.
29394 **    May you share freely, never taking more than you give.
29395 **
29396 ******************************************************************************
29397 **
29398 ** This file contains macros and a little bit of code that is common to
29399 ** all of the platform-specific files (os_*.c) and is #included into those
29400 ** files.
29401 **
29402 ** This file should be #included by the os_*.c files only.  It is not a
29403 ** general purpose header file.
29404 */
29405 #ifndef _OS_COMMON_H_
29406 #define _OS_COMMON_H_
29407
29408 /*
29409 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29410 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29411 ** switch.  The following code should catch this problem at compile-time.
29412 */
29413 #ifdef MEMORY_DEBUG
29414 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
29415 #endif
29416
29417 #ifdef SQLITE_DEBUG
29418 SQLITE_PRIVATE int sqlite3OSTrace = 0;
29419 #define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
29420 #else
29421 #define OSTRACE(X)
29422 #endif
29423
29424 /*
29425 ** Macros for performance tracing.  Normally turned off.  Only works
29426 ** on i486 hardware.
29427 */
29428 #ifdef SQLITE_PERFORMANCE_TRACE
29429
29430 /* 
29431 ** hwtime.h contains inline assembler code for implementing 
29432 ** high-performance timing routines.
29433 */
29434 /************** Include hwtime.h in the middle of os_common.h ****************/
29435 /************** Begin file hwtime.h ******************************************/
29436 /*
29437 ** 2008 May 27
29438 **
29439 ** The author disclaims copyright to this source code.  In place of
29440 ** a legal notice, here is a blessing:
29441 **
29442 **    May you do good and not evil.
29443 **    May you find forgiveness for yourself and forgive others.
29444 **    May you share freely, never taking more than you give.
29445 **
29446 ******************************************************************************
29447 **
29448 ** This file contains inline asm code for retrieving "high-performance"
29449 ** counters for x86 class CPUs.
29450 */
29451 #ifndef _HWTIME_H_
29452 #define _HWTIME_H_
29453
29454 /*
29455 ** The following routine only works on pentium-class (or newer) processors.
29456 ** It uses the RDTSC opcode to read the cycle count value out of the
29457 ** processor and returns that value.  This can be used for high-res
29458 ** profiling.
29459 */
29460 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
29461       (defined(i386) || defined(__i386__) || defined(_M_IX86))
29462
29463   #if defined(__GNUC__)
29464
29465   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29466      unsigned int lo, hi;
29467      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29468      return (sqlite_uint64)hi << 32 | lo;
29469   }
29470
29471   #elif defined(_MSC_VER)
29472
29473   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29474      __asm {
29475         rdtsc
29476         ret       ; return value at EDX:EAX
29477      }
29478   }
29479
29480   #endif
29481
29482 #elif (defined(__GNUC__) && defined(__x86_64__))
29483
29484   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29485       unsigned long val;
29486       __asm__ __volatile__ ("rdtsc" : "=A" (val));
29487       return val;
29488   }
29489  
29490 #elif (defined(__GNUC__) && defined(__ppc__))
29491
29492   __inline__ sqlite_uint64 sqlite3Hwtime(void){
29493       unsigned long long retval;
29494       unsigned long junk;
29495       __asm__ __volatile__ ("\n\
29496           1:      mftbu   %1\n\
29497                   mftb    %L0\n\
29498                   mftbu   %0\n\
29499                   cmpw    %0,%1\n\
29500                   bne     1b"
29501                   : "=r" (retval), "=r" (junk));
29502       return retval;
29503   }
29504
29505 #else
29506
29507   #error Need implementation of sqlite3Hwtime() for your platform.
29508
29509   /*
29510   ** To compile without implementing sqlite3Hwtime() for your platform,
29511   ** you can remove the above #error and use the following
29512   ** stub function.  You will lose timing support for many
29513   ** of the debugging and testing utilities, but it should at
29514   ** least compile and run.
29515   */
29516 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29517
29518 #endif
29519
29520 #endif /* !defined(_HWTIME_H_) */
29521
29522 /************** End of hwtime.h **********************************************/
29523 /************** Continuing where we left off in os_common.h ******************/
29524
29525 static sqlite_uint64 g_start;
29526 static sqlite_uint64 g_elapsed;
29527 #define TIMER_START       g_start=sqlite3Hwtime()
29528 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
29529 #define TIMER_ELAPSED     g_elapsed
29530 #else
29531 #define TIMER_START
29532 #define TIMER_END
29533 #define TIMER_ELAPSED     ((sqlite_uint64)0)
29534 #endif
29535
29536 /*
29537 ** If we compile with the SQLITE_TEST macro set, then the following block
29538 ** of code will give us the ability to simulate a disk I/O error.  This
29539 ** is used for testing the I/O recovery logic.
29540 */
29541 #ifdef SQLITE_TEST
29542 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
29543 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
29544 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
29545 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
29546 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
29547 SQLITE_API int sqlite3_diskfull_pending = 0;
29548 SQLITE_API int sqlite3_diskfull = 0;
29549 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29550 #define SimulateIOError(CODE)  \
29551   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29552        || sqlite3_io_error_pending-- == 1 )  \
29553               { local_ioerr(); CODE; }
29554 static void local_ioerr(){
29555   IOTRACE(("IOERR\n"));
29556   sqlite3_io_error_hit++;
29557   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29558 }
29559 #define SimulateDiskfullError(CODE) \
29560    if( sqlite3_diskfull_pending ){ \
29561      if( sqlite3_diskfull_pending == 1 ){ \
29562        local_ioerr(); \
29563        sqlite3_diskfull = 1; \
29564        sqlite3_io_error_hit = 1; \
29565        CODE; \
29566      }else{ \
29567        sqlite3_diskfull_pending--; \
29568      } \
29569    }
29570 #else
29571 #define SimulateIOErrorBenign(X)
29572 #define SimulateIOError(A)
29573 #define SimulateDiskfullError(A)
29574 #endif
29575
29576 /*
29577 ** When testing, keep a count of the number of open files.
29578 */
29579 #ifdef SQLITE_TEST
29580 SQLITE_API int sqlite3_open_file_count = 0;
29581 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
29582 #else
29583 #define OpenCounter(X)
29584 #endif
29585
29586 #endif /* !defined(_OS_COMMON_H_) */
29587
29588 /************** End of os_common.h *******************************************/
29589 /************** Continuing where we left off in os_win.c *********************/
29590
29591 /*
29592 ** Some microsoft compilers lack this definition.
29593 */
29594 #ifndef INVALID_FILE_ATTRIBUTES
29595 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
29596 #endif
29597
29598 /*
29599 ** Determine if we are dealing with WindowsCE - which has a much
29600 ** reduced API.
29601 */
29602 #if SQLITE_OS_WINCE
29603 # define AreFileApisANSI() 1
29604 # define FormatMessageW(a,b,c,d,e,f,g) 0
29605 #endif
29606
29607 /* Forward references */
29608 typedef struct winShm winShm;           /* A connection to shared-memory */
29609 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
29610
29611 /*
29612 ** WinCE lacks native support for file locking so we have to fake it
29613 ** with some code of our own.
29614 */
29615 #if SQLITE_OS_WINCE
29616 typedef struct winceLock {
29617   int nReaders;       /* Number of reader locks obtained */
29618   BOOL bPending;      /* Indicates a pending lock has been obtained */
29619   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
29620   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
29621 } winceLock;
29622 #endif
29623
29624 /*
29625 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
29626 ** portability layer.
29627 */
29628 typedef struct winFile winFile;
29629 struct winFile {
29630   const sqlite3_io_methods *pMethod; /*** Must be first ***/
29631   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
29632   HANDLE h;               /* Handle for accessing the file */
29633   unsigned char locktype; /* Type of lock currently held on this file */
29634   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
29635   DWORD lastErrno;        /* The Windows errno from the last I/O error */
29636   DWORD sectorSize;       /* Sector size of the device file is on */
29637   winShm *pShm;           /* Instance of shared memory on this file */
29638   const char *zPath;      /* Full pathname of this file */
29639   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
29640 #if SQLITE_OS_WINCE
29641   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
29642   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
29643   HANDLE hShared;         /* Shared memory segment used for locking */
29644   winceLock local;        /* Locks obtained by this instance of winFile */
29645   winceLock *shared;      /* Global shared lock memory for the file  */
29646 #endif
29647 };
29648
29649 /*
29650 ** Forward prototypes.
29651 */
29652 static int getSectorSize(
29653     sqlite3_vfs *pVfs,
29654     const char *zRelative     /* UTF-8 file name */
29655 );
29656
29657 /*
29658 ** The following variable is (normally) set once and never changes
29659 ** thereafter.  It records whether the operating system is Win95
29660 ** or WinNT.
29661 **
29662 ** 0:   Operating system unknown.
29663 ** 1:   Operating system is Win95.
29664 ** 2:   Operating system is WinNT.
29665 **
29666 ** In order to facilitate testing on a WinNT system, the test fixture
29667 ** can manually set this value to 1 to emulate Win98 behavior.
29668 */
29669 #ifdef SQLITE_TEST
29670 SQLITE_API int sqlite3_os_type = 0;
29671 #else
29672 static int sqlite3_os_type = 0;
29673 #endif
29674
29675 /*
29676 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
29677 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
29678 **
29679 ** Here is an interesting observation:  Win95, Win98, and WinME lack
29680 ** the LockFileEx() API.  But we can still statically link against that
29681 ** API as long as we don't call it when running Win95/98/ME.  A call to
29682 ** this routine is used to determine if the host is Win95/98/ME or
29683 ** WinNT/2K/XP so that we will know whether or not we can safely call
29684 ** the LockFileEx() API.
29685 */
29686 #if SQLITE_OS_WINCE
29687 # define isNT()  (1)
29688 #else
29689   static int isNT(void){
29690     if( sqlite3_os_type==0 ){
29691       OSVERSIONINFO sInfo;
29692       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
29693       GetVersionEx(&sInfo);
29694       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
29695     }
29696     return sqlite3_os_type==2;
29697   }
29698 #endif /* SQLITE_OS_WINCE */
29699
29700 /*
29701 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
29702 **
29703 ** Space to hold the returned string is obtained from malloc.
29704 */
29705 static WCHAR *utf8ToUnicode(const char *zFilename){
29706   int nChar;
29707   WCHAR *zWideFilename;
29708
29709   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
29710   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
29711   if( zWideFilename==0 ){
29712     return 0;
29713   }
29714   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
29715   if( nChar==0 ){
29716     free(zWideFilename);
29717     zWideFilename = 0;
29718   }
29719   return zWideFilename;
29720 }
29721
29722 /*
29723 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
29724 ** obtained from malloc().
29725 */
29726 static char *unicodeToUtf8(const WCHAR *zWideFilename){
29727   int nByte;
29728   char *zFilename;
29729
29730   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
29731   zFilename = malloc( nByte );
29732   if( zFilename==0 ){
29733     return 0;
29734   }
29735   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
29736                               0, 0);
29737   if( nByte == 0 ){
29738     free(zFilename);
29739     zFilename = 0;
29740   }
29741   return zFilename;
29742 }
29743
29744 /*
29745 ** Convert an ansi string to microsoft unicode, based on the
29746 ** current codepage settings for file apis.
29747 ** 
29748 ** Space to hold the returned string is obtained
29749 ** from malloc.
29750 */
29751 static WCHAR *mbcsToUnicode(const char *zFilename){
29752   int nByte;
29753   WCHAR *zMbcsFilename;
29754   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29755
29756   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
29757   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
29758   if( zMbcsFilename==0 ){
29759     return 0;
29760   }
29761   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
29762   if( nByte==0 ){
29763     free(zMbcsFilename);
29764     zMbcsFilename = 0;
29765   }
29766   return zMbcsFilename;
29767 }
29768
29769 /*
29770 ** Convert microsoft unicode to multibyte character string, based on the
29771 ** user's Ansi codepage.
29772 **
29773 ** Space to hold the returned string is obtained from
29774 ** malloc().
29775 */
29776 static char *unicodeToMbcs(const WCHAR *zWideFilename){
29777   int nByte;
29778   char *zFilename;
29779   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
29780
29781   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
29782   zFilename = malloc( nByte );
29783   if( zFilename==0 ){
29784     return 0;
29785   }
29786   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
29787                               0, 0);
29788   if( nByte == 0 ){
29789     free(zFilename);
29790     zFilename = 0;
29791   }
29792   return zFilename;
29793 }
29794
29795 /*
29796 ** Convert multibyte character string to UTF-8.  Space to hold the
29797 ** returned string is obtained from malloc().
29798 */
29799 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
29800   char *zFilenameUtf8;
29801   WCHAR *zTmpWide;
29802
29803   zTmpWide = mbcsToUnicode(zFilename);
29804   if( zTmpWide==0 ){
29805     return 0;
29806   }
29807   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
29808   free(zTmpWide);
29809   return zFilenameUtf8;
29810 }
29811
29812 /*
29813 ** Convert UTF-8 to multibyte character string.  Space to hold the 
29814 ** returned string is obtained from malloc().
29815 */
29816 static char *utf8ToMbcs(const char *zFilename){
29817   char *zFilenameMbcs;
29818   WCHAR *zTmpWide;
29819
29820   zTmpWide = utf8ToUnicode(zFilename);
29821   if( zTmpWide==0 ){
29822     return 0;
29823   }
29824   zFilenameMbcs = unicodeToMbcs(zTmpWide);
29825   free(zTmpWide);
29826   return zFilenameMbcs;
29827 }
29828
29829 #if SQLITE_OS_WINCE
29830 /*************************************************************************
29831 ** This section contains code for WinCE only.
29832 */
29833 /*
29834 ** WindowsCE does not have a localtime() function.  So create a
29835 ** substitute.
29836 */
29837 struct tm *__cdecl localtime(const time_t *t)
29838 {
29839   static struct tm y;
29840   FILETIME uTm, lTm;
29841   SYSTEMTIME pTm;
29842   sqlite3_int64 t64;
29843   t64 = *t;
29844   t64 = (t64 + 11644473600)*10000000;
29845   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
29846   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
29847   FileTimeToLocalFileTime(&uTm,&lTm);
29848   FileTimeToSystemTime(&lTm,&pTm);
29849   y.tm_year = pTm.wYear - 1900;
29850   y.tm_mon = pTm.wMonth - 1;
29851   y.tm_wday = pTm.wDayOfWeek;
29852   y.tm_mday = pTm.wDay;
29853   y.tm_hour = pTm.wHour;
29854   y.tm_min = pTm.wMinute;
29855   y.tm_sec = pTm.wSecond;
29856   return &y;
29857 }
29858
29859 /* This will never be called, but defined to make the code compile */
29860 #define GetTempPathA(a,b)
29861
29862 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
29863 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
29864 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
29865
29866 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
29867
29868 /*
29869 ** Acquire a lock on the handle h
29870 */
29871 static void winceMutexAcquire(HANDLE h){
29872    DWORD dwErr;
29873    do {
29874      dwErr = WaitForSingleObject(h, INFINITE);
29875    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
29876 }
29877 /*
29878 ** Release a lock acquired by winceMutexAcquire()
29879 */
29880 #define winceMutexRelease(h) ReleaseMutex(h)
29881
29882 /*
29883 ** Create the mutex and shared memory used for locking in the file
29884 ** descriptor pFile
29885 */
29886 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
29887   WCHAR *zTok;
29888   WCHAR *zName = utf8ToUnicode(zFilename);
29889   BOOL bInit = TRUE;
29890
29891   /* Initialize the local lockdata */
29892   ZeroMemory(&pFile->local, sizeof(pFile->local));
29893
29894   /* Replace the backslashes from the filename and lowercase it
29895   ** to derive a mutex name. */
29896   zTok = CharLowerW(zName);
29897   for (;*zTok;zTok++){
29898     if (*zTok == '\\') *zTok = '_';
29899   }
29900
29901   /* Create/open the named mutex */
29902   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
29903   if (!pFile->hMutex){
29904     pFile->lastErrno = GetLastError();
29905     free(zName);
29906     return FALSE;
29907   }
29908
29909   /* Acquire the mutex before continuing */
29910   winceMutexAcquire(pFile->hMutex);
29911   
29912   /* Since the names of named mutexes, semaphores, file mappings etc are 
29913   ** case-sensitive, take advantage of that by uppercasing the mutex name
29914   ** and using that as the shared filemapping name.
29915   */
29916   CharUpperW(zName);
29917   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
29918                                        PAGE_READWRITE, 0, sizeof(winceLock),
29919                                        zName);  
29920
29921   /* Set a flag that indicates we're the first to create the memory so it 
29922   ** must be zero-initialized */
29923   if (GetLastError() == ERROR_ALREADY_EXISTS){
29924     bInit = FALSE;
29925   }
29926
29927   free(zName);
29928
29929   /* If we succeeded in making the shared memory handle, map it. */
29930   if (pFile->hShared){
29931     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
29932              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
29933     /* If mapping failed, close the shared memory handle and erase it */
29934     if (!pFile->shared){
29935       pFile->lastErrno = GetLastError();
29936       CloseHandle(pFile->hShared);
29937       pFile->hShared = NULL;
29938     }
29939   }
29940
29941   /* If shared memory could not be created, then close the mutex and fail */
29942   if (pFile->hShared == NULL){
29943     winceMutexRelease(pFile->hMutex);
29944     CloseHandle(pFile->hMutex);
29945     pFile->hMutex = NULL;
29946     return FALSE;
29947   }
29948   
29949   /* Initialize the shared memory if we're supposed to */
29950   if (bInit) {
29951     ZeroMemory(pFile->shared, sizeof(winceLock));
29952   }
29953
29954   winceMutexRelease(pFile->hMutex);
29955   return TRUE;
29956 }
29957
29958 /*
29959 ** Destroy the part of winFile that deals with wince locks
29960 */
29961 static void winceDestroyLock(winFile *pFile){
29962   if (pFile->hMutex){
29963     /* Acquire the mutex */
29964     winceMutexAcquire(pFile->hMutex);
29965
29966     /* The following blocks should probably assert in debug mode, but they
29967        are to cleanup in case any locks remained open */
29968     if (pFile->local.nReaders){
29969       pFile->shared->nReaders --;
29970     }
29971     if (pFile->local.bReserved){
29972       pFile->shared->bReserved = FALSE;
29973     }
29974     if (pFile->local.bPending){
29975       pFile->shared->bPending = FALSE;
29976     }
29977     if (pFile->local.bExclusive){
29978       pFile->shared->bExclusive = FALSE;
29979     }
29980
29981     /* De-reference and close our copy of the shared memory handle */
29982     UnmapViewOfFile(pFile->shared);
29983     CloseHandle(pFile->hShared);
29984
29985     /* Done with the mutex */
29986     winceMutexRelease(pFile->hMutex);    
29987     CloseHandle(pFile->hMutex);
29988     pFile->hMutex = NULL;
29989   }
29990 }
29991
29992 /* 
29993 ** An implementation of the LockFile() API of windows for wince
29994 */
29995 static BOOL winceLockFile(
29996   HANDLE *phFile,
29997   DWORD dwFileOffsetLow,
29998   DWORD dwFileOffsetHigh,
29999   DWORD nNumberOfBytesToLockLow,
30000   DWORD nNumberOfBytesToLockHigh
30001 ){
30002   winFile *pFile = HANDLE_TO_WINFILE(phFile);
30003   BOOL bReturn = FALSE;
30004
30005   UNUSED_PARAMETER(dwFileOffsetHigh);
30006   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
30007
30008   if (!pFile->hMutex) return TRUE;
30009   winceMutexAcquire(pFile->hMutex);
30010
30011   /* Wanting an exclusive lock? */
30012   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
30013        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
30014     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
30015        pFile->shared->bExclusive = TRUE;
30016        pFile->local.bExclusive = TRUE;
30017        bReturn = TRUE;
30018     }
30019   }
30020
30021   /* Want a read-only lock? */
30022   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
30023            nNumberOfBytesToLockLow == 1){
30024     if (pFile->shared->bExclusive == 0){
30025       pFile->local.nReaders ++;
30026       if (pFile->local.nReaders == 1){
30027         pFile->shared->nReaders ++;
30028       }
30029       bReturn = TRUE;
30030     }
30031   }
30032
30033   /* Want a pending lock? */
30034   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
30035     /* If no pending lock has been acquired, then acquire it */
30036     if (pFile->shared->bPending == 0) {
30037       pFile->shared->bPending = TRUE;
30038       pFile->local.bPending = TRUE;
30039       bReturn = TRUE;
30040     }
30041   }
30042
30043   /* Want a reserved lock? */
30044   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
30045     if (pFile->shared->bReserved == 0) {
30046       pFile->shared->bReserved = TRUE;
30047       pFile->local.bReserved = TRUE;
30048       bReturn = TRUE;
30049     }
30050   }
30051
30052   winceMutexRelease(pFile->hMutex);
30053   return bReturn;
30054 }
30055
30056 /*
30057 ** An implementation of the UnlockFile API of windows for wince
30058 */
30059 static BOOL winceUnlockFile(
30060   HANDLE *phFile,
30061   DWORD dwFileOffsetLow,
30062   DWORD dwFileOffsetHigh,
30063   DWORD nNumberOfBytesToUnlockLow,
30064   DWORD nNumberOfBytesToUnlockHigh
30065 ){
30066   winFile *pFile = HANDLE_TO_WINFILE(phFile);
30067   BOOL bReturn = FALSE;
30068
30069   UNUSED_PARAMETER(dwFileOffsetHigh);
30070   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
30071
30072   if (!pFile->hMutex) return TRUE;
30073   winceMutexAcquire(pFile->hMutex);
30074
30075   /* Releasing a reader lock or an exclusive lock */
30076   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
30077     /* Did we have an exclusive lock? */
30078     if (pFile->local.bExclusive){
30079       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
30080       pFile->local.bExclusive = FALSE;
30081       pFile->shared->bExclusive = FALSE;
30082       bReturn = TRUE;
30083     }
30084
30085     /* Did we just have a reader lock? */
30086     else if (pFile->local.nReaders){
30087       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
30088       pFile->local.nReaders --;
30089       if (pFile->local.nReaders == 0)
30090       {
30091         pFile->shared->nReaders --;
30092       }
30093       bReturn = TRUE;
30094     }
30095   }
30096
30097   /* Releasing a pending lock */
30098   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
30099     if (pFile->local.bPending){
30100       pFile->local.bPending = FALSE;
30101       pFile->shared->bPending = FALSE;
30102       bReturn = TRUE;
30103     }
30104   }
30105   /* Releasing a reserved lock */
30106   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
30107     if (pFile->local.bReserved) {
30108       pFile->local.bReserved = FALSE;
30109       pFile->shared->bReserved = FALSE;
30110       bReturn = TRUE;
30111     }
30112   }
30113
30114   winceMutexRelease(pFile->hMutex);
30115   return bReturn;
30116 }
30117
30118 /*
30119 ** An implementation of the LockFileEx() API of windows for wince
30120 */
30121 static BOOL winceLockFileEx(
30122   HANDLE *phFile,
30123   DWORD dwFlags,
30124   DWORD dwReserved,
30125   DWORD nNumberOfBytesToLockLow,
30126   DWORD nNumberOfBytesToLockHigh,
30127   LPOVERLAPPED lpOverlapped
30128 ){
30129   UNUSED_PARAMETER(dwReserved);
30130   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
30131
30132   /* If the caller wants a shared read lock, forward this call
30133   ** to winceLockFile */
30134   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
30135       dwFlags == 1 &&
30136       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
30137     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
30138   }
30139   return FALSE;
30140 }
30141 /*
30142 ** End of the special code for wince
30143 *****************************************************************************/
30144 #endif /* SQLITE_OS_WINCE */
30145
30146 /*****************************************************************************
30147 ** The next group of routines implement the I/O methods specified
30148 ** by the sqlite3_io_methods object.
30149 ******************************************************************************/
30150
30151 /*
30152 ** Some microsoft compilers lack this definition.
30153 */
30154 #ifndef INVALID_SET_FILE_POINTER
30155 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
30156 #endif
30157
30158 /*
30159 ** Move the current position of the file handle passed as the first 
30160 ** argument to offset iOffset within the file. If successful, return 0. 
30161 ** Otherwise, set pFile->lastErrno and return non-zero.
30162 */
30163 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
30164   LONG upperBits;                 /* Most sig. 32 bits of new offset */
30165   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
30166   DWORD dwRet;                    /* Value returned by SetFilePointer() */
30167
30168   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
30169   lowerBits = (LONG)(iOffset & 0xffffffff);
30170
30171   /* API oddity: If successful, SetFilePointer() returns a dword 
30172   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
30173   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
30174   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
30175   ** whether an error has actually occured, it is also necessary to call 
30176   ** GetLastError().
30177   */
30178   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
30179   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
30180     pFile->lastErrno = GetLastError();
30181     return 1;
30182   }
30183
30184   return 0;
30185 }
30186
30187 /*
30188 ** Close a file.
30189 **
30190 ** It is reported that an attempt to close a handle might sometimes
30191 ** fail.  This is a very unreasonable result, but windows is notorious
30192 ** for being unreasonable so I do not doubt that it might happen.  If
30193 ** the close fails, we pause for 100 milliseconds and try again.  As
30194 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
30195 ** giving up and returning an error.
30196 */
30197 #define MX_CLOSE_ATTEMPT 3
30198 static int winClose(sqlite3_file *id){
30199   int rc, cnt = 0;
30200   winFile *pFile = (winFile*)id;
30201
30202   assert( id!=0 );
30203   assert( pFile->pShm==0 );
30204   OSTRACE(("CLOSE %d\n", pFile->h));
30205   do{
30206     rc = CloseHandle(pFile->h);
30207     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
30208   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
30209 #if SQLITE_OS_WINCE
30210 #define WINCE_DELETION_ATTEMPTS 3
30211   winceDestroyLock(pFile);
30212   if( pFile->zDeleteOnClose ){
30213     int cnt = 0;
30214     while(
30215            DeleteFileW(pFile->zDeleteOnClose)==0
30216         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
30217         && cnt++ < WINCE_DELETION_ATTEMPTS
30218     ){
30219        Sleep(100);  /* Wait a little before trying again */
30220     }
30221     free(pFile->zDeleteOnClose);
30222   }
30223 #endif
30224   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
30225   OpenCounter(-1);
30226   return rc ? SQLITE_OK : SQLITE_IOERR;
30227 }
30228
30229 /*
30230 ** Read data from a file into a buffer.  Return SQLITE_OK if all
30231 ** bytes were read successfully and SQLITE_IOERR if anything goes
30232 ** wrong.
30233 */
30234 static int winRead(
30235   sqlite3_file *id,          /* File to read from */
30236   void *pBuf,                /* Write content into this buffer */
30237   int amt,                   /* Number of bytes to read */
30238   sqlite3_int64 offset       /* Begin reading at this offset */
30239 ){
30240   winFile *pFile = (winFile*)id;  /* file handle */
30241   DWORD nRead;                    /* Number of bytes actually read from file */
30242
30243   assert( id!=0 );
30244   SimulateIOError(return SQLITE_IOERR_READ);
30245   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
30246
30247   if( seekWinFile(pFile, offset) ){
30248     return SQLITE_FULL;
30249   }
30250   if( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
30251     pFile->lastErrno = GetLastError();
30252     return SQLITE_IOERR_READ;
30253   }
30254   if( nRead<(DWORD)amt ){
30255     /* Unread parts of the buffer must be zero-filled */
30256     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
30257     return SQLITE_IOERR_SHORT_READ;
30258   }
30259
30260   return SQLITE_OK;
30261 }
30262
30263 /*
30264 ** Write data from a buffer into a file.  Return SQLITE_OK on success
30265 ** or some other error code on failure.
30266 */
30267 static int winWrite(
30268   sqlite3_file *id,               /* File to write into */
30269   const void *pBuf,               /* The bytes to be written */
30270   int amt,                        /* Number of bytes to write */
30271   sqlite3_int64 offset            /* Offset into the file to begin writing at */
30272 ){
30273   int rc;                         /* True if error has occured, else false */
30274   winFile *pFile = (winFile*)id;  /* File handle */
30275
30276   assert( amt>0 );
30277   assert( pFile );
30278   SimulateIOError(return SQLITE_IOERR_WRITE);
30279   SimulateDiskfullError(return SQLITE_FULL);
30280
30281   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
30282
30283   rc = seekWinFile(pFile, offset);
30284   if( rc==0 ){
30285     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
30286     int nRem = amt;               /* Number of bytes yet to be written */
30287     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
30288
30289     while( nRem>0 && WriteFile(pFile->h, aRem, nRem, &nWrite, 0) && nWrite>0 ){
30290       aRem += nWrite;
30291       nRem -= nWrite;
30292     }
30293     if( nRem>0 ){
30294       pFile->lastErrno = GetLastError();
30295       rc = 1;
30296     }
30297   }
30298
30299   if( rc ){
30300     if( pFile->lastErrno==ERROR_HANDLE_DISK_FULL ){
30301       return SQLITE_FULL;
30302     }
30303     return SQLITE_IOERR_WRITE;
30304   }
30305   return SQLITE_OK;
30306 }
30307
30308 /*
30309 ** Truncate an open file to a specified size
30310 */
30311 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
30312   winFile *pFile = (winFile*)id;  /* File handle object */
30313   int rc = SQLITE_OK;             /* Return code for this function */
30314
30315   assert( pFile );
30316
30317   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
30318   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
30319
30320   /* If the user has configured a chunk-size for this file, truncate the
30321   ** file so that it consists of an integer number of chunks (i.e. the
30322   ** actual file size after the operation may be larger than the requested
30323   ** size).
30324   */
30325   if( pFile->szChunk ){
30326     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
30327   }
30328
30329   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
30330   if( seekWinFile(pFile, nByte) ){
30331     rc = SQLITE_IOERR_TRUNCATE;
30332   }else if( 0==SetEndOfFile(pFile->h) ){
30333     pFile->lastErrno = GetLastError();
30334     rc = SQLITE_IOERR_TRUNCATE;
30335   }
30336
30337   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
30338   return rc;
30339 }
30340
30341 #ifdef SQLITE_TEST
30342 /*
30343 ** Count the number of fullsyncs and normal syncs.  This is used to test
30344 ** that syncs and fullsyncs are occuring at the right times.
30345 */
30346 SQLITE_API int sqlite3_sync_count = 0;
30347 SQLITE_API int sqlite3_fullsync_count = 0;
30348 #endif
30349
30350 /*
30351 ** Make sure all writes to a particular file are committed to disk.
30352 */
30353 static int winSync(sqlite3_file *id, int flags){
30354 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || defined(SQLITE_DEBUG)
30355   winFile *pFile = (winFile*)id;
30356 #else
30357   UNUSED_PARAMETER(id);
30358 #endif
30359
30360   assert( pFile );
30361   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
30362   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
30363       || (flags&0x0F)==SQLITE_SYNC_FULL
30364   );
30365
30366   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
30367
30368 #ifndef SQLITE_TEST
30369   UNUSED_PARAMETER(flags);
30370 #else
30371   if( flags & SQLITE_SYNC_FULL ){
30372     sqlite3_fullsync_count++;
30373   }
30374   sqlite3_sync_count++;
30375 #endif
30376
30377   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
30378   ** line is to test that doing so does not cause any problems.
30379   */
30380   SimulateDiskfullError( return SQLITE_FULL );
30381   SimulateIOError( return SQLITE_IOERR; );
30382
30383   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
30384   ** no-op
30385   */
30386 #ifdef SQLITE_NO_SYNC
30387   return SQLITE_OK;
30388 #else
30389   if( FlushFileBuffers(pFile->h) ){
30390     return SQLITE_OK;
30391   }else{
30392     pFile->lastErrno = GetLastError();
30393     return SQLITE_IOERR;
30394   }
30395 #endif
30396 }
30397
30398 /*
30399 ** Determine the current size of a file in bytes
30400 */
30401 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
30402   DWORD upperBits;
30403   DWORD lowerBits;
30404   winFile *pFile = (winFile*)id;
30405   DWORD error;
30406
30407   assert( id!=0 );
30408   SimulateIOError(return SQLITE_IOERR_FSTAT);
30409   lowerBits = GetFileSize(pFile->h, &upperBits);
30410   if(   (lowerBits == INVALID_FILE_SIZE)
30411      && ((error = GetLastError()) != NO_ERROR) )
30412   {
30413     pFile->lastErrno = error;
30414     return SQLITE_IOERR_FSTAT;
30415   }
30416   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
30417   return SQLITE_OK;
30418 }
30419
30420 /*
30421 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
30422 */
30423 #ifndef LOCKFILE_FAIL_IMMEDIATELY
30424 # define LOCKFILE_FAIL_IMMEDIATELY 1
30425 #endif
30426
30427 /*
30428 ** Acquire a reader lock.
30429 ** Different API routines are called depending on whether or not this
30430 ** is Win95 or WinNT.
30431 */
30432 static int getReadLock(winFile *pFile){
30433   int res;
30434   if( isNT() ){
30435     OVERLAPPED ovlp;
30436     ovlp.Offset = SHARED_FIRST;
30437     ovlp.OffsetHigh = 0;
30438     ovlp.hEvent = 0;
30439     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
30440                      0, SHARED_SIZE, 0, &ovlp);
30441 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30442 */
30443 #if SQLITE_OS_WINCE==0
30444   }else{
30445     int lk;
30446     sqlite3_randomness(sizeof(lk), &lk);
30447     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
30448     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
30449 #endif
30450   }
30451   if( res == 0 ){
30452     pFile->lastErrno = GetLastError();
30453   }
30454   return res;
30455 }
30456
30457 /*
30458 ** Undo a readlock
30459 */
30460 static int unlockReadLock(winFile *pFile){
30461   int res;
30462   if( isNT() ){
30463     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30464 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
30465 */
30466 #if SQLITE_OS_WINCE==0
30467   }else{
30468     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
30469 #endif
30470   }
30471   if( res == 0 ){
30472     pFile->lastErrno = GetLastError();
30473   }
30474   return res;
30475 }
30476
30477 /*
30478 ** Lock the file with the lock specified by parameter locktype - one
30479 ** of the following:
30480 **
30481 **     (1) SHARED_LOCK
30482 **     (2) RESERVED_LOCK
30483 **     (3) PENDING_LOCK
30484 **     (4) EXCLUSIVE_LOCK
30485 **
30486 ** Sometimes when requesting one lock state, additional lock states
30487 ** are inserted in between.  The locking might fail on one of the later
30488 ** transitions leaving the lock state different from what it started but
30489 ** still short of its goal.  The following chart shows the allowed
30490 ** transitions and the inserted intermediate states:
30491 **
30492 **    UNLOCKED -> SHARED
30493 **    SHARED -> RESERVED
30494 **    SHARED -> (PENDING) -> EXCLUSIVE
30495 **    RESERVED -> (PENDING) -> EXCLUSIVE
30496 **    PENDING -> EXCLUSIVE
30497 **
30498 ** This routine will only increase a lock.  The winUnlock() routine
30499 ** erases all locks at once and returns us immediately to locking level 0.
30500 ** It is not possible to lower the locking level one step at a time.  You
30501 ** must go straight to locking level 0.
30502 */
30503 static int winLock(sqlite3_file *id, int locktype){
30504   int rc = SQLITE_OK;    /* Return code from subroutines */
30505   int res = 1;           /* Result of a windows lock call */
30506   int newLocktype;       /* Set pFile->locktype to this value before exiting */
30507   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
30508   winFile *pFile = (winFile*)id;
30509   DWORD error = NO_ERROR;
30510
30511   assert( id!=0 );
30512   OSTRACE(("LOCK %d %d was %d(%d)\n",
30513            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
30514
30515   /* If there is already a lock of this type or more restrictive on the
30516   ** OsFile, do nothing. Don't use the end_lock: exit path, as
30517   ** sqlite3OsEnterMutex() hasn't been called yet.
30518   */
30519   if( pFile->locktype>=locktype ){
30520     return SQLITE_OK;
30521   }
30522
30523   /* Make sure the locking sequence is correct
30524   */
30525   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
30526   assert( locktype!=PENDING_LOCK );
30527   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
30528
30529   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
30530   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
30531   ** the PENDING_LOCK byte is temporary.
30532   */
30533   newLocktype = pFile->locktype;
30534   if(   (pFile->locktype==NO_LOCK)
30535      || (   (locktype==EXCLUSIVE_LOCK)
30536          && (pFile->locktype==RESERVED_LOCK))
30537   ){
30538     int cnt = 3;
30539     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
30540       /* Try 3 times to get the pending lock.  The pending lock might be
30541       ** held by another reader process who will release it momentarily.
30542       */
30543       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
30544       Sleep(1);
30545     }
30546     gotPendingLock = res;
30547     if( !res ){
30548       error = GetLastError();
30549     }
30550   }
30551
30552   /* Acquire a shared lock
30553   */
30554   if( locktype==SHARED_LOCK && res ){
30555     assert( pFile->locktype==NO_LOCK );
30556     res = getReadLock(pFile);
30557     if( res ){
30558       newLocktype = SHARED_LOCK;
30559     }else{
30560       error = GetLastError();
30561     }
30562   }
30563
30564   /* Acquire a RESERVED lock
30565   */
30566   if( locktype==RESERVED_LOCK && res ){
30567     assert( pFile->locktype==SHARED_LOCK );
30568     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30569     if( res ){
30570       newLocktype = RESERVED_LOCK;
30571     }else{
30572       error = GetLastError();
30573     }
30574   }
30575
30576   /* Acquire a PENDING lock
30577   */
30578   if( locktype==EXCLUSIVE_LOCK && res ){
30579     newLocktype = PENDING_LOCK;
30580     gotPendingLock = 0;
30581   }
30582
30583   /* Acquire an EXCLUSIVE lock
30584   */
30585   if( locktype==EXCLUSIVE_LOCK && res ){
30586     assert( pFile->locktype>=SHARED_LOCK );
30587     res = unlockReadLock(pFile);
30588     OSTRACE(("unreadlock = %d\n", res));
30589     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30590     if( res ){
30591       newLocktype = EXCLUSIVE_LOCK;
30592     }else{
30593       error = GetLastError();
30594       OSTRACE(("error-code = %d\n", error));
30595       getReadLock(pFile);
30596     }
30597   }
30598
30599   /* If we are holding a PENDING lock that ought to be released, then
30600   ** release it now.
30601   */
30602   if( gotPendingLock && locktype==SHARED_LOCK ){
30603     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
30604   }
30605
30606   /* Update the state of the lock has held in the file descriptor then
30607   ** return the appropriate result code.
30608   */
30609   if( res ){
30610     rc = SQLITE_OK;
30611   }else{
30612     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
30613            locktype, newLocktype));
30614     pFile->lastErrno = error;
30615     rc = SQLITE_BUSY;
30616   }
30617   pFile->locktype = (u8)newLocktype;
30618   return rc;
30619 }
30620
30621 /*
30622 ** This routine checks if there is a RESERVED lock held on the specified
30623 ** file by this or any other process. If such a lock is held, return
30624 ** non-zero, otherwise zero.
30625 */
30626 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
30627   int rc;
30628   winFile *pFile = (winFile*)id;
30629
30630   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
30631
30632   assert( id!=0 );
30633   if( pFile->locktype>=RESERVED_LOCK ){
30634     rc = 1;
30635     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
30636   }else{
30637     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30638     if( rc ){
30639       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30640     }
30641     rc = !rc;
30642     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
30643   }
30644   *pResOut = rc;
30645   return SQLITE_OK;
30646 }
30647
30648 /*
30649 ** Lower the locking level on file descriptor id to locktype.  locktype
30650 ** must be either NO_LOCK or SHARED_LOCK.
30651 **
30652 ** If the locking level of the file descriptor is already at or below
30653 ** the requested locking level, this routine is a no-op.
30654 **
30655 ** It is not possible for this routine to fail if the second argument
30656 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
30657 ** might return SQLITE_IOERR;
30658 */
30659 static int winUnlock(sqlite3_file *id, int locktype){
30660   int type;
30661   winFile *pFile = (winFile*)id;
30662   int rc = SQLITE_OK;
30663   assert( pFile!=0 );
30664   assert( locktype<=SHARED_LOCK );
30665   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
30666           pFile->locktype, pFile->sharedLockByte));
30667   type = pFile->locktype;
30668   if( type>=EXCLUSIVE_LOCK ){
30669     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
30670     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
30671       /* This should never happen.  We should always be able to
30672       ** reacquire the read lock */
30673       rc = SQLITE_IOERR_UNLOCK;
30674     }
30675   }
30676   if( type>=RESERVED_LOCK ){
30677     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
30678   }
30679   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
30680     unlockReadLock(pFile);
30681   }
30682   if( type>=PENDING_LOCK ){
30683     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
30684   }
30685   pFile->locktype = (u8)locktype;
30686   return rc;
30687 }
30688
30689 /*
30690 ** Control and query of the open file handle.
30691 */
30692 static int winFileControl(sqlite3_file *id, int op, void *pArg){
30693   switch( op ){
30694     case SQLITE_FCNTL_LOCKSTATE: {
30695       *(int*)pArg = ((winFile*)id)->locktype;
30696       return SQLITE_OK;
30697     }
30698     case SQLITE_LAST_ERRNO: {
30699       *(int*)pArg = (int)((winFile*)id)->lastErrno;
30700       return SQLITE_OK;
30701     }
30702     case SQLITE_FCNTL_CHUNK_SIZE: {
30703       ((winFile*)id)->szChunk = *(int *)pArg;
30704       return SQLITE_OK;
30705     }
30706     case SQLITE_FCNTL_SIZE_HINT: {
30707       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
30708       SimulateIOErrorBenign(1);
30709       winTruncate(id, sz);
30710       SimulateIOErrorBenign(0);
30711       return SQLITE_OK;
30712     }
30713   }
30714   return SQLITE_ERROR;
30715 }
30716
30717 /*
30718 ** Return the sector size in bytes of the underlying block device for
30719 ** the specified file. This is almost always 512 bytes, but may be
30720 ** larger for some devices.
30721 **
30722 ** SQLite code assumes this function cannot fail. It also assumes that
30723 ** if two files are created in the same file-system directory (i.e.
30724 ** a database and its journal file) that the sector size will be the
30725 ** same for both.
30726 */
30727 static int winSectorSize(sqlite3_file *id){
30728   assert( id!=0 );
30729   return (int)(((winFile*)id)->sectorSize);
30730 }
30731
30732 /*
30733 ** Return a vector of device characteristics.
30734 */
30735 static int winDeviceCharacteristics(sqlite3_file *id){
30736   UNUSED_PARAMETER(id);
30737   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
30738 }
30739
30740 #ifndef SQLITE_OMIT_WAL
30741
30742 /* 
30743 ** Windows will only let you create file view mappings
30744 ** on allocation size granularity boundaries.
30745 ** During sqlite3_os_init() we do a GetSystemInfo()
30746 ** to get the granularity size.
30747 */
30748 SYSTEM_INFO winSysInfo;
30749
30750 /*
30751 ** Helper functions to obtain and relinquish the global mutex. The
30752 ** global mutex is used to protect the winLockInfo objects used by 
30753 ** this file, all of which may be shared by multiple threads.
30754 **
30755 ** Function winShmMutexHeld() is used to assert() that the global mutex 
30756 ** is held when required. This function is only used as part of assert() 
30757 ** statements. e.g.
30758 **
30759 **   winShmEnterMutex()
30760 **     assert( winShmMutexHeld() );
30761 **   winShmLeaveMutex()
30762 */
30763 static void winShmEnterMutex(void){
30764   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30765 }
30766 static void winShmLeaveMutex(void){
30767   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30768 }
30769 #ifdef SQLITE_DEBUG
30770 static int winShmMutexHeld(void) {
30771   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
30772 }
30773 #endif
30774
30775 /*
30776 ** Object used to represent a single file opened and mmapped to provide
30777 ** shared memory.  When multiple threads all reference the same
30778 ** log-summary, each thread has its own winFile object, but they all
30779 ** point to a single instance of this object.  In other words, each
30780 ** log-summary is opened only once per process.
30781 **
30782 ** winShmMutexHeld() must be true when creating or destroying
30783 ** this object or while reading or writing the following fields:
30784 **
30785 **      nRef
30786 **      pNext 
30787 **
30788 ** The following fields are read-only after the object is created:
30789 ** 
30790 **      fid
30791 **      zFilename
30792 **
30793 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
30794 ** winShmMutexHeld() is true when reading or writing any other field
30795 ** in this structure.
30796 **
30797 */
30798 struct winShmNode {
30799   sqlite3_mutex *mutex;      /* Mutex to access this object */
30800   char *zFilename;           /* Name of the file */
30801   winFile hFile;             /* File handle from winOpen */
30802
30803   int szRegion;              /* Size of shared-memory regions */
30804   int nRegion;               /* Size of array apRegion */
30805   struct ShmRegion {
30806     HANDLE hMap;             /* File handle from CreateFileMapping */
30807     void *pMap;
30808   } *aRegion;
30809   DWORD lastErrno;           /* The Windows errno from the last I/O error */
30810
30811   int nRef;                  /* Number of winShm objects pointing to this */
30812   winShm *pFirst;            /* All winShm objects pointing to this */
30813   winShmNode *pNext;         /* Next in list of all winShmNode objects */
30814 #ifdef SQLITE_DEBUG
30815   u8 nextShmId;              /* Next available winShm.id value */
30816 #endif
30817 };
30818
30819 /*
30820 ** A global array of all winShmNode objects.
30821 **
30822 ** The winShmMutexHeld() must be true while reading or writing this list.
30823 */
30824 static winShmNode *winShmNodeList = 0;
30825
30826 /*
30827 ** Structure used internally by this VFS to record the state of an
30828 ** open shared memory connection.
30829 **
30830 ** The following fields are initialized when this object is created and
30831 ** are read-only thereafter:
30832 **
30833 **    winShm.pShmNode
30834 **    winShm.id
30835 **
30836 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
30837 ** while accessing any read/write fields.
30838 */
30839 struct winShm {
30840   winShmNode *pShmNode;      /* The underlying winShmNode object */
30841   winShm *pNext;             /* Next winShm with the same winShmNode */
30842   u8 hasMutex;               /* True if holding the winShmNode mutex */
30843   u16 sharedMask;            /* Mask of shared locks held */
30844   u16 exclMask;              /* Mask of exclusive locks held */
30845 #ifdef SQLITE_DEBUG
30846   u8 id;                     /* Id of this connection with its winShmNode */
30847 #endif
30848 };
30849
30850 /*
30851 ** Constants used for locking
30852 */
30853 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
30854 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
30855
30856 /*
30857 ** Apply advisory locks for all n bytes beginning at ofst.
30858 */
30859 #define _SHM_UNLCK  1
30860 #define _SHM_RDLCK  2
30861 #define _SHM_WRLCK  3
30862 static int winShmSystemLock(
30863   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
30864   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
30865   int ofst,             /* Offset to first byte to be locked/unlocked */
30866   int nByte             /* Number of bytes to lock or unlock */
30867 ){
30868   OVERLAPPED ovlp;
30869   DWORD dwFlags;
30870   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
30871
30872   /* Access to the winShmNode object is serialized by the caller */
30873   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
30874
30875   /* Initialize the locking parameters */
30876   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
30877   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
30878
30879   memset(&ovlp, 0, sizeof(OVERLAPPED));
30880   ovlp.Offset = ofst;
30881
30882   /* Release/Acquire the system-level lock */
30883   if( lockType==_SHM_UNLCK ){
30884     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
30885   }else{
30886     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
30887   }
30888   
30889   if( rc!= 0 ){
30890     rc = SQLITE_OK;
30891   }else{
30892     pFile->lastErrno =  GetLastError();
30893     rc = SQLITE_BUSY;
30894   }
30895
30896   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
30897            pFile->hFile.h,
30898            rc==SQLITE_OK ? "ok" : "failed",
30899            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
30900            pFile->lastErrno));
30901
30902   return rc;
30903 }
30904
30905 /* Forward references to VFS methods */
30906 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
30907 static int winDelete(sqlite3_vfs *,const char*,int);
30908
30909 /*
30910 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
30911 **
30912 ** This is not a VFS shared-memory method; it is a utility function called
30913 ** by VFS shared-memory methods.
30914 */
30915 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
30916   winShmNode **pp;
30917   winShmNode *p;
30918   BOOL bRc;
30919   assert( winShmMutexHeld() );
30920   pp = &winShmNodeList;
30921   while( (p = *pp)!=0 ){
30922     if( p->nRef==0 ){
30923       int i;
30924       if( p->mutex ) sqlite3_mutex_free(p->mutex);
30925       for(i=0; i<p->nRegion; i++){
30926         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
30927         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
30928                  (int)GetCurrentProcessId(), i,
30929                  bRc ? "ok" : "failed"));
30930         bRc = CloseHandle(p->aRegion[i].hMap);
30931         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
30932                  (int)GetCurrentProcessId(), i,
30933                  bRc ? "ok" : "failed"));
30934       }
30935       if( p->hFile.h != INVALID_HANDLE_VALUE ){
30936         SimulateIOErrorBenign(1);
30937         winClose((sqlite3_file *)&p->hFile);
30938         SimulateIOErrorBenign(0);
30939       }
30940       if( deleteFlag ){
30941         SimulateIOErrorBenign(1);
30942         winDelete(pVfs, p->zFilename, 0);
30943         SimulateIOErrorBenign(0);
30944       }
30945       *pp = p->pNext;
30946       sqlite3_free(p->aRegion);
30947       sqlite3_free(p);
30948     }else{
30949       pp = &p->pNext;
30950     }
30951   }
30952 }
30953
30954 /*
30955 ** Open the shared-memory area associated with database file pDbFd.
30956 **
30957 ** When opening a new shared-memory file, if no other instances of that
30958 ** file are currently open, in this process or in other processes, then
30959 ** the file must be truncated to zero length or have its header cleared.
30960 */
30961 static int winOpenSharedMemory(winFile *pDbFd){
30962   struct winShm *p;                  /* The connection to be opened */
30963   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
30964   int rc;                            /* Result code */
30965   struct winShmNode *pNew;           /* Newly allocated winShmNode */
30966   int nName;                         /* Size of zName in bytes */
30967
30968   assert( pDbFd->pShm==0 );    /* Not previously opened */
30969
30970   /* Allocate space for the new sqlite3_shm object.  Also speculatively
30971   ** allocate space for a new winShmNode and filename.
30972   */
30973   p = sqlite3_malloc( sizeof(*p) );
30974   if( p==0 ) return SQLITE_NOMEM;
30975   memset(p, 0, sizeof(*p));
30976   nName = sqlite3Strlen30(pDbFd->zPath);
30977   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
30978   if( pNew==0 ){
30979     sqlite3_free(p);
30980     return SQLITE_NOMEM;
30981   }
30982   memset(pNew, 0, sizeof(*pNew));
30983   pNew->zFilename = (char*)&pNew[1];
30984   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
30985
30986   /* Look to see if there is an existing winShmNode that can be used.
30987   ** If no matching winShmNode currently exists, create a new one.
30988   */
30989   winShmEnterMutex();
30990   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
30991     /* TBD need to come up with better match here.  Perhaps
30992     ** use FILE_ID_BOTH_DIR_INFO Structure.
30993     */
30994     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
30995   }
30996   if( pShmNode ){
30997     sqlite3_free(pNew);
30998   }else{
30999     pShmNode = pNew;
31000     pNew = 0;
31001     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
31002     pShmNode->pNext = winShmNodeList;
31003     winShmNodeList = pShmNode;
31004
31005     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
31006     if( pShmNode->mutex==0 ){
31007       rc = SQLITE_NOMEM;
31008       goto shm_open_err;
31009     }
31010
31011     rc = winOpen(pDbFd->pVfs,
31012                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
31013                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
31014                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
31015                  0);
31016     if( SQLITE_OK!=rc ){
31017       rc = SQLITE_CANTOPEN_BKPT;
31018       goto shm_open_err;
31019     }
31020
31021     /* Check to see if another process is holding the dead-man switch.
31022     ** If not, truncate the file to zero length. 
31023     */
31024     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
31025       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
31026       if( rc!=SQLITE_OK ){
31027         rc = SQLITE_IOERR_SHMOPEN;
31028       }
31029     }
31030     if( rc==SQLITE_OK ){
31031       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
31032       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
31033     }
31034     if( rc ) goto shm_open_err;
31035   }
31036
31037   /* Make the new connection a child of the winShmNode */
31038   p->pShmNode = pShmNode;
31039 #ifdef SQLITE_DEBUG
31040   p->id = pShmNode->nextShmId++;
31041 #endif
31042   pShmNode->nRef++;
31043   pDbFd->pShm = p;
31044   winShmLeaveMutex();
31045
31046   /* The reference count on pShmNode has already been incremented under
31047   ** the cover of the winShmEnterMutex() mutex and the pointer from the
31048   ** new (struct winShm) object to the pShmNode has been set. All that is
31049   ** left to do is to link the new object into the linked list starting
31050   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
31051   ** mutex.
31052   */
31053   sqlite3_mutex_enter(pShmNode->mutex);
31054   p->pNext = pShmNode->pFirst;
31055   pShmNode->pFirst = p;
31056   sqlite3_mutex_leave(pShmNode->mutex);
31057   return SQLITE_OK;
31058
31059   /* Jump here on any error */
31060 shm_open_err:
31061   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
31062   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
31063   sqlite3_free(p);
31064   sqlite3_free(pNew);
31065   winShmLeaveMutex();
31066   return rc;
31067 }
31068
31069 /*
31070 ** Close a connection to shared-memory.  Delete the underlying 
31071 ** storage if deleteFlag is true.
31072 */
31073 static int winShmUnmap(
31074   sqlite3_file *fd,          /* Database holding shared memory */
31075   int deleteFlag             /* Delete after closing if true */
31076 ){
31077   winFile *pDbFd;       /* Database holding shared-memory */
31078   winShm *p;            /* The connection to be closed */
31079   winShmNode *pShmNode; /* The underlying shared-memory file */
31080   winShm **pp;          /* For looping over sibling connections */
31081
31082   pDbFd = (winFile*)fd;
31083   p = pDbFd->pShm;
31084   if( p==0 ) return SQLITE_OK;
31085   pShmNode = p->pShmNode;
31086
31087   /* Remove connection p from the set of connections associated
31088   ** with pShmNode */
31089   sqlite3_mutex_enter(pShmNode->mutex);
31090   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
31091   *pp = p->pNext;
31092
31093   /* Free the connection p */
31094   sqlite3_free(p);
31095   pDbFd->pShm = 0;
31096   sqlite3_mutex_leave(pShmNode->mutex);
31097
31098   /* If pShmNode->nRef has reached 0, then close the underlying
31099   ** shared-memory file, too */
31100   winShmEnterMutex();
31101   assert( pShmNode->nRef>0 );
31102   pShmNode->nRef--;
31103   if( pShmNode->nRef==0 ){
31104     winShmPurge(pDbFd->pVfs, deleteFlag);
31105   }
31106   winShmLeaveMutex();
31107
31108   return SQLITE_OK;
31109 }
31110
31111 /*
31112 ** Change the lock state for a shared-memory segment.
31113 */
31114 static int winShmLock(
31115   sqlite3_file *fd,          /* Database file holding the shared memory */
31116   int ofst,                  /* First lock to acquire or release */
31117   int n,                     /* Number of locks to acquire or release */
31118   int flags                  /* What to do with the lock */
31119 ){
31120   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
31121   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
31122   winShm *pX;                           /* For looping over all siblings */
31123   winShmNode *pShmNode = p->pShmNode;
31124   int rc = SQLITE_OK;                   /* Result code */
31125   u16 mask;                             /* Mask of locks to take or release */
31126
31127   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
31128   assert( n>=1 );
31129   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
31130        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
31131        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
31132        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
31133   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
31134
31135   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
31136   assert( n>1 || mask==(1<<ofst) );
31137   sqlite3_mutex_enter(pShmNode->mutex);
31138   if( flags & SQLITE_SHM_UNLOCK ){
31139     u16 allMask = 0; /* Mask of locks held by siblings */
31140
31141     /* See if any siblings hold this same lock */
31142     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31143       if( pX==p ) continue;
31144       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
31145       allMask |= pX->sharedMask;
31146     }
31147
31148     /* Unlock the system-level locks */
31149     if( (mask & allMask)==0 ){
31150       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
31151     }else{
31152       rc = SQLITE_OK;
31153     }
31154
31155     /* Undo the local locks */
31156     if( rc==SQLITE_OK ){
31157       p->exclMask &= ~mask;
31158       p->sharedMask &= ~mask;
31159     } 
31160   }else if( flags & SQLITE_SHM_SHARED ){
31161     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
31162
31163     /* Find out which shared locks are already held by sibling connections.
31164     ** If any sibling already holds an exclusive lock, go ahead and return
31165     ** SQLITE_BUSY.
31166     */
31167     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31168       if( (pX->exclMask & mask)!=0 ){
31169         rc = SQLITE_BUSY;
31170         break;
31171       }
31172       allShared |= pX->sharedMask;
31173     }
31174
31175     /* Get shared locks at the system level, if necessary */
31176     if( rc==SQLITE_OK ){
31177       if( (allShared & mask)==0 ){
31178         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
31179       }else{
31180         rc = SQLITE_OK;
31181       }
31182     }
31183
31184     /* Get the local shared locks */
31185     if( rc==SQLITE_OK ){
31186       p->sharedMask |= mask;
31187     }
31188   }else{
31189     /* Make sure no sibling connections hold locks that will block this
31190     ** lock.  If any do, return SQLITE_BUSY right away.
31191     */
31192     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
31193       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
31194         rc = SQLITE_BUSY;
31195         break;
31196       }
31197     }
31198   
31199     /* Get the exclusive locks at the system level.  Then if successful
31200     ** also mark the local connection as being locked.
31201     */
31202     if( rc==SQLITE_OK ){
31203       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
31204       if( rc==SQLITE_OK ){
31205         assert( (p->sharedMask & mask)==0 );
31206         p->exclMask |= mask;
31207       }
31208     }
31209   }
31210   sqlite3_mutex_leave(pShmNode->mutex);
31211   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
31212            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
31213            rc ? "failed" : "ok"));
31214   return rc;
31215 }
31216
31217 /*
31218 ** Implement a memory barrier or memory fence on shared memory.  
31219 **
31220 ** All loads and stores begun before the barrier must complete before
31221 ** any load or store begun after the barrier.
31222 */
31223 static void winShmBarrier(
31224   sqlite3_file *fd          /* Database holding the shared memory */
31225 ){
31226   UNUSED_PARAMETER(fd);
31227   /* MemoryBarrier(); // does not work -- do not know why not */
31228   winShmEnterMutex();
31229   winShmLeaveMutex();
31230 }
31231
31232 /*
31233 ** This function is called to obtain a pointer to region iRegion of the 
31234 ** shared-memory associated with the database file fd. Shared-memory regions 
31235 ** are numbered starting from zero. Each shared-memory region is szRegion 
31236 ** bytes in size.
31237 **
31238 ** If an error occurs, an error code is returned and *pp is set to NULL.
31239 **
31240 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
31241 ** region has not been allocated (by any client, including one running in a
31242 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
31243 ** isWrite is non-zero and the requested shared-memory region has not yet 
31244 ** been allocated, it is allocated by this function.
31245 **
31246 ** If the shared-memory region has already been allocated or is allocated by
31247 ** this call as described above, then it is mapped into this processes 
31248 ** address space (if it is not already), *pp is set to point to the mapped 
31249 ** memory and SQLITE_OK returned.
31250 */
31251 static int winShmMap(
31252   sqlite3_file *fd,               /* Handle open on database file */
31253   int iRegion,                    /* Region to retrieve */
31254   int szRegion,                   /* Size of regions */
31255   int isWrite,                    /* True to extend file if necessary */
31256   void volatile **pp              /* OUT: Mapped memory */
31257 ){
31258   winFile *pDbFd = (winFile*)fd;
31259   winShm *p = pDbFd->pShm;
31260   winShmNode *pShmNode;
31261   int rc = SQLITE_OK;
31262
31263   if( !p ){
31264     rc = winOpenSharedMemory(pDbFd);
31265     if( rc!=SQLITE_OK ) return rc;
31266     p = pDbFd->pShm;
31267   }
31268   pShmNode = p->pShmNode;
31269
31270   sqlite3_mutex_enter(pShmNode->mutex);
31271   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
31272
31273   if( pShmNode->nRegion<=iRegion ){
31274     struct ShmRegion *apNew;           /* New aRegion[] array */
31275     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
31276     sqlite3_int64 sz;                  /* Current size of wal-index file */
31277
31278     pShmNode->szRegion = szRegion;
31279
31280     /* The requested region is not mapped into this processes address space.
31281     ** Check to see if it has been allocated (i.e. if the wal-index file is
31282     ** large enough to contain the requested region).
31283     */
31284     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
31285     if( rc!=SQLITE_OK ){
31286       rc = SQLITE_IOERR_SHMSIZE;
31287       goto shmpage_out;
31288     }
31289
31290     if( sz<nByte ){
31291       /* The requested memory region does not exist. If isWrite is set to
31292       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
31293       **
31294       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
31295       ** the requested memory region.
31296       */
31297       if( !isWrite ) goto shmpage_out;
31298       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
31299       if( rc!=SQLITE_OK ){
31300         rc = SQLITE_IOERR_SHMSIZE;
31301         goto shmpage_out;
31302       }
31303     }
31304
31305     /* Map the requested memory region into this processes address space. */
31306     apNew = (struct ShmRegion *)sqlite3_realloc(
31307         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
31308     );
31309     if( !apNew ){
31310       rc = SQLITE_IOERR_NOMEM;
31311       goto shmpage_out;
31312     }
31313     pShmNode->aRegion = apNew;
31314
31315     while( pShmNode->nRegion<=iRegion ){
31316       HANDLE hMap;                /* file-mapping handle */
31317       void *pMap = 0;             /* Mapped memory region */
31318      
31319       hMap = CreateFileMapping(pShmNode->hFile.h, 
31320           NULL, PAGE_READWRITE, 0, nByte, NULL
31321       );
31322       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
31323                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
31324                hMap ? "ok" : "failed"));
31325       if( hMap ){
31326         int iOffset = pShmNode->nRegion*szRegion;
31327         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
31328         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
31329             0, iOffset - iOffsetShift, szRegion + iOffsetShift
31330         );
31331         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
31332                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
31333                  pMap ? "ok" : "failed"));
31334       }
31335       if( !pMap ){
31336         pShmNode->lastErrno = GetLastError();
31337         rc = SQLITE_IOERR;
31338         if( hMap ) CloseHandle(hMap);
31339         goto shmpage_out;
31340       }
31341
31342       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
31343       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
31344       pShmNode->nRegion++;
31345     }
31346   }
31347
31348 shmpage_out:
31349   if( pShmNode->nRegion>iRegion ){
31350     int iOffset = iRegion*szRegion;
31351     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
31352     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
31353     *pp = (void *)&p[iOffsetShift];
31354   }else{
31355     *pp = 0;
31356   }
31357   sqlite3_mutex_leave(pShmNode->mutex);
31358   return rc;
31359 }
31360
31361 #else
31362 # define winShmMap     0
31363 # define winShmLock    0
31364 # define winShmBarrier 0
31365 # define winShmUnmap   0
31366 #endif /* #ifndef SQLITE_OMIT_WAL */
31367
31368 /*
31369 ** Here ends the implementation of all sqlite3_file methods.
31370 **
31371 ********************** End sqlite3_file Methods *******************************
31372 ******************************************************************************/
31373
31374 /*
31375 ** This vector defines all the methods that can operate on an
31376 ** sqlite3_file for win32.
31377 */
31378 static const sqlite3_io_methods winIoMethod = {
31379   2,                              /* iVersion */
31380   winClose,                       /* xClose */
31381   winRead,                        /* xRead */
31382   winWrite,                       /* xWrite */
31383   winTruncate,                    /* xTruncate */
31384   winSync,                        /* xSync */
31385   winFileSize,                    /* xFileSize */
31386   winLock,                        /* xLock */
31387   winUnlock,                      /* xUnlock */
31388   winCheckReservedLock,           /* xCheckReservedLock */
31389   winFileControl,                 /* xFileControl */
31390   winSectorSize,                  /* xSectorSize */
31391   winDeviceCharacteristics,       /* xDeviceCharacteristics */
31392   winShmMap,                      /* xShmMap */
31393   winShmLock,                     /* xShmLock */
31394   winShmBarrier,                  /* xShmBarrier */
31395   winShmUnmap                     /* xShmUnmap */
31396 };
31397
31398 /****************************************************************************
31399 **************************** sqlite3_vfs methods ****************************
31400 **
31401 ** This division contains the implementation of methods on the
31402 ** sqlite3_vfs object.
31403 */
31404
31405 /*
31406 ** Convert a UTF-8 filename into whatever form the underlying
31407 ** operating system wants filenames in.  Space to hold the result
31408 ** is obtained from malloc and must be freed by the calling
31409 ** function.
31410 */
31411 static void *convertUtf8Filename(const char *zFilename){
31412   void *zConverted = 0;
31413   if( isNT() ){
31414     zConverted = utf8ToUnicode(zFilename);
31415 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31416 */
31417 #if SQLITE_OS_WINCE==0
31418   }else{
31419     zConverted = utf8ToMbcs(zFilename);
31420 #endif
31421   }
31422   /* caller will handle out of memory */
31423   return zConverted;
31424 }
31425
31426 /*
31427 ** Create a temporary file name in zBuf.  zBuf must be big enough to
31428 ** hold at pVfs->mxPathname characters.
31429 */
31430 static int getTempname(int nBuf, char *zBuf){
31431   static char zChars[] =
31432     "abcdefghijklmnopqrstuvwxyz"
31433     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
31434     "0123456789";
31435   size_t i, j;
31436   char zTempPath[MAX_PATH+1];
31437
31438   /* It's odd to simulate an io-error here, but really this is just
31439   ** using the io-error infrastructure to test that SQLite handles this
31440   ** function failing. 
31441   */
31442   SimulateIOError( return SQLITE_IOERR );
31443
31444   if( sqlite3_temp_directory ){
31445     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
31446   }else if( isNT() ){
31447     char *zMulti;
31448     WCHAR zWidePath[MAX_PATH];
31449     GetTempPathW(MAX_PATH-30, zWidePath);
31450     zMulti = unicodeToUtf8(zWidePath);
31451     if( zMulti ){
31452       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
31453       free(zMulti);
31454     }else{
31455       return SQLITE_NOMEM;
31456     }
31457 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31458 ** Since the ASCII version of these Windows API do not exist for WINCE,
31459 ** it's important to not reference them for WINCE builds.
31460 */
31461 #if SQLITE_OS_WINCE==0
31462   }else{
31463     char *zUtf8;
31464     char zMbcsPath[MAX_PATH];
31465     GetTempPathA(MAX_PATH-30, zMbcsPath);
31466     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
31467     if( zUtf8 ){
31468       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
31469       free(zUtf8);
31470     }else{
31471       return SQLITE_NOMEM;
31472     }
31473 #endif
31474   }
31475
31476   /* Check that the output buffer is large enough for the temporary file 
31477   ** name. If it is not, return SQLITE_ERROR.
31478   */
31479   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
31480     return SQLITE_ERROR;
31481   }
31482
31483   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
31484   zTempPath[i] = 0;
31485
31486   sqlite3_snprintf(nBuf-17, zBuf,
31487                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
31488   j = sqlite3Strlen30(zBuf);
31489   sqlite3_randomness(15, &zBuf[j]);
31490   for(i=0; i<15; i++, j++){
31491     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
31492   }
31493   zBuf[j] = 0;
31494
31495   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
31496   return SQLITE_OK; 
31497 }
31498
31499 /*
31500 ** The return value of getLastErrorMsg
31501 ** is zero if the error message fits in the buffer, or non-zero
31502 ** otherwise (if the message was truncated).
31503 */
31504 static int getLastErrorMsg(int nBuf, char *zBuf){
31505   /* FormatMessage returns 0 on failure.  Otherwise it
31506   ** returns the number of TCHARs written to the output
31507   ** buffer, excluding the terminating null char.
31508   */
31509   DWORD error = GetLastError();
31510   DWORD dwLen = 0;
31511   char *zOut = 0;
31512
31513   if( isNT() ){
31514     WCHAR *zTempWide = NULL;
31515     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
31516                            NULL,
31517                            error,
31518                            0,
31519                            (LPWSTR) &zTempWide,
31520                            0,
31521                            0);
31522     if( dwLen > 0 ){
31523       /* allocate a buffer and convert to UTF8 */
31524       zOut = unicodeToUtf8(zTempWide);
31525       /* free the system buffer allocated by FormatMessage */
31526       LocalFree(zTempWide);
31527     }
31528 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31529 ** Since the ASCII version of these Windows API do not exist for WINCE,
31530 ** it's important to not reference them for WINCE builds.
31531 */
31532 #if SQLITE_OS_WINCE==0
31533   }else{
31534     char *zTemp = NULL;
31535     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
31536                            NULL,
31537                            error,
31538                            0,
31539                            (LPSTR) &zTemp,
31540                            0,
31541                            0);
31542     if( dwLen > 0 ){
31543       /* allocate a buffer and convert to UTF8 */
31544       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31545       /* free the system buffer allocated by FormatMessage */
31546       LocalFree(zTemp);
31547     }
31548 #endif
31549   }
31550   if( 0 == dwLen ){
31551     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
31552   }else{
31553     /* copy a maximum of nBuf chars to output buffer */
31554     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
31555     /* free the UTF8 buffer */
31556     free(zOut);
31557   }
31558   return 0;
31559 }
31560
31561 /*
31562 ** Open a file.
31563 */
31564 static int winOpen(
31565   sqlite3_vfs *pVfs,        /* Not used */
31566   const char *zName,        /* Name of the file (UTF-8) */
31567   sqlite3_file *id,         /* Write the SQLite file handle here */
31568   int flags,                /* Open mode flags */
31569   int *pOutFlags            /* Status return flags */
31570 ){
31571   HANDLE h;
31572   DWORD dwDesiredAccess;
31573   DWORD dwShareMode;
31574   DWORD dwCreationDisposition;
31575   DWORD dwFlagsAndAttributes = 0;
31576 #if SQLITE_OS_WINCE
31577   int isTemp = 0;
31578 #endif
31579   winFile *pFile = (winFile*)id;
31580   void *zConverted;              /* Filename in OS encoding */
31581   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
31582
31583   /* If argument zPath is a NULL pointer, this function is required to open
31584   ** a temporary file. Use this buffer to store the file name in.
31585   */
31586   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
31587
31588   int rc = SQLITE_OK;            /* Function Return Code */
31589 #if !defined(NDEBUG) || SQLITE_OS_WINCE
31590   int eType = flags&0xFFFFFF00;  /* Type of file to open */
31591 #endif
31592
31593   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
31594   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
31595   int isCreate     = (flags & SQLITE_OPEN_CREATE);
31596 #ifndef NDEBUG
31597   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
31598 #endif
31599   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
31600
31601 #ifndef NDEBUG
31602   int isOpenJournal = (isCreate && (
31603         eType==SQLITE_OPEN_MASTER_JOURNAL 
31604      || eType==SQLITE_OPEN_MAIN_JOURNAL 
31605      || eType==SQLITE_OPEN_WAL
31606   ));
31607 #endif
31608
31609   /* Check the following statements are true: 
31610   **
31611   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
31612   **   (b) if CREATE is set, then READWRITE must also be set, and
31613   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
31614   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
31615   */
31616   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
31617   assert(isCreate==0 || isReadWrite);
31618   assert(isExclusive==0 || isCreate);
31619   assert(isDelete==0 || isCreate);
31620
31621   /* The main DB, main journal, WAL file and master journal are never 
31622   ** automatically deleted. Nor are they ever temporary files.  */
31623   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
31624   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
31625   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
31626   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
31627
31628   /* Assert that the upper layer has set one of the "file-type" flags. */
31629   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
31630        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
31631        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
31632        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
31633   );
31634
31635   assert( id!=0 );
31636   UNUSED_PARAMETER(pVfs);
31637
31638   pFile->h = INVALID_HANDLE_VALUE;
31639
31640   /* If the second argument to this function is NULL, generate a 
31641   ** temporary file name to use 
31642   */
31643   if( !zUtf8Name ){
31644     assert(isDelete && !isOpenJournal);
31645     rc = getTempname(MAX_PATH+1, zTmpname);
31646     if( rc!=SQLITE_OK ){
31647       return rc;
31648     }
31649     zUtf8Name = zTmpname;
31650   }
31651
31652   /* Convert the filename to the system encoding. */
31653   zConverted = convertUtf8Filename(zUtf8Name);
31654   if( zConverted==0 ){
31655     return SQLITE_NOMEM;
31656   }
31657
31658   if( isReadWrite ){
31659     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
31660   }else{
31661     dwDesiredAccess = GENERIC_READ;
31662   }
31663
31664   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
31665   ** created. SQLite doesn't use it to indicate "exclusive access" 
31666   ** as it is usually understood.
31667   */
31668   if( isExclusive ){
31669     /* Creates a new file, only if it does not already exist. */
31670     /* If the file exists, it fails. */
31671     dwCreationDisposition = CREATE_NEW;
31672   }else if( isCreate ){
31673     /* Open existing file, or create if it doesn't exist */
31674     dwCreationDisposition = OPEN_ALWAYS;
31675   }else{
31676     /* Opens a file, only if it exists. */
31677     dwCreationDisposition = OPEN_EXISTING;
31678   }
31679
31680   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
31681
31682   if( isDelete ){
31683 #if SQLITE_OS_WINCE
31684     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
31685     isTemp = 1;
31686 #else
31687     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
31688                                | FILE_ATTRIBUTE_HIDDEN
31689                                | FILE_FLAG_DELETE_ON_CLOSE;
31690 #endif
31691   }else{
31692     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
31693   }
31694   /* Reports from the internet are that performance is always
31695   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
31696 #if SQLITE_OS_WINCE
31697   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
31698 #endif
31699
31700   if( isNT() ){
31701     h = CreateFileW((WCHAR*)zConverted,
31702        dwDesiredAccess,
31703        dwShareMode,
31704        NULL,
31705        dwCreationDisposition,
31706        dwFlagsAndAttributes,
31707        NULL
31708     );
31709 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31710 ** Since the ASCII version of these Windows API do not exist for WINCE,
31711 ** it's important to not reference them for WINCE builds.
31712 */
31713 #if SQLITE_OS_WINCE==0
31714   }else{
31715     h = CreateFileA((char*)zConverted,
31716        dwDesiredAccess,
31717        dwShareMode,
31718        NULL,
31719        dwCreationDisposition,
31720        dwFlagsAndAttributes,
31721        NULL
31722     );
31723 #endif
31724   }
31725
31726   OSTRACE(("OPEN %d %s 0x%lx %s\n", 
31727            h, zName, dwDesiredAccess, 
31728            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
31729
31730   if( h==INVALID_HANDLE_VALUE ){
31731     pFile->lastErrno = GetLastError();
31732     free(zConverted);
31733     if( isReadWrite ){
31734       return winOpen(pVfs, zName, id, 
31735              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
31736     }else{
31737       return SQLITE_CANTOPEN_BKPT;
31738     }
31739   }
31740
31741   if( pOutFlags ){
31742     if( isReadWrite ){
31743       *pOutFlags = SQLITE_OPEN_READWRITE;
31744     }else{
31745       *pOutFlags = SQLITE_OPEN_READONLY;
31746     }
31747   }
31748
31749   memset(pFile, 0, sizeof(*pFile));
31750   pFile->pMethod = &winIoMethod;
31751   pFile->h = h;
31752   pFile->lastErrno = NO_ERROR;
31753   pFile->pVfs = pVfs;
31754   pFile->pShm = 0;
31755   pFile->zPath = zName;
31756   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
31757
31758 #if SQLITE_OS_WINCE
31759   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
31760        && !winceCreateLock(zName, pFile)
31761   ){
31762     CloseHandle(h);
31763     free(zConverted);
31764     return SQLITE_CANTOPEN_BKPT;
31765   }
31766   if( isTemp ){
31767     pFile->zDeleteOnClose = zConverted;
31768   }else
31769 #endif
31770   {
31771     free(zConverted);
31772   }
31773
31774   OpenCounter(+1);
31775   return rc;
31776 }
31777
31778 /*
31779 ** Delete the named file.
31780 **
31781 ** Note that windows does not allow a file to be deleted if some other
31782 ** process has it open.  Sometimes a virus scanner or indexing program
31783 ** will open a journal file shortly after it is created in order to do
31784 ** whatever it does.  While this other process is holding the
31785 ** file open, we will be unable to delete it.  To work around this
31786 ** problem, we delay 100 milliseconds and try to delete again.  Up
31787 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
31788 ** up and returning an error.
31789 */
31790 #define MX_DELETION_ATTEMPTS 5
31791 static int winDelete(
31792   sqlite3_vfs *pVfs,          /* Not used on win32 */
31793   const char *zFilename,      /* Name of file to delete */
31794   int syncDir                 /* Not used on win32 */
31795 ){
31796   int cnt = 0;
31797   DWORD rc;
31798   DWORD error = 0;
31799   void *zConverted;
31800   UNUSED_PARAMETER(pVfs);
31801   UNUSED_PARAMETER(syncDir);
31802
31803   SimulateIOError(return SQLITE_IOERR_DELETE);
31804   zConverted = convertUtf8Filename(zFilename);
31805   if( zConverted==0 ){
31806     return SQLITE_NOMEM;
31807   }
31808   if( isNT() ){
31809     do{
31810       DeleteFileW(zConverted);
31811     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
31812                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31813            && (++cnt < MX_DELETION_ATTEMPTS)
31814            && (Sleep(100), 1) );
31815 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31816 ** Since the ASCII version of these Windows API do not exist for WINCE,
31817 ** it's important to not reference them for WINCE builds.
31818 */
31819 #if SQLITE_OS_WINCE==0
31820   }else{
31821     do{
31822       DeleteFileA(zConverted);
31823     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
31824                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
31825            && (++cnt < MX_DELETION_ATTEMPTS)
31826            && (Sleep(100), 1) );
31827 #endif
31828   }
31829   free(zConverted);
31830   OSTRACE(("DELETE \"%s\" %s\n", zFilename,
31831        ( (rc==INVALID_FILE_ATTRIBUTES) && (error==ERROR_FILE_NOT_FOUND)) ?
31832          "ok" : "failed" ));
31833  
31834   return (   (rc == INVALID_FILE_ATTRIBUTES) 
31835           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
31836 }
31837
31838 /*
31839 ** Check the existance and status of a file.
31840 */
31841 static int winAccess(
31842   sqlite3_vfs *pVfs,         /* Not used on win32 */
31843   const char *zFilename,     /* Name of file to check */
31844   int flags,                 /* Type of test to make on this file */
31845   int *pResOut               /* OUT: Result */
31846 ){
31847   DWORD attr;
31848   int rc = 0;
31849   void *zConverted;
31850   UNUSED_PARAMETER(pVfs);
31851
31852   SimulateIOError( return SQLITE_IOERR_ACCESS; );
31853   zConverted = convertUtf8Filename(zFilename);
31854   if( zConverted==0 ){
31855     return SQLITE_NOMEM;
31856   }
31857   if( isNT() ){
31858     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
31859     memset(&sAttrData, 0, sizeof(sAttrData));
31860     if( GetFileAttributesExW((WCHAR*)zConverted,
31861                              GetFileExInfoStandard, 
31862                              &sAttrData) ){
31863       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
31864       ** as if it does not exist.
31865       */
31866       if(    flags==SQLITE_ACCESS_EXISTS
31867           && sAttrData.nFileSizeHigh==0 
31868           && sAttrData.nFileSizeLow==0 ){
31869         attr = INVALID_FILE_ATTRIBUTES;
31870       }else{
31871         attr = sAttrData.dwFileAttributes;
31872       }
31873     }else{
31874       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
31875         free(zConverted);
31876         return SQLITE_IOERR_ACCESS;
31877       }else{
31878         attr = INVALID_FILE_ATTRIBUTES;
31879       }
31880     }
31881 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31882 ** Since the ASCII version of these Windows API do not exist for WINCE,
31883 ** it's important to not reference them for WINCE builds.
31884 */
31885 #if SQLITE_OS_WINCE==0
31886   }else{
31887     attr = GetFileAttributesA((char*)zConverted);
31888 #endif
31889   }
31890   free(zConverted);
31891   switch( flags ){
31892     case SQLITE_ACCESS_READ:
31893     case SQLITE_ACCESS_EXISTS:
31894       rc = attr!=INVALID_FILE_ATTRIBUTES;
31895       break;
31896     case SQLITE_ACCESS_READWRITE:
31897       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
31898       break;
31899     default:
31900       assert(!"Invalid flags argument");
31901   }
31902   *pResOut = rc;
31903   return SQLITE_OK;
31904 }
31905
31906
31907 /*
31908 ** Turn a relative pathname into a full pathname.  Write the full
31909 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
31910 ** bytes in size.
31911 */
31912 static int winFullPathname(
31913   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
31914   const char *zRelative,        /* Possibly relative input path */
31915   int nFull,                    /* Size of output buffer in bytes */
31916   char *zFull                   /* Output buffer */
31917 ){
31918   
31919 #if defined(__CYGWIN__)
31920   SimulateIOError( return SQLITE_ERROR );
31921   UNUSED_PARAMETER(nFull);
31922   cygwin_conv_to_full_win32_path(zRelative, zFull);
31923   return SQLITE_OK;
31924 #endif
31925
31926 #if SQLITE_OS_WINCE
31927   SimulateIOError( return SQLITE_ERROR );
31928   UNUSED_PARAMETER(nFull);
31929   /* WinCE has no concept of a relative pathname, or so I am told. */
31930   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
31931   return SQLITE_OK;
31932 #endif
31933
31934 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
31935   int nByte;
31936   void *zConverted;
31937   char *zOut;
31938
31939   /* It's odd to simulate an io-error here, but really this is just
31940   ** using the io-error infrastructure to test that SQLite handles this
31941   ** function failing. This function could fail if, for example, the
31942   ** current working directory has been unlinked.
31943   */
31944   SimulateIOError( return SQLITE_ERROR );
31945   UNUSED_PARAMETER(nFull);
31946   zConverted = convertUtf8Filename(zRelative);
31947   if( isNT() ){
31948     WCHAR *zTemp;
31949     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
31950     zTemp = malloc( nByte*sizeof(zTemp[0]) );
31951     if( zTemp==0 ){
31952       free(zConverted);
31953       return SQLITE_NOMEM;
31954     }
31955     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
31956     free(zConverted);
31957     zOut = unicodeToUtf8(zTemp);
31958     free(zTemp);
31959 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
31960 ** Since the ASCII version of these Windows API do not exist for WINCE,
31961 ** it's important to not reference them for WINCE builds.
31962 */
31963 #if SQLITE_OS_WINCE==0
31964   }else{
31965     char *zTemp;
31966     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
31967     zTemp = malloc( nByte*sizeof(zTemp[0]) );
31968     if( zTemp==0 ){
31969       free(zConverted);
31970       return SQLITE_NOMEM;
31971     }
31972     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
31973     free(zConverted);
31974     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
31975     free(zTemp);
31976 #endif
31977   }
31978   if( zOut ){
31979     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
31980     free(zOut);
31981     return SQLITE_OK;
31982   }else{
31983     return SQLITE_NOMEM;
31984   }
31985 #endif
31986 }
31987
31988 /*
31989 ** Get the sector size of the device used to store
31990 ** file.
31991 */
31992 static int getSectorSize(
31993     sqlite3_vfs *pVfs,
31994     const char *zRelative     /* UTF-8 file name */
31995 ){
31996   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
31997   /* GetDiskFreeSpace is not supported under WINCE */
31998 #if SQLITE_OS_WINCE
31999   UNUSED_PARAMETER(pVfs);
32000   UNUSED_PARAMETER(zRelative);
32001 #else
32002   char zFullpath[MAX_PATH+1];
32003   int rc;
32004   DWORD dwRet = 0;
32005   DWORD dwDummy;
32006
32007   /*
32008   ** We need to get the full path name of the file
32009   ** to get the drive letter to look up the sector
32010   ** size.
32011   */
32012   SimulateIOErrorBenign(1);
32013   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
32014   SimulateIOErrorBenign(0);
32015   if( rc == SQLITE_OK )
32016   {
32017     void *zConverted = convertUtf8Filename(zFullpath);
32018     if( zConverted ){
32019       if( isNT() ){
32020         /* trim path to just drive reference */
32021         WCHAR *p = zConverted;
32022         for(;*p;p++){
32023           if( *p == '\\' ){
32024             *p = '\0';
32025             break;
32026           }
32027         }
32028         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
32029                                   &dwDummy,
32030                                   &bytesPerSector,
32031                                   &dwDummy,
32032                                   &dwDummy);
32033       }else{
32034         /* trim path to just drive reference */
32035         char *p = (char *)zConverted;
32036         for(;*p;p++){
32037           if( *p == '\\' ){
32038             *p = '\0';
32039             break;
32040           }
32041         }
32042         dwRet = GetDiskFreeSpaceA((char*)zConverted,
32043                                   &dwDummy,
32044                                   &bytesPerSector,
32045                                   &dwDummy,
32046                                   &dwDummy);
32047       }
32048       free(zConverted);
32049     }
32050     if( !dwRet ){
32051       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
32052     }
32053   }
32054 #endif
32055   return (int) bytesPerSector; 
32056 }
32057
32058 #ifndef SQLITE_OMIT_LOAD_EXTENSION
32059 /*
32060 ** Interfaces for opening a shared library, finding entry points
32061 ** within the shared library, and closing the shared library.
32062 */
32063 /*
32064 ** Interfaces for opening a shared library, finding entry points
32065 ** within the shared library, and closing the shared library.
32066 */
32067 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
32068   HANDLE h;
32069   void *zConverted = convertUtf8Filename(zFilename);
32070   UNUSED_PARAMETER(pVfs);
32071   if( zConverted==0 ){
32072     return 0;
32073   }
32074   if( isNT() ){
32075     h = LoadLibraryW((WCHAR*)zConverted);
32076 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
32077 ** Since the ASCII version of these Windows API do not exist for WINCE,
32078 ** it's important to not reference them for WINCE builds.
32079 */
32080 #if SQLITE_OS_WINCE==0
32081   }else{
32082     h = LoadLibraryA((char*)zConverted);
32083 #endif
32084   }
32085   free(zConverted);
32086   return (void*)h;
32087 }
32088 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
32089   UNUSED_PARAMETER(pVfs);
32090   getLastErrorMsg(nBuf, zBufOut);
32091 }
32092 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
32093   UNUSED_PARAMETER(pVfs);
32094 #if SQLITE_OS_WINCE
32095   /* The GetProcAddressA() routine is only available on wince. */
32096   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
32097 #else
32098   /* All other windows platforms expect GetProcAddress() to take
32099   ** an Ansi string regardless of the _UNICODE setting */
32100   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
32101 #endif
32102 }
32103 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
32104   UNUSED_PARAMETER(pVfs);
32105   FreeLibrary((HANDLE)pHandle);
32106 }
32107 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
32108   #define winDlOpen  0
32109   #define winDlError 0
32110   #define winDlSym   0
32111   #define winDlClose 0
32112 #endif
32113
32114
32115 /*
32116 ** Write up to nBuf bytes of randomness into zBuf.
32117 */
32118 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
32119   int n = 0;
32120   UNUSED_PARAMETER(pVfs);
32121 #if defined(SQLITE_TEST)
32122   n = nBuf;
32123   memset(zBuf, 0, nBuf);
32124 #else
32125   if( sizeof(SYSTEMTIME)<=nBuf-n ){
32126     SYSTEMTIME x;
32127     GetSystemTime(&x);
32128     memcpy(&zBuf[n], &x, sizeof(x));
32129     n += sizeof(x);
32130   }
32131   if( sizeof(DWORD)<=nBuf-n ){
32132     DWORD pid = GetCurrentProcessId();
32133     memcpy(&zBuf[n], &pid, sizeof(pid));
32134     n += sizeof(pid);
32135   }
32136   if( sizeof(DWORD)<=nBuf-n ){
32137     DWORD cnt = GetTickCount();
32138     memcpy(&zBuf[n], &cnt, sizeof(cnt));
32139     n += sizeof(cnt);
32140   }
32141   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
32142     LARGE_INTEGER i;
32143     QueryPerformanceCounter(&i);
32144     memcpy(&zBuf[n], &i, sizeof(i));
32145     n += sizeof(i);
32146   }
32147 #endif
32148   return n;
32149 }
32150
32151
32152 /*
32153 ** Sleep for a little while.  Return the amount of time slept.
32154 */
32155 static int winSleep(sqlite3_vfs *pVfs, int microsec){
32156   Sleep((microsec+999)/1000);
32157   UNUSED_PARAMETER(pVfs);
32158   return ((microsec+999)/1000)*1000;
32159 }
32160
32161 /*
32162 ** The following variable, if set to a non-zero value, is interpreted as
32163 ** the number of seconds since 1970 and is used to set the result of
32164 ** sqlite3OsCurrentTime() during testing.
32165 */
32166 #ifdef SQLITE_TEST
32167 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
32168 #endif
32169
32170 /*
32171 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
32172 ** the current time and date as a Julian Day number times 86_400_000.  In
32173 ** other words, write into *piNow the number of milliseconds since the Julian
32174 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
32175 ** proleptic Gregorian calendar.
32176 **
32177 ** On success, return 0.  Return 1 if the time and date cannot be found.
32178 */
32179 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
32180   /* FILETIME structure is a 64-bit value representing the number of 
32181      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
32182   */
32183   FILETIME ft;
32184   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
32185 #ifdef SQLITE_TEST
32186   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
32187 #endif
32188   /* 2^32 - to avoid use of LL and warnings in gcc */
32189   static const sqlite3_int64 max32BitValue = 
32190       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
32191
32192 #if SQLITE_OS_WINCE
32193   SYSTEMTIME time;
32194   GetSystemTime(&time);
32195   /* if SystemTimeToFileTime() fails, it returns zero. */
32196   if (!SystemTimeToFileTime(&time,&ft)){
32197     return 1;
32198   }
32199 #else
32200   GetSystemTimeAsFileTime( &ft );
32201 #endif
32202
32203   *piNow = winFiletimeEpoch +
32204             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
32205                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
32206
32207 #ifdef SQLITE_TEST
32208   if( sqlite3_current_time ){
32209     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
32210   }
32211 #endif
32212   UNUSED_PARAMETER(pVfs);
32213   return 0;
32214 }
32215
32216 /*
32217 ** Find the current time (in Universal Coordinated Time).  Write the
32218 ** current time and date as a Julian Day number into *prNow and
32219 ** return 0.  Return 1 if the time and date cannot be found.
32220 */
32221 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
32222   int rc;
32223   sqlite3_int64 i;
32224   rc = winCurrentTimeInt64(pVfs, &i);
32225   if( !rc ){
32226     *prNow = i/86400000.0;
32227   }
32228   return rc;
32229 }
32230
32231 /*
32232 ** The idea is that this function works like a combination of
32233 ** GetLastError() and FormatMessage() on windows (or errno and
32234 ** strerror_r() on unix). After an error is returned by an OS
32235 ** function, SQLite calls this function with zBuf pointing to
32236 ** a buffer of nBuf bytes. The OS layer should populate the
32237 ** buffer with a nul-terminated UTF-8 encoded error message
32238 ** describing the last IO error to have occurred within the calling
32239 ** thread.
32240 **
32241 ** If the error message is too large for the supplied buffer,
32242 ** it should be truncated. The return value of xGetLastError
32243 ** is zero if the error message fits in the buffer, or non-zero
32244 ** otherwise (if the message was truncated). If non-zero is returned,
32245 ** then it is not necessary to include the nul-terminator character
32246 ** in the output buffer.
32247 **
32248 ** Not supplying an error message will have no adverse effect
32249 ** on SQLite. It is fine to have an implementation that never
32250 ** returns an error message:
32251 **
32252 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
32253 **     assert(zBuf[0]=='\0');
32254 **     return 0;
32255 **   }
32256 **
32257 ** However if an error message is supplied, it will be incorporated
32258 ** by sqlite into the error message available to the user using
32259 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
32260 */
32261 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
32262   UNUSED_PARAMETER(pVfs);
32263   return getLastErrorMsg(nBuf, zBuf);
32264 }
32265
32266
32267
32268 /*
32269 ** Initialize and deinitialize the operating system interface.
32270 */
32271 SQLITE_API int sqlite3_os_init(void){
32272   static sqlite3_vfs winVfs = {
32273     2,                   /* iVersion */
32274     sizeof(winFile),     /* szOsFile */
32275     MAX_PATH,            /* mxPathname */
32276     0,                   /* pNext */
32277     "win32",             /* zName */
32278     0,                   /* pAppData */
32279     winOpen,             /* xOpen */
32280     winDelete,           /* xDelete */
32281     winAccess,           /* xAccess */
32282     winFullPathname,     /* xFullPathname */
32283     winDlOpen,           /* xDlOpen */
32284     winDlError,          /* xDlError */
32285     winDlSym,            /* xDlSym */
32286     winDlClose,          /* xDlClose */
32287     winRandomness,       /* xRandomness */
32288     winSleep,            /* xSleep */
32289     winCurrentTime,      /* xCurrentTime */
32290     winGetLastError,     /* xGetLastError */
32291     winCurrentTimeInt64, /* xCurrentTimeInt64 */
32292   };
32293
32294 #ifndef SQLITE_OMIT_WAL
32295   /* get memory map allocation granularity */
32296   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
32297   GetSystemInfo(&winSysInfo);
32298   assert(winSysInfo.dwAllocationGranularity > 0);
32299 #endif
32300
32301   sqlite3_vfs_register(&winVfs, 1);
32302   return SQLITE_OK; 
32303 }
32304 SQLITE_API int sqlite3_os_end(void){ 
32305   return SQLITE_OK;
32306 }
32307
32308 #endif /* SQLITE_OS_WIN */
32309
32310 /************** End of os_win.c **********************************************/
32311 /************** Begin file bitvec.c ******************************************/
32312 /*
32313 ** 2008 February 16
32314 **
32315 ** The author disclaims copyright to this source code.  In place of
32316 ** a legal notice, here is a blessing:
32317 **
32318 **    May you do good and not evil.
32319 **    May you find forgiveness for yourself and forgive others.
32320 **    May you share freely, never taking more than you give.
32321 **
32322 *************************************************************************
32323 ** This file implements an object that represents a fixed-length
32324 ** bitmap.  Bits are numbered starting with 1.
32325 **
32326 ** A bitmap is used to record which pages of a database file have been
32327 ** journalled during a transaction, or which pages have the "dont-write"
32328 ** property.  Usually only a few pages are meet either condition.
32329 ** So the bitmap is usually sparse and has low cardinality.
32330 ** But sometimes (for example when during a DROP of a large table) most
32331 ** or all of the pages in a database can get journalled.  In those cases, 
32332 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
32333 ** to handle both cases well.
32334 **
32335 ** The size of the bitmap is fixed when the object is created.
32336 **
32337 ** All bits are clear when the bitmap is created.  Individual bits
32338 ** may be set or cleared one at a time.
32339 **
32340 ** Test operations are about 100 times more common that set operations.
32341 ** Clear operations are exceedingly rare.  There are usually between
32342 ** 5 and 500 set operations per Bitvec object, though the number of sets can
32343 ** sometimes grow into tens of thousands or larger.  The size of the
32344 ** Bitvec object is the number of pages in the database file at the
32345 ** start of a transaction, and is thus usually less than a few thousand,
32346 ** but can be as large as 2 billion for a really big database.
32347 */
32348
32349 /* Size of the Bitvec structure in bytes. */
32350 #define BITVEC_SZ        512
32351
32352 /* Round the union size down to the nearest pointer boundary, since that's how 
32353 ** it will be aligned within the Bitvec struct. */
32354 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
32355
32356 /* Type of the array "element" for the bitmap representation. 
32357 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
32358 ** Setting this to the "natural word" size of your CPU may improve
32359 ** performance. */
32360 #define BITVEC_TELEM     u8
32361 /* Size, in bits, of the bitmap element. */
32362 #define BITVEC_SZELEM    8
32363 /* Number of elements in a bitmap array. */
32364 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
32365 /* Number of bits in the bitmap array. */
32366 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
32367
32368 /* Number of u32 values in hash table. */
32369 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
32370 /* Maximum number of entries in hash table before 
32371 ** sub-dividing and re-hashing. */
32372 #define BITVEC_MXHASH    (BITVEC_NINT/2)
32373 /* Hashing function for the aHash representation.
32374 ** Empirical testing showed that the *37 multiplier 
32375 ** (an arbitrary prime)in the hash function provided 
32376 ** no fewer collisions than the no-op *1. */
32377 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
32378
32379 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
32380
32381
32382 /*
32383 ** A bitmap is an instance of the following structure.
32384 **
32385 ** This bitmap records the existance of zero or more bits
32386 ** with values between 1 and iSize, inclusive.
32387 **
32388 ** There are three possible representations of the bitmap.
32389 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
32390 ** bitmap.  The least significant bit is bit 1.
32391 **
32392 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
32393 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
32394 **
32395 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
32396 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
32397 ** handles up to iDivisor separate values of i.  apSub[0] holds
32398 ** values between 1 and iDivisor.  apSub[1] holds values between
32399 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
32400 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
32401 ** to hold deal with values between 1 and iDivisor.
32402 */
32403 struct Bitvec {
32404   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
32405   u32 nSet;       /* Number of bits that are set - only valid for aHash
32406                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
32407                   ** this would be 125. */
32408   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
32409                   /* Should >=0 for apSub element. */
32410                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
32411                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
32412   union {
32413     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
32414     u32 aHash[BITVEC_NINT];      /* Hash table representation */
32415     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
32416   } u;
32417 };
32418
32419 /*
32420 ** Create a new bitmap object able to handle bits between 0 and iSize,
32421 ** inclusive.  Return a pointer to the new object.  Return NULL if 
32422 ** malloc fails.
32423 */
32424 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
32425   Bitvec *p;
32426   assert( sizeof(*p)==BITVEC_SZ );
32427   p = sqlite3MallocZero( sizeof(*p) );
32428   if( p ){
32429     p->iSize = iSize;
32430   }
32431   return p;
32432 }
32433
32434 /*
32435 ** Check to see if the i-th bit is set.  Return true or false.
32436 ** If p is NULL (if the bitmap has not been created) or if
32437 ** i is out of range, then return false.
32438 */
32439 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
32440   if( p==0 ) return 0;
32441   if( i>p->iSize || i==0 ) return 0;
32442   i--;
32443   while( p->iDivisor ){
32444     u32 bin = i/p->iDivisor;
32445     i = i%p->iDivisor;
32446     p = p->u.apSub[bin];
32447     if (!p) {
32448       return 0;
32449     }
32450   }
32451   if( p->iSize<=BITVEC_NBIT ){
32452     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
32453   } else{
32454     u32 h = BITVEC_HASH(i++);
32455     while( p->u.aHash[h] ){
32456       if( p->u.aHash[h]==i ) return 1;
32457       h = (h+1) % BITVEC_NINT;
32458     }
32459     return 0;
32460   }
32461 }
32462
32463 /*
32464 ** Set the i-th bit.  Return 0 on success and an error code if
32465 ** anything goes wrong.
32466 **
32467 ** This routine might cause sub-bitmaps to be allocated.  Failing
32468 ** to get the memory needed to hold the sub-bitmap is the only
32469 ** that can go wrong with an insert, assuming p and i are valid.
32470 **
32471 ** The calling function must ensure that p is a valid Bitvec object
32472 ** and that the value for "i" is within range of the Bitvec object.
32473 ** Otherwise the behavior is undefined.
32474 */
32475 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
32476   u32 h;
32477   if( p==0 ) return SQLITE_OK;
32478   assert( i>0 );
32479   assert( i<=p->iSize );
32480   i--;
32481   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
32482     u32 bin = i/p->iDivisor;
32483     i = i%p->iDivisor;
32484     if( p->u.apSub[bin]==0 ){
32485       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
32486       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
32487     }
32488     p = p->u.apSub[bin];
32489   }
32490   if( p->iSize<=BITVEC_NBIT ){
32491     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
32492     return SQLITE_OK;
32493   }
32494   h = BITVEC_HASH(i++);
32495   /* if there wasn't a hash collision, and this doesn't */
32496   /* completely fill the hash, then just add it without */
32497   /* worring about sub-dividing and re-hashing. */
32498   if( !p->u.aHash[h] ){
32499     if (p->nSet<(BITVEC_NINT-1)) {
32500       goto bitvec_set_end;
32501     } else {
32502       goto bitvec_set_rehash;
32503     }
32504   }
32505   /* there was a collision, check to see if it's already */
32506   /* in hash, if not, try to find a spot for it */
32507   do {
32508     if( p->u.aHash[h]==i ) return SQLITE_OK;
32509     h++;
32510     if( h>=BITVEC_NINT ) h = 0;
32511   } while( p->u.aHash[h] );
32512   /* we didn't find it in the hash.  h points to the first */
32513   /* available free spot. check to see if this is going to */
32514   /* make our hash too "full".  */
32515 bitvec_set_rehash:
32516   if( p->nSet>=BITVEC_MXHASH ){
32517     unsigned int j;
32518     int rc;
32519     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
32520     if( aiValues==0 ){
32521       return SQLITE_NOMEM;
32522     }else{
32523       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
32524       memset(p->u.apSub, 0, sizeof(p->u.apSub));
32525       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
32526       rc = sqlite3BitvecSet(p, i);
32527       for(j=0; j<BITVEC_NINT; j++){
32528         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
32529       }
32530       sqlite3StackFree(0, aiValues);
32531       return rc;
32532     }
32533   }
32534 bitvec_set_end:
32535   p->nSet++;
32536   p->u.aHash[h] = i;
32537   return SQLITE_OK;
32538 }
32539
32540 /*
32541 ** Clear the i-th bit.
32542 **
32543 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
32544 ** that BitvecClear can use to rebuilt its hash table.
32545 */
32546 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
32547   if( p==0 ) return;
32548   assert( i>0 );
32549   i--;
32550   while( p->iDivisor ){
32551     u32 bin = i/p->iDivisor;
32552     i = i%p->iDivisor;
32553     p = p->u.apSub[bin];
32554     if (!p) {
32555       return;
32556     }
32557   }
32558   if( p->iSize<=BITVEC_NBIT ){
32559     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
32560   }else{
32561     unsigned int j;
32562     u32 *aiValues = pBuf;
32563     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
32564     memset(p->u.aHash, 0, sizeof(p->u.aHash));
32565     p->nSet = 0;
32566     for(j=0; j<BITVEC_NINT; j++){
32567       if( aiValues[j] && aiValues[j]!=(i+1) ){
32568         u32 h = BITVEC_HASH(aiValues[j]-1);
32569         p->nSet++;
32570         while( p->u.aHash[h] ){
32571           h++;
32572           if( h>=BITVEC_NINT ) h = 0;
32573         }
32574         p->u.aHash[h] = aiValues[j];
32575       }
32576     }
32577   }
32578 }
32579
32580 /*
32581 ** Destroy a bitmap object.  Reclaim all memory used.
32582 */
32583 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
32584   if( p==0 ) return;
32585   if( p->iDivisor ){
32586     unsigned int i;
32587     for(i=0; i<BITVEC_NPTR; i++){
32588       sqlite3BitvecDestroy(p->u.apSub[i]);
32589     }
32590   }
32591   sqlite3_free(p);
32592 }
32593
32594 /*
32595 ** Return the value of the iSize parameter specified when Bitvec *p
32596 ** was created.
32597 */
32598 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
32599   return p->iSize;
32600 }
32601
32602 #ifndef SQLITE_OMIT_BUILTIN_TEST
32603 /*
32604 ** Let V[] be an array of unsigned characters sufficient to hold
32605 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
32606 ** Then the following macros can be used to set, clear, or test
32607 ** individual bits within V.
32608 */
32609 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
32610 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
32611 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
32612
32613 /*
32614 ** This routine runs an extensive test of the Bitvec code.
32615 **
32616 ** The input is an array of integers that acts as a program
32617 ** to test the Bitvec.  The integers are opcodes followed
32618 ** by 0, 1, or 3 operands, depending on the opcode.  Another
32619 ** opcode follows immediately after the last operand.
32620 **
32621 ** There are 6 opcodes numbered from 0 through 5.  0 is the
32622 ** "halt" opcode and causes the test to end.
32623 **
32624 **    0          Halt and return the number of errors
32625 **    1 N S X    Set N bits beginning with S and incrementing by X
32626 **    2 N S X    Clear N bits beginning with S and incrementing by X
32627 **    3 N        Set N randomly chosen bits
32628 **    4 N        Clear N randomly chosen bits
32629 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
32630 **
32631 ** The opcodes 1 through 4 perform set and clear operations are performed
32632 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
32633 ** Opcode 5 works on the linear array only, not on the Bitvec.
32634 ** Opcode 5 is used to deliberately induce a fault in order to
32635 ** confirm that error detection works.
32636 **
32637 ** At the conclusion of the test the linear array is compared
32638 ** against the Bitvec object.  If there are any differences,
32639 ** an error is returned.  If they are the same, zero is returned.
32640 **
32641 ** If a memory allocation error occurs, return -1.
32642 */
32643 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
32644   Bitvec *pBitvec = 0;
32645   unsigned char *pV = 0;
32646   int rc = -1;
32647   int i, nx, pc, op;
32648   void *pTmpSpace;
32649
32650   /* Allocate the Bitvec to be tested and a linear array of
32651   ** bits to act as the reference */
32652   pBitvec = sqlite3BitvecCreate( sz );
32653   pV = sqlite3_malloc( (sz+7)/8 + 1 );
32654   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
32655   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
32656   memset(pV, 0, (sz+7)/8 + 1);
32657
32658   /* NULL pBitvec tests */
32659   sqlite3BitvecSet(0, 1);
32660   sqlite3BitvecClear(0, 1, pTmpSpace);
32661
32662   /* Run the program */
32663   pc = 0;
32664   while( (op = aOp[pc])!=0 ){
32665     switch( op ){
32666       case 1:
32667       case 2:
32668       case 5: {
32669         nx = 4;
32670         i = aOp[pc+2] - 1;
32671         aOp[pc+2] += aOp[pc+3];
32672         break;
32673       }
32674       case 3:
32675       case 4: 
32676       default: {
32677         nx = 2;
32678         sqlite3_randomness(sizeof(i), &i);
32679         break;
32680       }
32681     }
32682     if( (--aOp[pc+1]) > 0 ) nx = 0;
32683     pc += nx;
32684     i = (i & 0x7fffffff)%sz;
32685     if( (op & 1)!=0 ){
32686       SETBIT(pV, (i+1));
32687       if( op!=5 ){
32688         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
32689       }
32690     }else{
32691       CLEARBIT(pV, (i+1));
32692       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
32693     }
32694   }
32695
32696   /* Test to make sure the linear array exactly matches the
32697   ** Bitvec object.  Start with the assumption that they do
32698   ** match (rc==0).  Change rc to non-zero if a discrepancy
32699   ** is found.
32700   */
32701   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
32702           + sqlite3BitvecTest(pBitvec, 0)
32703           + (sqlite3BitvecSize(pBitvec) - sz);
32704   for(i=1; i<=sz; i++){
32705     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
32706       rc = i;
32707       break;
32708     }
32709   }
32710
32711   /* Free allocated structure */
32712 bitvec_end:
32713   sqlite3_free(pTmpSpace);
32714   sqlite3_free(pV);
32715   sqlite3BitvecDestroy(pBitvec);
32716   return rc;
32717 }
32718 #endif /* SQLITE_OMIT_BUILTIN_TEST */
32719
32720 /************** End of bitvec.c **********************************************/
32721 /************** Begin file pcache.c ******************************************/
32722 /*
32723 ** 2008 August 05
32724 **
32725 ** The author disclaims copyright to this source code.  In place of
32726 ** a legal notice, here is a blessing:
32727 **
32728 **    May you do good and not evil.
32729 **    May you find forgiveness for yourself and forgive others.
32730 **    May you share freely, never taking more than you give.
32731 **
32732 *************************************************************************
32733 ** This file implements that page cache.
32734 */
32735
32736 /*
32737 ** A complete page cache is an instance of this structure.
32738 */
32739 struct PCache {
32740   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
32741   PgHdr *pSynced;                     /* Last synced page in dirty page list */
32742   int nRef;                           /* Number of referenced pages */
32743   int nMax;                           /* Configured cache size */
32744   int szPage;                         /* Size of every page in this cache */
32745   int szExtra;                        /* Size of extra space for each page */
32746   int bPurgeable;                     /* True if pages are on backing store */
32747   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
32748   void *pStress;                      /* Argument to xStress */
32749   sqlite3_pcache *pCache;             /* Pluggable cache module */
32750   PgHdr *pPage1;                      /* Reference to page 1 */
32751 };
32752
32753 /*
32754 ** Some of the assert() macros in this code are too expensive to run
32755 ** even during normal debugging.  Use them only rarely on long-running
32756 ** tests.  Enable the expensive asserts using the
32757 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
32758 */
32759 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
32760 # define expensive_assert(X)  assert(X)
32761 #else
32762 # define expensive_assert(X)
32763 #endif
32764
32765 /********************************** Linked List Management ********************/
32766
32767 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
32768 /*
32769 ** Check that the pCache->pSynced variable is set correctly. If it
32770 ** is not, either fail an assert or return zero. Otherwise, return
32771 ** non-zero. This is only used in debugging builds, as follows:
32772 **
32773 **   expensive_assert( pcacheCheckSynced(pCache) );
32774 */
32775 static int pcacheCheckSynced(PCache *pCache){
32776   PgHdr *p;
32777   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
32778     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
32779   }
32780   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
32781 }
32782 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
32783
32784 /*
32785 ** Remove page pPage from the list of dirty pages.
32786 */
32787 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
32788   PCache *p = pPage->pCache;
32789
32790   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
32791   assert( pPage->pDirtyPrev || pPage==p->pDirty );
32792
32793   /* Update the PCache1.pSynced variable if necessary. */
32794   if( p->pSynced==pPage ){
32795     PgHdr *pSynced = pPage->pDirtyPrev;
32796     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
32797       pSynced = pSynced->pDirtyPrev;
32798     }
32799     p->pSynced = pSynced;
32800   }
32801
32802   if( pPage->pDirtyNext ){
32803     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
32804   }else{
32805     assert( pPage==p->pDirtyTail );
32806     p->pDirtyTail = pPage->pDirtyPrev;
32807   }
32808   if( pPage->pDirtyPrev ){
32809     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
32810   }else{
32811     assert( pPage==p->pDirty );
32812     p->pDirty = pPage->pDirtyNext;
32813   }
32814   pPage->pDirtyNext = 0;
32815   pPage->pDirtyPrev = 0;
32816
32817   expensive_assert( pcacheCheckSynced(p) );
32818 }
32819
32820 /*
32821 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
32822 ** pPage).
32823 */
32824 static void pcacheAddToDirtyList(PgHdr *pPage){
32825   PCache *p = pPage->pCache;
32826
32827   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
32828
32829   pPage->pDirtyNext = p->pDirty;
32830   if( pPage->pDirtyNext ){
32831     assert( pPage->pDirtyNext->pDirtyPrev==0 );
32832     pPage->pDirtyNext->pDirtyPrev = pPage;
32833   }
32834   p->pDirty = pPage;
32835   if( !p->pDirtyTail ){
32836     p->pDirtyTail = pPage;
32837   }
32838   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
32839     p->pSynced = pPage;
32840   }
32841   expensive_assert( pcacheCheckSynced(p) );
32842 }
32843
32844 /*
32845 ** Wrapper around the pluggable caches xUnpin method. If the cache is
32846 ** being used for an in-memory database, this function is a no-op.
32847 */
32848 static void pcacheUnpin(PgHdr *p){
32849   PCache *pCache = p->pCache;
32850   if( pCache->bPurgeable ){
32851     if( p->pgno==1 ){
32852       pCache->pPage1 = 0;
32853     }
32854     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
32855   }
32856 }
32857
32858 /*************************************************** General Interfaces ******
32859 **
32860 ** Initialize and shutdown the page cache subsystem. Neither of these 
32861 ** functions are threadsafe.
32862 */
32863 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
32864   if( sqlite3GlobalConfig.pcache.xInit==0 ){
32865     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
32866     ** built-in default page cache is used instead of the application defined
32867     ** page cache. */
32868     sqlite3PCacheSetDefault();
32869   }
32870   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
32871 }
32872 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
32873   if( sqlite3GlobalConfig.pcache.xShutdown ){
32874     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
32875     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
32876   }
32877 }
32878
32879 /*
32880 ** Return the size in bytes of a PCache object.
32881 */
32882 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
32883
32884 /*
32885 ** Create a new PCache object. Storage space to hold the object
32886 ** has already been allocated and is passed in as the p pointer. 
32887 ** The caller discovers how much space needs to be allocated by 
32888 ** calling sqlite3PcacheSize().
32889 */
32890 SQLITE_PRIVATE void sqlite3PcacheOpen(
32891   int szPage,                  /* Size of every page */
32892   int szExtra,                 /* Extra space associated with each page */
32893   int bPurgeable,              /* True if pages are on backing store */
32894   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
32895   void *pStress,               /* Argument to xStress */
32896   PCache *p                    /* Preallocated space for the PCache */
32897 ){
32898   memset(p, 0, sizeof(PCache));
32899   p->szPage = szPage;
32900   p->szExtra = szExtra;
32901   p->bPurgeable = bPurgeable;
32902   p->xStress = xStress;
32903   p->pStress = pStress;
32904   p->nMax = 100;
32905 }
32906
32907 /*
32908 ** Change the page size for PCache object. The caller must ensure that there
32909 ** are no outstanding page references when this function is called.
32910 */
32911 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
32912   assert( pCache->nRef==0 && pCache->pDirty==0 );
32913   if( pCache->pCache ){
32914     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
32915     pCache->pCache = 0;
32916     pCache->pPage1 = 0;
32917   }
32918   pCache->szPage = szPage;
32919 }
32920
32921 /*
32922 ** Try to obtain a page from the cache.
32923 */
32924 SQLITE_PRIVATE int sqlite3PcacheFetch(
32925   PCache *pCache,       /* Obtain the page from this cache */
32926   Pgno pgno,            /* Page number to obtain */
32927   int createFlag,       /* If true, create page if it does not exist already */
32928   PgHdr **ppPage        /* Write the page here */
32929 ){
32930   PgHdr *pPage = 0;
32931   int eCreate;
32932
32933   assert( pCache!=0 );
32934   assert( createFlag==1 || createFlag==0 );
32935   assert( pgno>0 );
32936
32937   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
32938   ** allocate it now.
32939   */
32940   if( !pCache->pCache && createFlag ){
32941     sqlite3_pcache *p;
32942     int nByte;
32943     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
32944     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
32945     if( !p ){
32946       return SQLITE_NOMEM;
32947     }
32948     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
32949     pCache->pCache = p;
32950   }
32951
32952   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
32953   if( pCache->pCache ){
32954     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
32955   }
32956
32957   if( !pPage && eCreate==1 ){
32958     PgHdr *pPg;
32959
32960     /* Find a dirty page to write-out and recycle. First try to find a 
32961     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
32962     ** cleared), but if that is not possible settle for any other 
32963     ** unreferenced dirty page.
32964     */
32965     expensive_assert( pcacheCheckSynced(pCache) );
32966     for(pPg=pCache->pSynced; 
32967         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
32968         pPg=pPg->pDirtyPrev
32969     );
32970     pCache->pSynced = pPg;
32971     if( !pPg ){
32972       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
32973     }
32974     if( pPg ){
32975       int rc;
32976       rc = pCache->xStress(pCache->pStress, pPg);
32977       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
32978         return rc;
32979       }
32980     }
32981
32982     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
32983   }
32984
32985   if( pPage ){
32986     if( !pPage->pData ){
32987       memset(pPage, 0, sizeof(PgHdr));
32988       pPage->pData = (void *)&pPage[1];
32989       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
32990       memset(pPage->pExtra, 0, pCache->szExtra);
32991       pPage->pCache = pCache;
32992       pPage->pgno = pgno;
32993     }
32994     assert( pPage->pCache==pCache );
32995     assert( pPage->pgno==pgno );
32996     assert( pPage->pData==(void *)&pPage[1] );
32997     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
32998
32999     if( 0==pPage->nRef ){
33000       pCache->nRef++;
33001     }
33002     pPage->nRef++;
33003     if( pgno==1 ){
33004       pCache->pPage1 = pPage;
33005     }
33006   }
33007   *ppPage = pPage;
33008   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
33009 }
33010
33011 /*
33012 ** Decrement the reference count on a page. If the page is clean and the
33013 ** reference count drops to 0, then it is made elible for recycling.
33014 */
33015 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
33016   assert( p->nRef>0 );
33017   p->nRef--;
33018   if( p->nRef==0 ){
33019     PCache *pCache = p->pCache;
33020     pCache->nRef--;
33021     if( (p->flags&PGHDR_DIRTY)==0 ){
33022       pcacheUnpin(p);
33023     }else{
33024       /* Move the page to the head of the dirty list. */
33025       pcacheRemoveFromDirtyList(p);
33026       pcacheAddToDirtyList(p);
33027     }
33028   }
33029 }
33030
33031 /*
33032 ** Increase the reference count of a supplied page by 1.
33033 */
33034 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
33035   assert(p->nRef>0);
33036   p->nRef++;
33037 }
33038
33039 /*
33040 ** Drop a page from the cache. There must be exactly one reference to the
33041 ** page. This function deletes that reference, so after it returns the
33042 ** page pointed to by p is invalid.
33043 */
33044 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
33045   PCache *pCache;
33046   assert( p->nRef==1 );
33047   if( p->flags&PGHDR_DIRTY ){
33048     pcacheRemoveFromDirtyList(p);
33049   }
33050   pCache = p->pCache;
33051   pCache->nRef--;
33052   if( p->pgno==1 ){
33053     pCache->pPage1 = 0;
33054   }
33055   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
33056 }
33057
33058 /*
33059 ** Make sure the page is marked as dirty. If it isn't dirty already,
33060 ** make it so.
33061 */
33062 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
33063   p->flags &= ~PGHDR_DONT_WRITE;
33064   assert( p->nRef>0 );
33065   if( 0==(p->flags & PGHDR_DIRTY) ){
33066     p->flags |= PGHDR_DIRTY;
33067     pcacheAddToDirtyList( p);
33068   }
33069 }
33070
33071 /*
33072 ** Make sure the page is marked as clean. If it isn't clean already,
33073 ** make it so.
33074 */
33075 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
33076   if( (p->flags & PGHDR_DIRTY) ){
33077     pcacheRemoveFromDirtyList(p);
33078     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
33079     if( p->nRef==0 ){
33080       pcacheUnpin(p);
33081     }
33082   }
33083 }
33084
33085 /*
33086 ** Make every page in the cache clean.
33087 */
33088 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
33089   PgHdr *p;
33090   while( (p = pCache->pDirty)!=0 ){
33091     sqlite3PcacheMakeClean(p);
33092   }
33093 }
33094
33095 /*
33096 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
33097 */
33098 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
33099   PgHdr *p;
33100   for(p=pCache->pDirty; p; p=p->pDirtyNext){
33101     p->flags &= ~PGHDR_NEED_SYNC;
33102   }
33103   pCache->pSynced = pCache->pDirtyTail;
33104 }
33105
33106 /*
33107 ** Change the page number of page p to newPgno. 
33108 */
33109 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
33110   PCache *pCache = p->pCache;
33111   assert( p->nRef>0 );
33112   assert( newPgno>0 );
33113   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
33114   p->pgno = newPgno;
33115   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
33116     pcacheRemoveFromDirtyList(p);
33117     pcacheAddToDirtyList(p);
33118   }
33119 }
33120
33121 /*
33122 ** Drop every cache entry whose page number is greater than "pgno". The
33123 ** caller must ensure that there are no outstanding references to any pages
33124 ** other than page 1 with a page number greater than pgno.
33125 **
33126 ** If there is a reference to page 1 and the pgno parameter passed to this
33127 ** function is 0, then the data area associated with page 1 is zeroed, but
33128 ** the page object is not dropped.
33129 */
33130 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
33131   if( pCache->pCache ){
33132     PgHdr *p;
33133     PgHdr *pNext;
33134     for(p=pCache->pDirty; p; p=pNext){
33135       pNext = p->pDirtyNext;
33136       /* This routine never gets call with a positive pgno except right
33137       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
33138       ** it must be that pgno==0.
33139       */
33140       assert( p->pgno>0 );
33141       if( ALWAYS(p->pgno>pgno) ){
33142         assert( p->flags&PGHDR_DIRTY );
33143         sqlite3PcacheMakeClean(p);
33144       }
33145     }
33146     if( pgno==0 && pCache->pPage1 ){
33147       memset(pCache->pPage1->pData, 0, pCache->szPage);
33148       pgno = 1;
33149     }
33150     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
33151   }
33152 }
33153
33154 /*
33155 ** Close a cache.
33156 */
33157 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
33158   if( pCache->pCache ){
33159     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
33160   }
33161 }
33162
33163 /* 
33164 ** Discard the contents of the cache.
33165 */
33166 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
33167   sqlite3PcacheTruncate(pCache, 0);
33168 }
33169
33170 /*
33171 ** Merge two lists of pages connected by pDirty and in pgno order.
33172 ** Do not both fixing the pDirtyPrev pointers.
33173 */
33174 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
33175   PgHdr result, *pTail;
33176   pTail = &result;
33177   while( pA && pB ){
33178     if( pA->pgno<pB->pgno ){
33179       pTail->pDirty = pA;
33180       pTail = pA;
33181       pA = pA->pDirty;
33182     }else{
33183       pTail->pDirty = pB;
33184       pTail = pB;
33185       pB = pB->pDirty;
33186     }
33187   }
33188   if( pA ){
33189     pTail->pDirty = pA;
33190   }else if( pB ){
33191     pTail->pDirty = pB;
33192   }else{
33193     pTail->pDirty = 0;
33194   }
33195   return result.pDirty;
33196 }
33197
33198 /*
33199 ** Sort the list of pages in accending order by pgno.  Pages are
33200 ** connected by pDirty pointers.  The pDirtyPrev pointers are
33201 ** corrupted by this sort.
33202 **
33203 ** Since there cannot be more than 2^31 distinct pages in a database,
33204 ** there cannot be more than 31 buckets required by the merge sorter.
33205 ** One extra bucket is added to catch overflow in case something
33206 ** ever changes to make the previous sentence incorrect.
33207 */
33208 #define N_SORT_BUCKET  32
33209 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
33210   PgHdr *a[N_SORT_BUCKET], *p;
33211   int i;
33212   memset(a, 0, sizeof(a));
33213   while( pIn ){
33214     p = pIn;
33215     pIn = p->pDirty;
33216     p->pDirty = 0;
33217     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
33218       if( a[i]==0 ){
33219         a[i] = p;
33220         break;
33221       }else{
33222         p = pcacheMergeDirtyList(a[i], p);
33223         a[i] = 0;
33224       }
33225     }
33226     if( NEVER(i==N_SORT_BUCKET-1) ){
33227       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
33228       ** the input list.  But that is impossible.
33229       */
33230       a[i] = pcacheMergeDirtyList(a[i], p);
33231     }
33232   }
33233   p = a[0];
33234   for(i=1; i<N_SORT_BUCKET; i++){
33235     p = pcacheMergeDirtyList(p, a[i]);
33236   }
33237   return p;
33238 }
33239
33240 /*
33241 ** Return a list of all dirty pages in the cache, sorted by page number.
33242 */
33243 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
33244   PgHdr *p;
33245   for(p=pCache->pDirty; p; p=p->pDirtyNext){
33246     p->pDirty = p->pDirtyNext;
33247   }
33248   return pcacheSortDirtyList(pCache->pDirty);
33249 }
33250
33251 /* 
33252 ** Return the total number of referenced pages held by the cache.
33253 */
33254 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
33255   return pCache->nRef;
33256 }
33257
33258 /*
33259 ** Return the number of references to the page supplied as an argument.
33260 */
33261 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
33262   return p->nRef;
33263 }
33264
33265 /* 
33266 ** Return the total number of pages in the cache.
33267 */
33268 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
33269   int nPage = 0;
33270   if( pCache->pCache ){
33271     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
33272   }
33273   return nPage;
33274 }
33275
33276 #ifdef SQLITE_TEST
33277 /*
33278 ** Get the suggested cache-size value.
33279 */
33280 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
33281   return pCache->nMax;
33282 }
33283 #endif
33284
33285 /*
33286 ** Set the suggested cache-size value.
33287 */
33288 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
33289   pCache->nMax = mxPage;
33290   if( pCache->pCache ){
33291     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
33292   }
33293 }
33294
33295 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
33296 /*
33297 ** For all dirty pages currently in the cache, invoke the specified
33298 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
33299 ** defined.
33300 */
33301 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
33302   PgHdr *pDirty;
33303   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
33304     xIter(pDirty);
33305   }
33306 }
33307 #endif
33308
33309 /************** End of pcache.c **********************************************/
33310 /************** Begin file pcache1.c *****************************************/
33311 /*
33312 ** 2008 November 05
33313 **
33314 ** The author disclaims copyright to this source code.  In place of
33315 ** a legal notice, here is a blessing:
33316 **
33317 **    May you do good and not evil.
33318 **    May you find forgiveness for yourself and forgive others.
33319 **    May you share freely, never taking more than you give.
33320 **
33321 *************************************************************************
33322 **
33323 ** This file implements the default page cache implementation (the
33324 ** sqlite3_pcache interface). It also contains part of the implementation
33325 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
33326 ** If the default page cache implementation is overriden, then neither of
33327 ** these two features are available.
33328 */
33329
33330
33331 typedef struct PCache1 PCache1;
33332 typedef struct PgHdr1 PgHdr1;
33333 typedef struct PgFreeslot PgFreeslot;
33334
33335 /* Each page cache is an instance of the following object.  Every
33336 ** open database file (including each in-memory database and each
33337 ** temporary or transient database) has a single page cache which
33338 ** is an instance of this object.
33339 **
33340 ** Pointers to structures of this type are cast and returned as 
33341 ** opaque sqlite3_pcache* handles.
33342 */
33343 struct PCache1 {
33344   /* Cache configuration parameters. Page size (szPage) and the purgeable
33345   ** flag (bPurgeable) are set when the cache is created. nMax may be 
33346   ** modified at any time by a call to the pcache1CacheSize() method.
33347   ** The global mutex must be held when accessing nMax.
33348   */
33349   int szPage;                         /* Size of allocated pages in bytes */
33350   int bPurgeable;                     /* True if cache is purgeable */
33351   unsigned int nMin;                  /* Minimum number of pages reserved */
33352   unsigned int nMax;                  /* Configured "cache_size" value */
33353
33354   /* Hash table of all pages. The following variables may only be accessed
33355   ** when the accessor is holding the global mutex (see pcache1EnterMutex() 
33356   ** and pcache1LeaveMutex()).
33357   */
33358   unsigned int nRecyclable;           /* Number of pages in the LRU list */
33359   unsigned int nPage;                 /* Total number of pages in apHash */
33360   unsigned int nHash;                 /* Number of slots in apHash[] */
33361   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
33362
33363   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
33364 };
33365
33366 /*
33367 ** Each cache entry is represented by an instance of the following 
33368 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
33369 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
33370 ** macro below).
33371 */
33372 struct PgHdr1 {
33373   unsigned int iKey;             /* Key value (page number) */
33374   PgHdr1 *pNext;                 /* Next in hash table chain */
33375   PCache1 *pCache;               /* Cache that currently owns this page */
33376   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
33377   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
33378 };
33379
33380 /*
33381 ** Free slots in the allocator used to divide up the buffer provided using
33382 ** the SQLITE_CONFIG_PAGECACHE mechanism.
33383 */
33384 struct PgFreeslot {
33385   PgFreeslot *pNext;  /* Next free slot */
33386 };
33387
33388 /*
33389 ** Global data used by this cache.
33390 */
33391 static SQLITE_WSD struct PCacheGlobal {
33392   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
33393
33394   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
33395   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
33396   int nCurrentPage;                   /* Number of purgeable pages allocated */
33397   PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
33398
33399   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
33400   int szSlot;                         /* Size of each free slot */
33401   int nSlot;                          /* The number of pcache slots */
33402   int nFreeSlot;                      /* Number of unused pcache slots */
33403   int nReserve;                       /* Try to keep nFreeSlot above this */
33404   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
33405   PgFreeslot *pFree;                  /* Free page blocks */
33406   int isInit;                         /* True if initialized */
33407 } pcache1_g;
33408
33409 /*
33410 ** All code in this file should access the global structure above via the
33411 ** alias "pcache1". This ensures that the WSD emulation is used when
33412 ** compiling for systems that do not support real WSD.
33413 */
33414 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
33415
33416 /*
33417 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
33418 ** bytes of data are located directly before it in memory (i.e. the total
33419 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
33420 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
33421 ** an argument and returns a pointer to the associated block of szPage
33422 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
33423 ** a pointer to a block of szPage bytes of data and the return value is
33424 ** a pointer to the associated PgHdr1 structure.
33425 **
33426 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
33427 */
33428 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
33429 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
33430
33431 /*
33432 ** Macros to enter and leave the global LRU mutex.
33433 */
33434 #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
33435 #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
33436
33437 /******************************************************************************/
33438 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
33439
33440 /*
33441 ** This function is called during initialization if a static buffer is 
33442 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
33443 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
33444 ** enough to contain 'n' buffers of 'sz' bytes each.
33445 */
33446 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
33447   if( pcache1.isInit ){
33448     PgFreeslot *p;
33449     sz = ROUNDDOWN8(sz);
33450     pcache1.szSlot = sz;
33451     pcache1.nSlot = pcache1.nFreeSlot = n;
33452     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
33453     pcache1.pStart = pBuf;
33454     pcache1.pFree = 0;
33455     while( n-- ){
33456       p = (PgFreeslot*)pBuf;
33457       p->pNext = pcache1.pFree;
33458       pcache1.pFree = p;
33459       pBuf = (void*)&((char*)pBuf)[sz];
33460     }
33461     pcache1.pEnd = pBuf;
33462   }
33463 }
33464
33465 /*
33466 ** Malloc function used within this file to allocate space from the buffer
33467 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
33468 ** such buffer exists or there is no space left in it, this function falls 
33469 ** back to sqlite3Malloc().
33470 */
33471 static void *pcache1Alloc(int nByte){
33472   void *p;
33473   assert( sqlite3_mutex_held(pcache1.mutex) );
33474   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
33475   if( nByte<=pcache1.szSlot && pcache1.pFree ){
33476     assert( pcache1.isInit );
33477     p = (PgHdr1 *)pcache1.pFree;
33478     pcache1.pFree = pcache1.pFree->pNext;
33479     pcache1.nFreeSlot--;
33480     assert( pcache1.nFreeSlot>=0 );
33481     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
33482   }else{
33483
33484     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
33485     ** global pcache mutex and unlock the pager-cache object pCache. This is 
33486     ** so that if the attempt to allocate a new buffer causes the the 
33487     ** configured soft-heap-limit to be breached, it will be possible to
33488     ** reclaim memory from this pager-cache.
33489     */
33490     pcache1LeaveMutex();
33491     p = sqlite3Malloc(nByte);
33492     pcache1EnterMutex();
33493     if( p ){
33494       int sz = sqlite3MallocSize(p);
33495       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
33496     }
33497     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
33498   }
33499   return p;
33500 }
33501
33502 /*
33503 ** Free an allocated buffer obtained from pcache1Alloc().
33504 */
33505 static void pcache1Free(void *p){
33506   assert( sqlite3_mutex_held(pcache1.mutex) );
33507   if( p==0 ) return;
33508   if( p>=pcache1.pStart && p<pcache1.pEnd ){
33509     PgFreeslot *pSlot;
33510     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
33511     pSlot = (PgFreeslot*)p;
33512     pSlot->pNext = pcache1.pFree;
33513     pcache1.pFree = pSlot;
33514     pcache1.nFreeSlot++;
33515     assert( pcache1.nFreeSlot<=pcache1.nSlot );
33516   }else{
33517     int iSize;
33518     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33519     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33520     iSize = sqlite3MallocSize(p);
33521     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
33522     sqlite3_free(p);
33523   }
33524 }
33525
33526 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
33527 /*
33528 ** Return the size of a pcache allocation
33529 */
33530 static int pcache1MemSize(void *p){
33531   assert( sqlite3_mutex_held(pcache1.mutex) );
33532   if( p>=pcache1.pStart && p<pcache1.pEnd ){
33533     return pcache1.szSlot;
33534   }else{
33535     int iSize;
33536     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
33537     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
33538     iSize = sqlite3MallocSize(p);
33539     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
33540     return iSize;
33541   }
33542 }
33543 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
33544
33545 /*
33546 ** Allocate a new page object initially associated with cache pCache.
33547 */
33548 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
33549   int nByte = sizeof(PgHdr1) + pCache->szPage;
33550   void *pPg = pcache1Alloc(nByte);
33551   PgHdr1 *p;
33552   if( pPg ){
33553     p = PAGE_TO_PGHDR1(pCache, pPg);
33554     if( pCache->bPurgeable ){
33555       pcache1.nCurrentPage++;
33556     }
33557   }else{
33558     p = 0;
33559   }
33560   return p;
33561 }
33562
33563 /*
33564 ** Free a page object allocated by pcache1AllocPage().
33565 **
33566 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
33567 ** that the current implementation happens to never call this routine
33568 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
33569 */
33570 static void pcache1FreePage(PgHdr1 *p){
33571   if( ALWAYS(p) ){
33572     if( p->pCache->bPurgeable ){
33573       pcache1.nCurrentPage--;
33574     }
33575     pcache1Free(PGHDR1_TO_PAGE(p));
33576   }
33577 }
33578
33579 /*
33580 ** Malloc function used by SQLite to obtain space from the buffer configured
33581 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
33582 ** exists, this function falls back to sqlite3Malloc().
33583 */
33584 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
33585   void *p;
33586   pcache1EnterMutex();
33587   p = pcache1Alloc(sz);
33588   pcache1LeaveMutex();
33589   return p;
33590 }
33591
33592 /*
33593 ** Free an allocated buffer obtained from sqlite3PageMalloc().
33594 */
33595 SQLITE_PRIVATE void sqlite3PageFree(void *p){
33596   pcache1EnterMutex();
33597   pcache1Free(p);
33598   pcache1LeaveMutex();
33599 }
33600
33601
33602 /*
33603 ** Return true if it desirable to avoid allocating a new page cache
33604 ** entry.
33605 **
33606 ** If memory was allocated specifically to the page cache using
33607 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
33608 ** it is desirable to avoid allocating a new page cache entry because
33609 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
33610 ** for all page cache needs and we should not need to spill the
33611 ** allocation onto the heap.
33612 **
33613 ** Or, the heap is used for all page cache memory put the heap is
33614 ** under memory pressure, then again it is desirable to avoid
33615 ** allocating a new page cache entry in order to avoid stressing
33616 ** the heap even further.
33617 */
33618 static int pcache1UnderMemoryPressure(PCache1 *pCache){
33619   assert( sqlite3_mutex_held(pcache1.mutex) );
33620   if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
33621     return pcache1.nFreeSlot<pcache1.nReserve;
33622   }else{
33623     return sqlite3HeapNearlyFull();
33624   }
33625 }
33626
33627 /******************************************************************************/
33628 /******** General Implementation Functions ************************************/
33629
33630 /*
33631 ** This function is used to resize the hash table used by the cache passed
33632 ** as the first argument.
33633 **
33634 ** The global mutex must be held when this function is called.
33635 */
33636 static int pcache1ResizeHash(PCache1 *p){
33637   PgHdr1 **apNew;
33638   unsigned int nNew;
33639   unsigned int i;
33640
33641   assert( sqlite3_mutex_held(pcache1.mutex) );
33642
33643   nNew = p->nHash*2;
33644   if( nNew<256 ){
33645     nNew = 256;
33646   }
33647
33648   pcache1LeaveMutex();
33649   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
33650   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
33651   if( p->nHash ){ sqlite3EndBenignMalloc(); }
33652   pcache1EnterMutex();
33653   if( apNew ){
33654     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
33655     for(i=0; i<p->nHash; i++){
33656       PgHdr1 *pPage;
33657       PgHdr1 *pNext = p->apHash[i];
33658       while( (pPage = pNext)!=0 ){
33659         unsigned int h = pPage->iKey % nNew;
33660         pNext = pPage->pNext;
33661         pPage->pNext = apNew[h];
33662         apNew[h] = pPage;
33663       }
33664     }
33665     sqlite3_free(p->apHash);
33666     p->apHash = apNew;
33667     p->nHash = nNew;
33668   }
33669
33670   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
33671 }
33672
33673 /*
33674 ** This function is used internally to remove the page pPage from the 
33675 ** global LRU list, if is part of it. If pPage is not part of the global
33676 ** LRU list, then this function is a no-op.
33677 **
33678 ** The global mutex must be held when this function is called.
33679 */
33680 static void pcache1PinPage(PgHdr1 *pPage){
33681   assert( sqlite3_mutex_held(pcache1.mutex) );
33682   if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
33683     if( pPage->pLruPrev ){
33684       pPage->pLruPrev->pLruNext = pPage->pLruNext;
33685     }
33686     if( pPage->pLruNext ){
33687       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
33688     }
33689     if( pcache1.pLruHead==pPage ){
33690       pcache1.pLruHead = pPage->pLruNext;
33691     }
33692     if( pcache1.pLruTail==pPage ){
33693       pcache1.pLruTail = pPage->pLruPrev;
33694     }
33695     pPage->pLruNext = 0;
33696     pPage->pLruPrev = 0;
33697     pPage->pCache->nRecyclable--;
33698   }
33699 }
33700
33701
33702 /*
33703 ** Remove the page supplied as an argument from the hash table 
33704 ** (PCache1.apHash structure) that it is currently stored in.
33705 **
33706 ** The global mutex must be held when this function is called.
33707 */
33708 static void pcache1RemoveFromHash(PgHdr1 *pPage){
33709   unsigned int h;
33710   PCache1 *pCache = pPage->pCache;
33711   PgHdr1 **pp;
33712
33713   h = pPage->iKey % pCache->nHash;
33714   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
33715   *pp = (*pp)->pNext;
33716
33717   pCache->nPage--;
33718 }
33719
33720 /*
33721 ** If there are currently more than pcache.nMaxPage pages allocated, try
33722 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
33723 */
33724 static void pcache1EnforceMaxPage(void){
33725   assert( sqlite3_mutex_held(pcache1.mutex) );
33726   while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
33727     PgHdr1 *p = pcache1.pLruTail;
33728     pcache1PinPage(p);
33729     pcache1RemoveFromHash(p);
33730     pcache1FreePage(p);
33731   }
33732 }
33733
33734 /*
33735 ** Discard all pages from cache pCache with a page number (key value) 
33736 ** greater than or equal to iLimit. Any pinned pages that meet this 
33737 ** criteria are unpinned before they are discarded.
33738 **
33739 ** The global mutex must be held when this function is called.
33740 */
33741 static void pcache1TruncateUnsafe(
33742   PCache1 *pCache, 
33743   unsigned int iLimit 
33744 ){
33745   TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
33746   unsigned int h;
33747   assert( sqlite3_mutex_held(pcache1.mutex) );
33748   for(h=0; h<pCache->nHash; h++){
33749     PgHdr1 **pp = &pCache->apHash[h]; 
33750     PgHdr1 *pPage;
33751     while( (pPage = *pp)!=0 ){
33752       if( pPage->iKey>=iLimit ){
33753         pCache->nPage--;
33754         *pp = pPage->pNext;
33755         pcache1PinPage(pPage);
33756         pcache1FreePage(pPage);
33757       }else{
33758         pp = &pPage->pNext;
33759         TESTONLY( nPage++; )
33760       }
33761     }
33762   }
33763   assert( pCache->nPage==nPage );
33764 }
33765
33766 /******************************************************************************/
33767 /******** sqlite3_pcache Methods **********************************************/
33768
33769 /*
33770 ** Implementation of the sqlite3_pcache.xInit method.
33771 */
33772 static int pcache1Init(void *NotUsed){
33773   UNUSED_PARAMETER(NotUsed);
33774   assert( pcache1.isInit==0 );
33775   memset(&pcache1, 0, sizeof(pcache1));
33776   if( sqlite3GlobalConfig.bCoreMutex ){
33777     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
33778   }
33779   pcache1.isInit = 1;
33780   return SQLITE_OK;
33781 }
33782
33783 /*
33784 ** Implementation of the sqlite3_pcache.xShutdown method.
33785 ** Note that the static mutex allocated in xInit does 
33786 ** not need to be freed.
33787 */
33788 static void pcache1Shutdown(void *NotUsed){
33789   UNUSED_PARAMETER(NotUsed);
33790   assert( pcache1.isInit!=0 );
33791   memset(&pcache1, 0, sizeof(pcache1));
33792 }
33793
33794 /*
33795 ** Implementation of the sqlite3_pcache.xCreate method.
33796 **
33797 ** Allocate a new cache.
33798 */
33799 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
33800   PCache1 *pCache;
33801
33802   pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
33803   if( pCache ){
33804     memset(pCache, 0, sizeof(PCache1));
33805     pCache->szPage = szPage;
33806     pCache->bPurgeable = (bPurgeable ? 1 : 0);
33807     if( bPurgeable ){
33808       pCache->nMin = 10;
33809       pcache1EnterMutex();
33810       pcache1.nMinPage += pCache->nMin;
33811       pcache1LeaveMutex();
33812     }
33813   }
33814   return (sqlite3_pcache *)pCache;
33815 }
33816
33817 /*
33818 ** Implementation of the sqlite3_pcache.xCachesize method. 
33819 **
33820 ** Configure the cache_size limit for a cache.
33821 */
33822 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
33823   PCache1 *pCache = (PCache1 *)p;
33824   if( pCache->bPurgeable ){
33825     pcache1EnterMutex();
33826     pcache1.nMaxPage += (nMax - pCache->nMax);
33827     pCache->nMax = nMax;
33828     pcache1EnforceMaxPage();
33829     pcache1LeaveMutex();
33830   }
33831 }
33832
33833 /*
33834 ** Implementation of the sqlite3_pcache.xPagecount method. 
33835 */
33836 static int pcache1Pagecount(sqlite3_pcache *p){
33837   int n;
33838   pcache1EnterMutex();
33839   n = ((PCache1 *)p)->nPage;
33840   pcache1LeaveMutex();
33841   return n;
33842 }
33843
33844 /*
33845 ** Implementation of the sqlite3_pcache.xFetch method. 
33846 **
33847 ** Fetch a page by key value.
33848 **
33849 ** Whether or not a new page may be allocated by this function depends on
33850 ** the value of the createFlag argument.  0 means do not allocate a new
33851 ** page.  1 means allocate a new page if space is easily available.  2 
33852 ** means to try really hard to allocate a new page.
33853 **
33854 ** For a non-purgeable cache (a cache used as the storage for an in-memory
33855 ** database) there is really no difference between createFlag 1 and 2.  So
33856 ** the calling function (pcache.c) will never have a createFlag of 1 on
33857 ** a non-purgable cache.
33858 **
33859 ** There are three different approaches to obtaining space for a page,
33860 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
33861 **
33862 **   1. Regardless of the value of createFlag, the cache is searched for a 
33863 **      copy of the requested page. If one is found, it is returned.
33864 **
33865 **   2. If createFlag==0 and the page is not already in the cache, NULL is
33866 **      returned.
33867 **
33868 **   3. If createFlag is 1, and the page is not already in the cache, then
33869 **      return NULL (do not allocate a new page) if any of the following
33870 **      conditions are true:
33871 **
33872 **       (a) the number of pages pinned by the cache is greater than
33873 **           PCache1.nMax, or
33874 **
33875 **       (b) the number of pages pinned by the cache is greater than
33876 **           the sum of nMax for all purgeable caches, less the sum of 
33877 **           nMin for all other purgeable caches, or
33878 **
33879 **   4. If none of the first three conditions apply and the cache is marked
33880 **      as purgeable, and if one of the following is true:
33881 **
33882 **       (a) The number of pages allocated for the cache is already 
33883 **           PCache1.nMax, or
33884 **
33885 **       (b) The number of pages allocated for all purgeable caches is
33886 **           already equal to or greater than the sum of nMax for all
33887 **           purgeable caches,
33888 **
33889 **       (c) The system is under memory pressure and wants to avoid
33890 **           unnecessary pages cache entry allocations
33891 **
33892 **      then attempt to recycle a page from the LRU list. If it is the right
33893 **      size, return the recycled buffer. Otherwise, free the buffer and
33894 **      proceed to step 5. 
33895 **
33896 **   5. Otherwise, allocate and return a new page buffer.
33897 */
33898 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
33899   unsigned int nPinned;
33900   PCache1 *pCache = (PCache1 *)p;
33901   PgHdr1 *pPage = 0;
33902
33903   assert( pCache->bPurgeable || createFlag!=1 );
33904   pcache1EnterMutex();
33905   if( createFlag==1 ) sqlite3BeginBenignMalloc();
33906
33907   /* Search the hash table for an existing entry. */
33908   if( pCache->nHash>0 ){
33909     unsigned int h = iKey % pCache->nHash;
33910     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
33911   }
33912
33913   if( pPage || createFlag==0 ){
33914     pcache1PinPage(pPage);
33915     goto fetch_out;
33916   }
33917
33918   /* Step 3 of header comment. */
33919   nPinned = pCache->nPage - pCache->nRecyclable;
33920   if( createFlag==1 && (
33921         nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
33922      || nPinned>=(pCache->nMax * 9 / 10)
33923      || pcache1UnderMemoryPressure(pCache)
33924   )){
33925     goto fetch_out;
33926   }
33927
33928   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
33929     goto fetch_out;
33930   }
33931
33932   /* Step 4. Try to recycle a page buffer if appropriate. */
33933   if( pCache->bPurgeable && pcache1.pLruTail && (
33934          (pCache->nPage+1>=pCache->nMax)
33935       || pcache1.nCurrentPage>=pcache1.nMaxPage
33936       || pcache1UnderMemoryPressure(pCache)
33937   )){
33938     pPage = pcache1.pLruTail;
33939     pcache1RemoveFromHash(pPage);
33940     pcache1PinPage(pPage);
33941     if( pPage->pCache->szPage!=pCache->szPage ){
33942       pcache1FreePage(pPage);
33943       pPage = 0;
33944     }else{
33945       pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
33946     }
33947   }
33948
33949   /* Step 5. If a usable page buffer has still not been found, 
33950   ** attempt to allocate a new one. 
33951   */
33952   if( !pPage ){
33953     pPage = pcache1AllocPage(pCache);
33954   }
33955
33956   if( pPage ){
33957     unsigned int h = iKey % pCache->nHash;
33958     pCache->nPage++;
33959     pPage->iKey = iKey;
33960     pPage->pNext = pCache->apHash[h];
33961     pPage->pCache = pCache;
33962     pPage->pLruPrev = 0;
33963     pPage->pLruNext = 0;
33964     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
33965     pCache->apHash[h] = pPage;
33966   }
33967
33968 fetch_out:
33969   if( pPage && iKey>pCache->iMaxKey ){
33970     pCache->iMaxKey = iKey;
33971   }
33972   if( createFlag==1 ) sqlite3EndBenignMalloc();
33973   pcache1LeaveMutex();
33974   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
33975 }
33976
33977
33978 /*
33979 ** Implementation of the sqlite3_pcache.xUnpin method.
33980 **
33981 ** Mark a page as unpinned (eligible for asynchronous recycling).
33982 */
33983 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
33984   PCache1 *pCache = (PCache1 *)p;
33985   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
33986  
33987   assert( pPage->pCache==pCache );
33988   pcache1EnterMutex();
33989
33990   /* It is an error to call this function if the page is already 
33991   ** part of the global LRU list.
33992   */
33993   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
33994   assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
33995
33996   if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
33997     pcache1RemoveFromHash(pPage);
33998     pcache1FreePage(pPage);
33999   }else{
34000     /* Add the page to the global LRU list. Normally, the page is added to
34001     ** the head of the list (last page to be recycled). However, if the 
34002     ** reuseUnlikely flag passed to this function is true, the page is added
34003     ** to the tail of the list (first page to be recycled).
34004     */
34005     if( pcache1.pLruHead ){
34006       pcache1.pLruHead->pLruPrev = pPage;
34007       pPage->pLruNext = pcache1.pLruHead;
34008       pcache1.pLruHead = pPage;
34009     }else{
34010       pcache1.pLruTail = pPage;
34011       pcache1.pLruHead = pPage;
34012     }
34013     pCache->nRecyclable++;
34014   }
34015
34016   pcache1LeaveMutex();
34017 }
34018
34019 /*
34020 ** Implementation of the sqlite3_pcache.xRekey method. 
34021 */
34022 static void pcache1Rekey(
34023   sqlite3_pcache *p,
34024   void *pPg,
34025   unsigned int iOld,
34026   unsigned int iNew
34027 ){
34028   PCache1 *pCache = (PCache1 *)p;
34029   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
34030   PgHdr1 **pp;
34031   unsigned int h; 
34032   assert( pPage->iKey==iOld );
34033   assert( pPage->pCache==pCache );
34034
34035   pcache1EnterMutex();
34036
34037   h = iOld%pCache->nHash;
34038   pp = &pCache->apHash[h];
34039   while( (*pp)!=pPage ){
34040     pp = &(*pp)->pNext;
34041   }
34042   *pp = pPage->pNext;
34043
34044   h = iNew%pCache->nHash;
34045   pPage->iKey = iNew;
34046   pPage->pNext = pCache->apHash[h];
34047   pCache->apHash[h] = pPage;
34048   if( iNew>pCache->iMaxKey ){
34049     pCache->iMaxKey = iNew;
34050   }
34051
34052   pcache1LeaveMutex();
34053 }
34054
34055 /*
34056 ** Implementation of the sqlite3_pcache.xTruncate method. 
34057 **
34058 ** Discard all unpinned pages in the cache with a page number equal to
34059 ** or greater than parameter iLimit. Any pinned pages with a page number
34060 ** equal to or greater than iLimit are implicitly unpinned.
34061 */
34062 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
34063   PCache1 *pCache = (PCache1 *)p;
34064   pcache1EnterMutex();
34065   if( iLimit<=pCache->iMaxKey ){
34066     pcache1TruncateUnsafe(pCache, iLimit);
34067     pCache->iMaxKey = iLimit-1;
34068   }
34069   pcache1LeaveMutex();
34070 }
34071
34072 /*
34073 ** Implementation of the sqlite3_pcache.xDestroy method. 
34074 **
34075 ** Destroy a cache allocated using pcache1Create().
34076 */
34077 static void pcache1Destroy(sqlite3_pcache *p){
34078   PCache1 *pCache = (PCache1 *)p;
34079   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
34080   pcache1EnterMutex();
34081   pcache1TruncateUnsafe(pCache, 0);
34082   pcache1.nMaxPage -= pCache->nMax;
34083   pcache1.nMinPage -= pCache->nMin;
34084   pcache1EnforceMaxPage();
34085   pcache1LeaveMutex();
34086   sqlite3_free(pCache->apHash);
34087   sqlite3_free(pCache);
34088 }
34089
34090 /*
34091 ** This function is called during initialization (sqlite3_initialize()) to
34092 ** install the default pluggable cache module, assuming the user has not
34093 ** already provided an alternative.
34094 */
34095 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
34096   static const sqlite3_pcache_methods defaultMethods = {
34097     0,                       /* pArg */
34098     pcache1Init,             /* xInit */
34099     pcache1Shutdown,         /* xShutdown */
34100     pcache1Create,           /* xCreate */
34101     pcache1Cachesize,        /* xCachesize */
34102     pcache1Pagecount,        /* xPagecount */
34103     pcache1Fetch,            /* xFetch */
34104     pcache1Unpin,            /* xUnpin */
34105     pcache1Rekey,            /* xRekey */
34106     pcache1Truncate,         /* xTruncate */
34107     pcache1Destroy           /* xDestroy */
34108   };
34109   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
34110 }
34111
34112 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
34113 /*
34114 ** This function is called to free superfluous dynamically allocated memory
34115 ** held by the pager system. Memory in use by any SQLite pager allocated
34116 ** by the current thread may be sqlite3_free()ed.
34117 **
34118 ** nReq is the number of bytes of memory required. Once this much has
34119 ** been released, the function returns. The return value is the total number 
34120 ** of bytes of memory released.
34121 */
34122 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
34123   int nFree = 0;
34124   if( pcache1.pStart==0 ){
34125     PgHdr1 *p;
34126     pcache1EnterMutex();
34127     while( (nReq<0 || nFree<nReq) && ((p=pcache1.pLruTail)!=0) ){
34128       nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
34129       pcache1PinPage(p);
34130       pcache1RemoveFromHash(p);
34131       pcache1FreePage(p);
34132     }
34133     pcache1LeaveMutex();
34134   }
34135   return nFree;
34136 }
34137 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
34138
34139 #ifdef SQLITE_TEST
34140 /*
34141 ** This function is used by test procedures to inspect the internal state
34142 ** of the global cache.
34143 */
34144 SQLITE_PRIVATE void sqlite3PcacheStats(
34145   int *pnCurrent,      /* OUT: Total number of pages cached */
34146   int *pnMax,          /* OUT: Global maximum cache size */
34147   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
34148   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
34149 ){
34150   PgHdr1 *p;
34151   int nRecyclable = 0;
34152   for(p=pcache1.pLruHead; p; p=p->pLruNext){
34153     nRecyclable++;
34154   }
34155   *pnCurrent = pcache1.nCurrentPage;
34156   *pnMax = pcache1.nMaxPage;
34157   *pnMin = pcache1.nMinPage;
34158   *pnRecyclable = nRecyclable;
34159 }
34160 #endif
34161
34162 /************** End of pcache1.c *********************************************/
34163 /************** Begin file rowset.c ******************************************/
34164 /*
34165 ** 2008 December 3
34166 **
34167 ** The author disclaims copyright to this source code.  In place of
34168 ** a legal notice, here is a blessing:
34169 **
34170 **    May you do good and not evil.
34171 **    May you find forgiveness for yourself and forgive others.
34172 **    May you share freely, never taking more than you give.
34173 **
34174 *************************************************************************
34175 **
34176 ** This module implements an object we call a "RowSet".
34177 **
34178 ** The RowSet object is a collection of rowids.  Rowids
34179 ** are inserted into the RowSet in an arbitrary order.  Inserts
34180 ** can be intermixed with tests to see if a given rowid has been
34181 ** previously inserted into the RowSet.
34182 **
34183 ** After all inserts are finished, it is possible to extract the
34184 ** elements of the RowSet in sorted order.  Once this extraction
34185 ** process has started, no new elements may be inserted.
34186 **
34187 ** Hence, the primitive operations for a RowSet are:
34188 **
34189 **    CREATE
34190 **    INSERT
34191 **    TEST
34192 **    SMALLEST
34193 **    DESTROY
34194 **
34195 ** The CREATE and DESTROY primitives are the constructor and destructor,
34196 ** obviously.  The INSERT primitive adds a new element to the RowSet.
34197 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
34198 ** extracts the least value from the RowSet.
34199 **
34200 ** The INSERT primitive might allocate additional memory.  Memory is
34201 ** allocated in chunks so most INSERTs do no allocation.  There is an 
34202 ** upper bound on the size of allocated memory.  No memory is freed
34203 ** until DESTROY.
34204 **
34205 ** The TEST primitive includes a "batch" number.  The TEST primitive
34206 ** will only see elements that were inserted before the last change
34207 ** in the batch number.  In other words, if an INSERT occurs between
34208 ** two TESTs where the TESTs have the same batch nubmer, then the
34209 ** value added by the INSERT will not be visible to the second TEST.
34210 ** The initial batch number is zero, so if the very first TEST contains
34211 ** a non-zero batch number, it will see all prior INSERTs.
34212 **
34213 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
34214 ** that is attempted.
34215 **
34216 ** The cost of an INSERT is roughly constant.  (Sometime new memory
34217 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
34218 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
34219 ** The cost of a TEST using the same batch number is O(logN).  The cost
34220 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
34221 ** primitives are constant time.  The cost of DESTROY is O(N).
34222 **
34223 ** There is an added cost of O(N) when switching between TEST and
34224 ** SMALLEST primitives.
34225 */
34226
34227
34228 /*
34229 ** Target size for allocation chunks.
34230 */
34231 #define ROWSET_ALLOCATION_SIZE 1024
34232
34233 /*
34234 ** The number of rowset entries per allocation chunk.
34235 */
34236 #define ROWSET_ENTRY_PER_CHUNK  \
34237                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
34238
34239 /*
34240 ** Each entry in a RowSet is an instance of the following object.
34241 */
34242 struct RowSetEntry {            
34243   i64 v;                        /* ROWID value for this entry */
34244   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
34245   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
34246 };
34247
34248 /*
34249 ** RowSetEntry objects are allocated in large chunks (instances of the
34250 ** following structure) to reduce memory allocation overhead.  The
34251 ** chunks are kept on a linked list so that they can be deallocated
34252 ** when the RowSet is destroyed.
34253 */
34254 struct RowSetChunk {
34255   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
34256   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
34257 };
34258
34259 /*
34260 ** A RowSet in an instance of the following structure.
34261 **
34262 ** A typedef of this structure if found in sqliteInt.h.
34263 */
34264 struct RowSet {
34265   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
34266   sqlite3 *db;                   /* The database connection */
34267   struct RowSetEntry *pEntry;    /* List of entries using pRight */
34268   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
34269   struct RowSetEntry *pFresh;    /* Source of new entry objects */
34270   struct RowSetEntry *pTree;     /* Binary tree of entries */
34271   u16 nFresh;                    /* Number of objects on pFresh */
34272   u8 isSorted;                   /* True if pEntry is sorted */
34273   u8 iBatch;                     /* Current insert batch */
34274 };
34275
34276 /*
34277 ** Turn bulk memory into a RowSet object.  N bytes of memory
34278 ** are available at pSpace.  The db pointer is used as a memory context
34279 ** for any subsequent allocations that need to occur.
34280 ** Return a pointer to the new RowSet object.
34281 **
34282 ** It must be the case that N is sufficient to make a Rowset.  If not
34283 ** an assertion fault occurs.
34284 ** 
34285 ** If N is larger than the minimum, use the surplus as an initial
34286 ** allocation of entries available to be filled.
34287 */
34288 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
34289   RowSet *p;
34290   assert( N >= ROUND8(sizeof(*p)) );
34291   p = pSpace;
34292   p->pChunk = 0;
34293   p->db = db;
34294   p->pEntry = 0;
34295   p->pLast = 0;
34296   p->pTree = 0;
34297   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
34298   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
34299   p->isSorted = 1;
34300   p->iBatch = 0;
34301   return p;
34302 }
34303
34304 /*
34305 ** Deallocate all chunks from a RowSet.  This frees all memory that
34306 ** the RowSet has allocated over its lifetime.  This routine is
34307 ** the destructor for the RowSet.
34308 */
34309 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
34310   struct RowSetChunk *pChunk, *pNextChunk;
34311   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
34312     pNextChunk = pChunk->pNextChunk;
34313     sqlite3DbFree(p->db, pChunk);
34314   }
34315   p->pChunk = 0;
34316   p->nFresh = 0;
34317   p->pEntry = 0;
34318   p->pLast = 0;
34319   p->pTree = 0;
34320   p->isSorted = 1;
34321 }
34322
34323 /*
34324 ** Insert a new value into a RowSet.
34325 **
34326 ** The mallocFailed flag of the database connection is set if a
34327 ** memory allocation fails.
34328 */
34329 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
34330   struct RowSetEntry *pEntry;  /* The new entry */
34331   struct RowSetEntry *pLast;   /* The last prior entry */
34332   assert( p!=0 );
34333   if( p->nFresh==0 ){
34334     struct RowSetChunk *pNew;
34335     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
34336     if( pNew==0 ){
34337       return;
34338     }
34339     pNew->pNextChunk = p->pChunk;
34340     p->pChunk = pNew;
34341     p->pFresh = pNew->aEntry;
34342     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
34343   }
34344   pEntry = p->pFresh++;
34345   p->nFresh--;
34346   pEntry->v = rowid;
34347   pEntry->pRight = 0;
34348   pLast = p->pLast;
34349   if( pLast ){
34350     if( p->isSorted && rowid<=pLast->v ){
34351       p->isSorted = 0;
34352     }
34353     pLast->pRight = pEntry;
34354   }else{
34355     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
34356     p->pEntry = pEntry;
34357   }
34358   p->pLast = pEntry;
34359 }
34360
34361 /*
34362 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
34363 **
34364 ** The input lists are connected via pRight pointers and are 
34365 ** assumed to each already be in sorted order.
34366 */
34367 static struct RowSetEntry *rowSetMerge(
34368   struct RowSetEntry *pA,    /* First sorted list to be merged */
34369   struct RowSetEntry *pB     /* Second sorted list to be merged */
34370 ){
34371   struct RowSetEntry head;
34372   struct RowSetEntry *pTail;
34373
34374   pTail = &head;
34375   while( pA && pB ){
34376     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
34377     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
34378     if( pA->v<pB->v ){
34379       pTail->pRight = pA;
34380       pA = pA->pRight;
34381       pTail = pTail->pRight;
34382     }else if( pB->v<pA->v ){
34383       pTail->pRight = pB;
34384       pB = pB->pRight;
34385       pTail = pTail->pRight;
34386     }else{
34387       pA = pA->pRight;
34388     }
34389   }
34390   if( pA ){
34391     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
34392     pTail->pRight = pA;
34393   }else{
34394     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
34395     pTail->pRight = pB;
34396   }
34397   return head.pRight;
34398 }
34399
34400 /*
34401 ** Sort all elements on the pEntry list of the RowSet into ascending order.
34402 */ 
34403 static void rowSetSort(RowSet *p){
34404   unsigned int i;
34405   struct RowSetEntry *pEntry;
34406   struct RowSetEntry *aBucket[40];
34407
34408   assert( p->isSorted==0 );
34409   memset(aBucket, 0, sizeof(aBucket));
34410   while( p->pEntry ){
34411     pEntry = p->pEntry;
34412     p->pEntry = pEntry->pRight;
34413     pEntry->pRight = 0;
34414     for(i=0; aBucket[i]; i++){
34415       pEntry = rowSetMerge(aBucket[i], pEntry);
34416       aBucket[i] = 0;
34417     }
34418     aBucket[i] = pEntry;
34419   }
34420   pEntry = 0;
34421   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
34422     pEntry = rowSetMerge(pEntry, aBucket[i]);
34423   }
34424   p->pEntry = pEntry;
34425   p->pLast = 0;
34426   p->isSorted = 1;
34427 }
34428
34429
34430 /*
34431 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
34432 ** Convert this tree into a linked list connected by the pRight pointers
34433 ** and return pointers to the first and last elements of the new list.
34434 */
34435 static void rowSetTreeToList(
34436   struct RowSetEntry *pIn,         /* Root of the input tree */
34437   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
34438   struct RowSetEntry **ppLast      /* Write tail of the output list here */
34439 ){
34440   assert( pIn!=0 );
34441   if( pIn->pLeft ){
34442     struct RowSetEntry *p;
34443     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
34444     p->pRight = pIn;
34445   }else{
34446     *ppFirst = pIn;
34447   }
34448   if( pIn->pRight ){
34449     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
34450   }else{
34451     *ppLast = pIn;
34452   }
34453   assert( (*ppLast)->pRight==0 );
34454 }
34455
34456
34457 /*
34458 ** Convert a sorted list of elements (connected by pRight) into a binary
34459 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
34460 ** node taken from the head of *ppList.  A depth of 2 means a tree with
34461 ** three nodes.  And so forth.
34462 **
34463 ** Use as many entries from the input list as required and update the
34464 ** *ppList to point to the unused elements of the list.  If the input
34465 ** list contains too few elements, then construct an incomplete tree
34466 ** and leave *ppList set to NULL.
34467 **
34468 ** Return a pointer to the root of the constructed binary tree.
34469 */
34470 static struct RowSetEntry *rowSetNDeepTree(
34471   struct RowSetEntry **ppList,
34472   int iDepth
34473 ){
34474   struct RowSetEntry *p;         /* Root of the new tree */
34475   struct RowSetEntry *pLeft;     /* Left subtree */
34476   if( *ppList==0 ){
34477     return 0;
34478   }
34479   if( iDepth==1 ){
34480     p = *ppList;
34481     *ppList = p->pRight;
34482     p->pLeft = p->pRight = 0;
34483     return p;
34484   }
34485   pLeft = rowSetNDeepTree(ppList, iDepth-1);
34486   p = *ppList;
34487   if( p==0 ){
34488     return pLeft;
34489   }
34490   p->pLeft = pLeft;
34491   *ppList = p->pRight;
34492   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
34493   return p;
34494 }
34495
34496 /*
34497 ** Convert a sorted list of elements into a binary tree. Make the tree
34498 ** as deep as it needs to be in order to contain the entire list.
34499 */
34500 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
34501   int iDepth;           /* Depth of the tree so far */
34502   struct RowSetEntry *p;       /* Current tree root */
34503   struct RowSetEntry *pLeft;   /* Left subtree */
34504
34505   assert( pList!=0 );
34506   p = pList;
34507   pList = p->pRight;
34508   p->pLeft = p->pRight = 0;
34509   for(iDepth=1; pList; iDepth++){
34510     pLeft = p;
34511     p = pList;
34512     pList = p->pRight;
34513     p->pLeft = pLeft;
34514     p->pRight = rowSetNDeepTree(&pList, iDepth);
34515   }
34516   return p;
34517 }
34518
34519 /*
34520 ** Convert the list in p->pEntry into a sorted list if it is not
34521 ** sorted already.  If there is a binary tree on p->pTree, then
34522 ** convert it into a list too and merge it into the p->pEntry list.
34523 */
34524 static void rowSetToList(RowSet *p){
34525   if( !p->isSorted ){
34526     rowSetSort(p);
34527   }
34528   if( p->pTree ){
34529     struct RowSetEntry *pHead, *pTail;
34530     rowSetTreeToList(p->pTree, &pHead, &pTail);
34531     p->pTree = 0;
34532     p->pEntry = rowSetMerge(p->pEntry, pHead);
34533   }
34534 }
34535
34536 /*
34537 ** Extract the smallest element from the RowSet.
34538 ** Write the element into *pRowid.  Return 1 on success.  Return
34539 ** 0 if the RowSet is already empty.
34540 **
34541 ** After this routine has been called, the sqlite3RowSetInsert()
34542 ** routine may not be called again.  
34543 */
34544 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
34545   rowSetToList(p);
34546   if( p->pEntry ){
34547     *pRowid = p->pEntry->v;
34548     p->pEntry = p->pEntry->pRight;
34549     if( p->pEntry==0 ){
34550       sqlite3RowSetClear(p);
34551     }
34552     return 1;
34553   }else{
34554     return 0;
34555   }
34556 }
34557
34558 /*
34559 ** Check to see if element iRowid was inserted into the the rowset as
34560 ** part of any insert batch prior to iBatch.  Return 1 or 0.
34561 */
34562 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
34563   struct RowSetEntry *p;
34564   if( iBatch!=pRowSet->iBatch ){
34565     if( pRowSet->pEntry ){
34566       rowSetToList(pRowSet);
34567       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
34568       pRowSet->pEntry = 0;
34569       pRowSet->pLast = 0;
34570     }
34571     pRowSet->iBatch = iBatch;
34572   }
34573   p = pRowSet->pTree;
34574   while( p ){
34575     if( p->v<iRowid ){
34576       p = p->pRight;
34577     }else if( p->v>iRowid ){
34578       p = p->pLeft;
34579     }else{
34580       return 1;
34581     }
34582   }
34583   return 0;
34584 }
34585
34586 /************** End of rowset.c **********************************************/
34587 /************** Begin file pager.c *******************************************/
34588 /*
34589 ** 2001 September 15
34590 **
34591 ** The author disclaims copyright to this source code.  In place of
34592 ** a legal notice, here is a blessing:
34593 **
34594 **    May you do good and not evil.
34595 **    May you find forgiveness for yourself and forgive others.
34596 **    May you share freely, never taking more than you give.
34597 **
34598 *************************************************************************
34599 ** This is the implementation of the page cache subsystem or "pager".
34600 ** 
34601 ** The pager is used to access a database disk file.  It implements
34602 ** atomic commit and rollback through the use of a journal file that
34603 ** is separate from the database file.  The pager also implements file
34604 ** locking to prevent two processes from writing the same database
34605 ** file simultaneously, or one process from reading the database while
34606 ** another is writing.
34607 */
34608 #ifndef SQLITE_OMIT_DISKIO
34609 /************** Include wal.h in the middle of pager.c ***********************/
34610 /************** Begin file wal.h *********************************************/
34611 /*
34612 ** 2010 February 1
34613 **
34614 ** The author disclaims copyright to this source code.  In place of
34615 ** a legal notice, here is a blessing:
34616 **
34617 **    May you do good and not evil.
34618 **    May you find forgiveness for yourself and forgive others.
34619 **    May you share freely, never taking more than you give.
34620 **
34621 *************************************************************************
34622 ** This header file defines the interface to the write-ahead logging 
34623 ** system. Refer to the comments below and the header comment attached to 
34624 ** the implementation of each function in log.c for further details.
34625 */
34626
34627 #ifndef _WAL_H_
34628 #define _WAL_H_
34629
34630
34631 #ifdef SQLITE_OMIT_WAL
34632 # define sqlite3WalOpen(x,y,z)                 0
34633 # define sqlite3WalClose(w,x,y,z)              0
34634 # define sqlite3WalBeginReadTransaction(y,z)   0
34635 # define sqlite3WalEndReadTransaction(z)
34636 # define sqlite3WalRead(v,w,x,y,z)             0
34637 # define sqlite3WalDbsize(y)                   0
34638 # define sqlite3WalBeginWriteTransaction(y)    0
34639 # define sqlite3WalEndWriteTransaction(x)      0
34640 # define sqlite3WalUndo(x,y,z)                 0
34641 # define sqlite3WalSavepoint(y,z)
34642 # define sqlite3WalSavepointUndo(y,z)          0
34643 # define sqlite3WalFrames(u,v,w,x,y,z)         0
34644 # define sqlite3WalCheckpoint(u,v,w,x)         0
34645 # define sqlite3WalCallback(z)                 0
34646 # define sqlite3WalExclusiveMode(y,z)          0
34647 # define sqlite3WalHeapMemory(z)               0
34648 #else
34649
34650 #define WAL_SAVEPOINT_NDATA 4
34651
34652 /* Connection to a write-ahead log (WAL) file. 
34653 ** There is one object of this type for each pager. 
34654 */
34655 typedef struct Wal Wal;
34656
34657 /* Open and close a connection to a write-ahead log. */
34658 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *zName, int, Wal**);
34659 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
34660
34661 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
34662 ** snapshot is like a read-transaction.  It is the state of the database
34663 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
34664 ** preserves the current state even if the other threads or processes
34665 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
34666 ** transaction and releases the lock.
34667 */
34668 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
34669 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
34670
34671 /* Read a page from the write-ahead log, if it is present. */
34672 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
34673
34674 /* If the WAL is not empty, return the size of the database. */
34675 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
34676
34677 /* Obtain or release the WRITER lock. */
34678 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
34679 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
34680
34681 /* Undo any frames written (but not committed) to the log */
34682 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
34683
34684 /* Return an integer that records the current (uncommitted) write
34685 ** position in the WAL */
34686 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
34687
34688 /* Move the write position of the WAL back to iFrame.  Called in
34689 ** response to a ROLLBACK TO command. */
34690 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
34691
34692 /* Write a frame or frames to the log. */
34693 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
34694
34695 /* Copy pages from the log to the database file */ 
34696 SQLITE_PRIVATE int sqlite3WalCheckpoint(
34697   Wal *pWal,                      /* Write-ahead log connection */
34698   int sync_flags,                 /* Flags to sync db file with (or 0) */
34699   int nBuf,                       /* Size of buffer nBuf */
34700   u8 *zBuf                        /* Temporary buffer to use */
34701 );
34702
34703 /* Return the value to pass to a sqlite3_wal_hook callback, the
34704 ** number of frames in the WAL at the point of the last commit since
34705 ** sqlite3WalCallback() was called.  If no commits have occurred since
34706 ** the last call, then return 0.
34707 */
34708 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
34709
34710 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
34711 ** by the pager layer on the database file.
34712 */
34713 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
34714
34715 /* Return true if the argument is non-NULL and the WAL module is using
34716 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
34717 ** WAL module is using shared-memory, return false. 
34718 */
34719 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
34720
34721 #endif /* ifndef SQLITE_OMIT_WAL */
34722 #endif /* _WAL_H_ */
34723
34724 /************** End of wal.h *************************************************/
34725 /************** Continuing where we left off in pager.c **********************/
34726
34727
34728 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
34729 **
34730 ** This comment block describes invariants that hold when using a rollback
34731 ** journal.  These invariants do not apply for journal_mode=WAL,
34732 ** journal_mode=MEMORY, or journal_mode=OFF.
34733 **
34734 ** Within this comment block, a page is deemed to have been synced
34735 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
34736 ** Otherwise, the page is not synced until the xSync method of the VFS
34737 ** is called successfully on the file containing the page.
34738 **
34739 ** Definition:  A page of the database file is said to be "overwriteable" if
34740 ** one or more of the following are true about the page:
34741 ** 
34742 **     (a)  The original content of the page as it was at the beginning of
34743 **          the transaction has been written into the rollback journal and
34744 **          synced.
34745 ** 
34746 **     (b)  The page was a freelist leaf page at the start of the transaction.
34747 ** 
34748 **     (c)  The page number is greater than the largest page that existed in
34749 **          the database file at the start of the transaction.
34750 ** 
34751 ** (1) A page of the database file is never overwritten unless one of the
34752 **     following are true:
34753 ** 
34754 **     (a) The page and all other pages on the same sector are overwriteable.
34755 ** 
34756 **     (b) The atomic page write optimization is enabled, and the entire
34757 **         transaction other than the update of the transaction sequence
34758 **         number consists of a single page change.
34759 ** 
34760 ** (2) The content of a page written into the rollback journal exactly matches
34761 **     both the content in the database when the rollback journal was written
34762 **     and the content in the database at the beginning of the current
34763 **     transaction.
34764 ** 
34765 ** (3) Writes to the database file are an integer multiple of the page size
34766 **     in length and are aligned on a page boundary.
34767 ** 
34768 ** (4) Reads from the database file are either aligned on a page boundary and
34769 **     an integer multiple of the page size in length or are taken from the
34770 **     first 100 bytes of the database file.
34771 ** 
34772 ** (5) All writes to the database file are synced prior to the rollback journal
34773 **     being deleted, truncated, or zeroed.
34774 ** 
34775 ** (6) If a master journal file is used, then all writes to the database file
34776 **     are synced prior to the master journal being deleted.
34777 ** 
34778 ** Definition: Two databases (or the same database at two points it time)
34779 ** are said to be "logically equivalent" if they give the same answer to
34780 ** all queries.  Note in particular the the content of freelist leaf
34781 ** pages can be changed arbitarily without effecting the logical equivalence
34782 ** of the database.
34783 ** 
34784 ** (7) At any time, if any subset, including the empty set and the total set,
34785 **     of the unsynced changes to a rollback journal are removed and the 
34786 **     journal is rolled back, the resulting database file will be logical
34787 **     equivalent to the database file at the beginning of the transaction.
34788 ** 
34789 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
34790 **     is called to restore the database file to the same size it was at
34791 **     the beginning of the transaction.  (In some VFSes, the xTruncate
34792 **     method is a no-op, but that does not change the fact the SQLite will
34793 **     invoke it.)
34794 ** 
34795 ** (9) Whenever the database file is modified, at least one bit in the range
34796 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
34797 **     the EXCLUSIVE lock, thus signaling other connections on the same
34798 **     database to flush their caches.
34799 **
34800 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
34801 **      than one billion transactions.
34802 **
34803 ** (11) A database file is well-formed at the beginning and at the conclusion
34804 **      of every transaction.
34805 **
34806 ** (12) An EXCLUSIVE lock is held on the database file when writing to
34807 **      the database file.
34808 **
34809 ** (13) A SHARED lock is held on the database file while reading any
34810 **      content out of the database file.
34811 **
34812 ******************************************************************************/
34813
34814 /*
34815 ** Macros for troubleshooting.  Normally turned off
34816 */
34817 #if 0
34818 int sqlite3PagerTrace=1;  /* True to enable tracing */
34819 #define sqlite3DebugPrintf printf
34820 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
34821 #else
34822 #define PAGERTRACE(X)
34823 #endif
34824
34825 /*
34826 ** The following two macros are used within the PAGERTRACE() macros above
34827 ** to print out file-descriptors. 
34828 **
34829 ** PAGERID() takes a pointer to a Pager struct as its argument. The
34830 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
34831 ** struct as its argument.
34832 */
34833 #define PAGERID(p) ((int)(p->fd))
34834 #define FILEHANDLEID(fd) ((int)fd)
34835
34836 /*
34837 ** The Pager.eState variable stores the current 'state' of a pager. A
34838 ** pager may be in any one of the seven states shown in the following
34839 ** state diagram.
34840 **
34841 **                            OPEN <------+------+
34842 **                              |         |      |
34843 **                              V         |      |
34844 **               +---------> READER-------+      |
34845 **               |              |                |
34846 **               |              V                |
34847 **               |<-------WRITER_LOCKED------> ERROR
34848 **               |              |                ^  
34849 **               |              V                |
34850 **               |<------WRITER_CACHEMOD-------->|
34851 **               |              |                |
34852 **               |              V                |
34853 **               |<-------WRITER_DBMOD---------->|
34854 **               |              |                |
34855 **               |              V                |
34856 **               +<------WRITER_FINISHED-------->+
34857 **
34858 **
34859 ** List of state transitions and the C [function] that performs each:
34860 ** 
34861 **   OPEN              -> READER              [sqlite3PagerSharedLock]
34862 **   READER            -> OPEN                [pager_unlock]
34863 **
34864 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
34865 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
34866 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
34867 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
34868 **   WRITER_***        -> READER              [pager_end_transaction]
34869 **
34870 **   WRITER_***        -> ERROR               [pager_error]
34871 **   ERROR             -> OPEN                [pager_unlock]
34872 ** 
34873 **
34874 **  OPEN:
34875 **
34876 **    The pager starts up in this state. Nothing is guaranteed in this
34877 **    state - the file may or may not be locked and the database size is
34878 **    unknown. The database may not be read or written.
34879 **
34880 **    * No read or write transaction is active.
34881 **    * Any lock, or no lock at all, may be held on the database file.
34882 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
34883 **
34884 **  READER:
34885 **
34886 **    In this state all the requirements for reading the database in 
34887 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
34888 **    was) in exclusive-locking mode, a user-level read transaction is 
34889 **    open. The database size is known in this state.
34890 **
34891 **    A connection running with locking_mode=normal enters this state when
34892 **    it opens a read-transaction on the database and returns to state
34893 **    OPEN after the read-transaction is completed. However a connection
34894 **    running in locking_mode=exclusive (including temp databases) remains in
34895 **    this state even after the read-transaction is closed. The only way
34896 **    a locking_mode=exclusive connection can transition from READER to OPEN
34897 **    is via the ERROR state (see below).
34898 ** 
34899 **    * A read transaction may be active (but a write-transaction cannot).
34900 **    * A SHARED or greater lock is held on the database file.
34901 **    * The dbSize variable may be trusted (even if a user-level read 
34902 **      transaction is not active). The dbOrigSize and dbFileSize variables
34903 **      may not be trusted at this point.
34904 **    * If the database is a WAL database, then the WAL connection is open.
34905 **    * Even if a read-transaction is not open, it is guaranteed that 
34906 **      there is no hot-journal in the file-system.
34907 **
34908 **  WRITER_LOCKED:
34909 **
34910 **    The pager moves to this state from READER when a write-transaction
34911 **    is first opened on the database. In WRITER_LOCKED state, all locks 
34912 **    required to start a write-transaction are held, but no actual 
34913 **    modifications to the cache or database have taken place.
34914 **
34915 **    In rollback mode, a RESERVED or (if the transaction was opened with 
34916 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
34917 **    moving to this state, but the journal file is not written to or opened 
34918 **    to in this state. If the transaction is committed or rolled back while 
34919 **    in WRITER_LOCKED state, all that is required is to unlock the database 
34920 **    file.
34921 **
34922 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
34923 **    If the connection is running with locking_mode=exclusive, an attempt
34924 **    is made to obtain an EXCLUSIVE lock on the database file.
34925 **
34926 **    * A write transaction is active.
34927 **    * If the connection is open in rollback-mode, a RESERVED or greater 
34928 **      lock is held on the database file.
34929 **    * If the connection is open in WAL-mode, a WAL write transaction
34930 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
34931 **      called).
34932 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
34933 **    * The contents of the pager cache have not been modified.
34934 **    * The journal file may or may not be open.
34935 **    * Nothing (not even the first header) has been written to the journal.
34936 **
34937 **  WRITER_CACHEMOD:
34938 **
34939 **    A pager moves from WRITER_LOCKED state to this state when a page is
34940 **    first modified by the upper layer. In rollback mode the journal file
34941 **    is opened (if it is not already open) and a header written to the
34942 **    start of it. The database file on disk has not been modified.
34943 **
34944 **    * A write transaction is active.
34945 **    * A RESERVED or greater lock is held on the database file.
34946 **    * The journal file is open and the first header has been written 
34947 **      to it, but the header has not been synced to disk.
34948 **    * The contents of the page cache have been modified.
34949 **
34950 **  WRITER_DBMOD:
34951 **
34952 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
34953 **    when it modifies the contents of the database file. WAL connections
34954 **    never enter this state (since they do not modify the database file,
34955 **    just the log file).
34956 **
34957 **    * A write transaction is active.
34958 **    * An EXCLUSIVE or greater lock is held on the database file.
34959 **    * The journal file is open and the first header has been written 
34960 **      and synced to disk.
34961 **    * The contents of the page cache have been modified (and possibly
34962 **      written to disk).
34963 **
34964 **  WRITER_FINISHED:
34965 **
34966 **    It is not possible for a WAL connection to enter this state.
34967 **
34968 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
34969 **    state after the entire transaction has been successfully written into the
34970 **    database file. In this state the transaction may be committed simply
34971 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
34972 **    not possible to modify the database further. At this point, the upper 
34973 **    layer must either commit or rollback the transaction.
34974 **
34975 **    * A write transaction is active.
34976 **    * An EXCLUSIVE or greater lock is held on the database file.
34977 **    * All writing and syncing of journal and database data has finished.
34978 **      If no error occured, all that remains is to finalize the journal to
34979 **      commit the transaction. If an error did occur, the caller will need
34980 **      to rollback the transaction. 
34981 **
34982 **  ERROR:
34983 **
34984 **    The ERROR state is entered when an IO or disk-full error (including
34985 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
34986 **    difficult to be sure that the in-memory pager state (cache contents, 
34987 **    db size etc.) are consistent with the contents of the file-system.
34988 **
34989 **    Temporary pager files may enter the ERROR state, but in-memory pagers
34990 **    cannot.
34991 **
34992 **    For example, if an IO error occurs while performing a rollback, 
34993 **    the contents of the page-cache may be left in an inconsistent state.
34994 **    At this point it would be dangerous to change back to READER state
34995 **    (as usually happens after a rollback). Any subsequent readers might
34996 **    report database corruption (due to the inconsistent cache), and if
34997 **    they upgrade to writers, they may inadvertently corrupt the database
34998 **    file. To avoid this hazard, the pager switches into the ERROR state
34999 **    instead of READER following such an error.
35000 **
35001 **    Once it has entered the ERROR state, any attempt to use the pager
35002 **    to read or write data returns an error. Eventually, once all 
35003 **    outstanding transactions have been abandoned, the pager is able to
35004 **    transition back to OPEN state, discarding the contents of the 
35005 **    page-cache and any other in-memory state at the same time. Everything
35006 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
35007 **    when a read-transaction is next opened on the pager (transitioning
35008 **    the pager into READER state). At that point the system has recovered 
35009 **    from the error.
35010 **
35011 **    Specifically, the pager jumps into the ERROR state if:
35012 **
35013 **      1. An error occurs while attempting a rollback. This happens in
35014 **         function sqlite3PagerRollback().
35015 **
35016 **      2. An error occurs while attempting to finalize a journal file
35017 **         following a commit in function sqlite3PagerCommitPhaseTwo().
35018 **
35019 **      3. An error occurs while attempting to write to the journal or
35020 **         database file in function pagerStress() in order to free up
35021 **         memory.
35022 **
35023 **    In other cases, the error is returned to the b-tree layer. The b-tree
35024 **    layer then attempts a rollback operation. If the error condition 
35025 **    persists, the pager enters the ERROR state via condition (1) above.
35026 **
35027 **    Condition (3) is necessary because it can be triggered by a read-only
35028 **    statement executed within a transaction. In this case, if the error
35029 **    code were simply returned to the user, the b-tree layer would not
35030 **    automatically attempt a rollback, as it assumes that an error in a
35031 **    read-only statement cannot leave the pager in an internally inconsistent 
35032 **    state.
35033 **
35034 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
35035 **    * There are one or more outstanding references to pages (after the
35036 **      last reference is dropped the pager should move back to OPEN state).
35037 **    * The pager is not an in-memory pager.
35038 **    
35039 **
35040 ** Notes:
35041 **
35042 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
35043 **     connection is open in WAL mode. A WAL connection is always in one
35044 **     of the first four states.
35045 **
35046 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
35047 **     state. There are two exceptions: immediately after exclusive-mode has
35048 **     been turned on (and before any read or write transactions are 
35049 **     executed), and when the pager is leaving the "error state".
35050 **
35051 **   * See also: assert_pager_state().
35052 */
35053 #define PAGER_OPEN                  0
35054 #define PAGER_READER                1
35055 #define PAGER_WRITER_LOCKED         2
35056 #define PAGER_WRITER_CACHEMOD       3
35057 #define PAGER_WRITER_DBMOD          4
35058 #define PAGER_WRITER_FINISHED       5
35059 #define PAGER_ERROR                 6
35060
35061 /*
35062 ** The Pager.eLock variable is almost always set to one of the 
35063 ** following locking-states, according to the lock currently held on
35064 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
35065 ** This variable is kept up to date as locks are taken and released by
35066 ** the pagerLockDb() and pagerUnlockDb() wrappers.
35067 **
35068 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
35069 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
35070 ** the operation was successful. In these circumstances pagerLockDb() and
35071 ** pagerUnlockDb() take a conservative approach - eLock is always updated
35072 ** when unlocking the file, and only updated when locking the file if the
35073 ** VFS call is successful. This way, the Pager.eLock variable may be set
35074 ** to a less exclusive (lower) value than the lock that is actually held
35075 ** at the system level, but it is never set to a more exclusive value.
35076 **
35077 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
35078 ** be a few redundant xLock() calls or a lock may be held for longer than
35079 ** required, but nothing really goes wrong.
35080 **
35081 ** The exception is when the database file is unlocked as the pager moves
35082 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
35083 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
35084 ** transition, by the same pager or any other). If the call to xUnlock()
35085 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
35086 ** can confuse the call to xCheckReservedLock() call made later as part
35087 ** of hot-journal detection.
35088 **
35089 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
35090 ** lock held by this process or any others". So xCheckReservedLock may 
35091 ** return true because the caller itself is holding an EXCLUSIVE lock (but
35092 ** doesn't know it because of a previous error in xUnlock). If this happens
35093 ** a hot-journal may be mistaken for a journal being created by an active
35094 ** transaction in another process, causing SQLite to read from the database
35095 ** without rolling it back.
35096 **
35097 ** To work around this, if a call to xUnlock() fails when unlocking the
35098 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
35099 ** is only changed back to a real locking state after a successful call
35100 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
35101 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
35102 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
35103 ** lock on the database file before attempting to roll it back. See function
35104 ** PagerSharedLock() for more detail.
35105 **
35106 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
35107 ** PAGER_OPEN state.
35108 */
35109 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
35110
35111 /*
35112 ** A macro used for invoking the codec if there is one
35113 */
35114 #ifdef SQLITE_HAS_CODEC
35115 # define CODEC1(P,D,N,X,E) \
35116     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
35117 # define CODEC2(P,D,N,X,E,O) \
35118     if( P->xCodec==0 ){ O=(char*)D; }else \
35119     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
35120 #else
35121 # define CODEC1(P,D,N,X,E)   /* NO-OP */
35122 # define CODEC2(P,D,N,X,E,O) O=(char*)D
35123 #endif
35124
35125 /*
35126 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
35127 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
35128 ** This could conceivably cause corruption following a power failure on
35129 ** such a system. This is currently an undocumented limit.
35130 */
35131 #define MAX_SECTOR_SIZE 0x10000
35132
35133 /*
35134 ** An instance of the following structure is allocated for each active
35135 ** savepoint and statement transaction in the system. All such structures
35136 ** are stored in the Pager.aSavepoint[] array, which is allocated and
35137 ** resized using sqlite3Realloc().
35138 **
35139 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
35140 ** set to 0. If a journal-header is written into the main journal while
35141 ** the savepoint is active, then iHdrOffset is set to the byte offset 
35142 ** immediately following the last journal record written into the main
35143 ** journal before the journal-header. This is required during savepoint
35144 ** rollback (see pagerPlaybackSavepoint()).
35145 */
35146 typedef struct PagerSavepoint PagerSavepoint;
35147 struct PagerSavepoint {
35148   i64 iOffset;                 /* Starting offset in main journal */
35149   i64 iHdrOffset;              /* See above */
35150   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
35151   Pgno nOrig;                  /* Original number of pages in file */
35152   Pgno iSubRec;                /* Index of first record in sub-journal */
35153 #ifndef SQLITE_OMIT_WAL
35154   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
35155 #endif
35156 };
35157
35158 /*
35159 ** A open page cache is an instance of struct Pager. A description of
35160 ** some of the more important member variables follows:
35161 **
35162 ** eState
35163 **
35164 **   The current 'state' of the pager object. See the comment and state
35165 **   diagram above for a description of the pager state.
35166 **
35167 ** eLock
35168 **
35169 **   For a real on-disk database, the current lock held on the database file -
35170 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
35171 **
35172 **   For a temporary or in-memory database (neither of which require any
35173 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
35174 **   databases always have Pager.exclusiveMode==1, this tricks the pager
35175 **   logic into thinking that it already has all the locks it will ever
35176 **   need (and no reason to release them).
35177 **
35178 **   In some (obscure) circumstances, this variable may also be set to
35179 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
35180 **   details.
35181 **
35182 ** changeCountDone
35183 **
35184 **   This boolean variable is used to make sure that the change-counter 
35185 **   (the 4-byte header field at byte offset 24 of the database file) is 
35186 **   not updated more often than necessary. 
35187 **
35188 **   It is set to true when the change-counter field is updated, which 
35189 **   can only happen if an exclusive lock is held on the database file.
35190 **   It is cleared (set to false) whenever an exclusive lock is 
35191 **   relinquished on the database file. Each time a transaction is committed,
35192 **   The changeCountDone flag is inspected. If it is true, the work of
35193 **   updating the change-counter is omitted for the current transaction.
35194 **
35195 **   This mechanism means that when running in exclusive mode, a connection 
35196 **   need only update the change-counter once, for the first transaction
35197 **   committed.
35198 **
35199 ** setMaster
35200 **
35201 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
35202 **   (or may not) specify a master-journal name to be written into the 
35203 **   journal file before it is synced to disk.
35204 **
35205 **   Whether or not a journal file contains a master-journal pointer affects 
35206 **   the way in which the journal file is finalized after the transaction is 
35207 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
35208 **   If a journal file does not contain a master-journal pointer, it is
35209 **   finalized by overwriting the first journal header with zeroes. If
35210 **   it does contain a master-journal pointer the journal file is finalized 
35211 **   by truncating it to zero bytes, just as if the connection were 
35212 **   running in "journal_mode=truncate" mode.
35213 **
35214 **   Journal files that contain master journal pointers cannot be finalized
35215 **   simply by overwriting the first journal-header with zeroes, as the
35216 **   master journal pointer could interfere with hot-journal rollback of any
35217 **   subsequently interrupted transaction that reuses the journal file.
35218 **
35219 **   The flag is cleared as soon as the journal file is finalized (either
35220 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
35221 **   journal file from being successfully finalized, the setMaster flag
35222 **   is cleared anyway (and the pager will move to ERROR state).
35223 **
35224 ** doNotSpill, doNotSyncSpill
35225 **
35226 **   These two boolean variables control the behaviour of cache-spills
35227 **   (calls made by the pcache module to the pagerStress() routine to
35228 **   write cached data to the file-system in order to free up memory).
35229 **
35230 **   When doNotSpill is non-zero, writing to the database from pagerStress()
35231 **   is disabled altogether. This is done in a very obscure case that
35232 **   comes up during savepoint rollback that requires the pcache module
35233 **   to allocate a new page to prevent the journal file from being written
35234 **   while it is being traversed by code in pager_playback().
35235 ** 
35236 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
35237 **   is permitted, but syncing the journal file is not. This flag is set
35238 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
35239 **   the database page-size in order to prevent a journal sync from happening 
35240 **   in between the journalling of two pages on the same sector. 
35241 **
35242 ** subjInMemory
35243 **
35244 **   This is a boolean variable. If true, then any required sub-journal
35245 **   is opened as an in-memory journal file. If false, then in-memory
35246 **   sub-journals are only used for in-memory pager files.
35247 **
35248 **   This variable is updated by the upper layer each time a new 
35249 **   write-transaction is opened.
35250 **
35251 ** dbSize, dbOrigSize, dbFileSize
35252 **
35253 **   Variable dbSize is set to the number of pages in the database file.
35254 **   It is valid in PAGER_READER and higher states (all states except for
35255 **   OPEN and ERROR). 
35256 **
35257 **   dbSize is set based on the size of the database file, which may be 
35258 **   larger than the size of the database (the value stored at offset
35259 **   28 of the database header by the btree). If the size of the file
35260 **   is not an integer multiple of the page-size, the value stored in
35261 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
35262 **   Except, any file that is greater than 0 bytes in size is considered
35263 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
35264 **   to dbSize==1).
35265 **
35266 **   During a write-transaction, if pages with page-numbers greater than
35267 **   dbSize are modified in the cache, dbSize is updated accordingly.
35268 **   Similarly, if the database is truncated using PagerTruncateImage(), 
35269 **   dbSize is updated.
35270 **
35271 **   Variables dbOrigSize and dbFileSize are valid in states 
35272 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
35273 **   variable at the start of the transaction. It is used during rollback,
35274 **   and to determine whether or not pages need to be journalled before
35275 **   being modified.
35276 **
35277 **   Throughout a write-transaction, dbFileSize contains the size of
35278 **   the file on disk in pages. It is set to a copy of dbSize when the
35279 **   write-transaction is first opened, and updated when VFS calls are made
35280 **   to write or truncate the database file on disk. 
35281 **
35282 **   The only reason the dbFileSize variable is required is to suppress 
35283 **   unnecessary calls to xTruncate() after committing a transaction. If, 
35284 **   when a transaction is committed, the dbFileSize variable indicates 
35285 **   that the database file is larger than the database image (Pager.dbSize), 
35286 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
35287 **   to measure the database file on disk, and then truncates it if required.
35288 **   dbFileSize is not used when rolling back a transaction. In this case
35289 **   pager_truncate() is called unconditionally (which means there may be
35290 **   a call to xFilesize() that is not strictly required). In either case,
35291 **   pager_truncate() may cause the file to become smaller or larger.
35292 **
35293 ** dbHintSize
35294 **
35295 **   The dbHintSize variable is used to limit the number of calls made to
35296 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
35297 **
35298 **   dbHintSize is set to a copy of the dbSize variable when a
35299 **   write-transaction is opened (at the same time as dbFileSize and
35300 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
35301 **   dbHintSize is increased to the number of pages that correspond to the
35302 **   size-hint passed to the method call. See pager_write_pagelist() for 
35303 **   details.
35304 **
35305 ** errCode
35306 **
35307 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
35308 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
35309 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
35310 **   sub-codes.
35311 */
35312 struct Pager {
35313   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
35314   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
35315   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
35316   u8 useJournal;              /* Use a rollback journal on this file */
35317   u8 noReadlock;              /* Do not bother to obtain readlocks */
35318   u8 noSync;                  /* Do not sync the journal if true */
35319   u8 fullSync;                /* Do extra syncs of the journal for robustness */
35320   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
35321   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
35322   u8 tempFile;                /* zFilename is a temporary file */
35323   u8 readOnly;                /* True for a read-only database */
35324   u8 memDb;                   /* True to inhibit all file I/O */
35325
35326   /**************************************************************************
35327   ** The following block contains those class members that change during
35328   ** routine opertion.  Class members not in this block are either fixed
35329   ** when the pager is first created or else only change when there is a
35330   ** significant mode change (such as changing the page_size, locking_mode,
35331   ** or the journal_mode).  From another view, these class members describe
35332   ** the "state" of the pager, while other class members describe the
35333   ** "configuration" of the pager.
35334   */
35335   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
35336   u8 eLock;                   /* Current lock held on database file */
35337   u8 changeCountDone;         /* Set after incrementing the change-counter */
35338   u8 setMaster;               /* True if a m-j name has been written to jrnl */
35339   u8 doNotSpill;              /* Do not spill the cache when non-zero */
35340   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
35341   u8 subjInMemory;            /* True to use in-memory sub-journals */
35342   Pgno dbSize;                /* Number of pages in the database */
35343   Pgno dbOrigSize;            /* dbSize before the current transaction */
35344   Pgno dbFileSize;            /* Number of pages in the database file */
35345   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
35346   int errCode;                /* One of several kinds of errors */
35347   int nRec;                   /* Pages journalled since last j-header written */
35348   u32 cksumInit;              /* Quasi-random value added to every checksum */
35349   u32 nSubRec;                /* Number of records written to sub-journal */
35350   Bitvec *pInJournal;         /* One bit for each page in the database file */
35351   sqlite3_file *fd;           /* File descriptor for database */
35352   sqlite3_file *jfd;          /* File descriptor for main journal */
35353   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
35354   i64 journalOff;             /* Current write offset in the journal file */
35355   i64 journalHdr;             /* Byte offset to previous journal header */
35356   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
35357   PagerSavepoint *aSavepoint; /* Array of active savepoints */
35358   int nSavepoint;             /* Number of elements in aSavepoint[] */
35359   char dbFileVers[16];        /* Changes whenever database file changes */
35360   /*
35361   ** End of the routinely-changing class members
35362   ***************************************************************************/
35363
35364   u16 nExtra;                 /* Add this many bytes to each in-memory page */
35365   i16 nReserve;               /* Number of unused bytes at end of each page */
35366   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
35367   u32 sectorSize;             /* Assumed sector size during rollback */
35368   int pageSize;               /* Number of bytes in a page */
35369   Pgno mxPgno;                /* Maximum allowed size of the database */
35370   i64 journalSizeLimit;       /* Size limit for persistent journal files */
35371   char *zFilename;            /* Name of the database file */
35372   char *zJournal;             /* Name of the journal file */
35373   int (*xBusyHandler)(void*); /* Function to call when busy */
35374   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
35375 #ifdef SQLITE_TEST
35376   int nHit, nMiss;            /* Cache hits and missing */
35377   int nRead, nWrite;          /* Database pages read/written */
35378 #endif
35379   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
35380 #ifdef SQLITE_HAS_CODEC
35381   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
35382   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
35383   void (*xCodecFree)(void*);             /* Destructor for the codec */
35384   void *pCodec;               /* First argument to xCodec... methods */
35385 #endif
35386   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
35387   PCache *pPCache;            /* Pointer to page cache object */
35388 #ifndef SQLITE_OMIT_WAL
35389   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
35390   char *zWal;                 /* File name for write-ahead log */
35391 #endif
35392 };
35393
35394 /*
35395 ** The following global variables hold counters used for
35396 ** testing purposes only.  These variables do not exist in
35397 ** a non-testing build.  These variables are not thread-safe.
35398 */
35399 #ifdef SQLITE_TEST
35400 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
35401 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
35402 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
35403 # define PAGER_INCR(v)  v++
35404 #else
35405 # define PAGER_INCR(v)
35406 #endif
35407
35408
35409
35410 /*
35411 ** Journal files begin with the following magic string.  The data
35412 ** was obtained from /dev/random.  It is used only as a sanity check.
35413 **
35414 ** Since version 2.8.0, the journal format contains additional sanity
35415 ** checking information.  If the power fails while the journal is being
35416 ** written, semi-random garbage data might appear in the journal
35417 ** file after power is restored.  If an attempt is then made
35418 ** to roll the journal back, the database could be corrupted.  The additional
35419 ** sanity checking data is an attempt to discover the garbage in the
35420 ** journal and ignore it.
35421 **
35422 ** The sanity checking information for the new journal format consists
35423 ** of a 32-bit checksum on each page of data.  The checksum covers both
35424 ** the page number and the pPager->pageSize bytes of data for the page.
35425 ** This cksum is initialized to a 32-bit random value that appears in the
35426 ** journal file right after the header.  The random initializer is important,
35427 ** because garbage data that appears at the end of a journal is likely
35428 ** data that was once in other files that have now been deleted.  If the
35429 ** garbage data came from an obsolete journal file, the checksums might
35430 ** be correct.  But by initializing the checksum to random value which
35431 ** is different for every journal, we minimize that risk.
35432 */
35433 static const unsigned char aJournalMagic[] = {
35434   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
35435 };
35436
35437 /*
35438 ** The size of the of each page record in the journal is given by
35439 ** the following macro.
35440 */
35441 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
35442
35443 /*
35444 ** The journal header size for this pager. This is usually the same 
35445 ** size as a single disk sector. See also setSectorSize().
35446 */
35447 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
35448
35449 /*
35450 ** The macro MEMDB is true if we are dealing with an in-memory database.
35451 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
35452 ** the value of MEMDB will be a constant and the compiler will optimize
35453 ** out code that would never execute.
35454 */
35455 #ifdef SQLITE_OMIT_MEMORYDB
35456 # define MEMDB 0
35457 #else
35458 # define MEMDB pPager->memDb
35459 #endif
35460
35461 /*
35462 ** The maximum legal page number is (2^31 - 1).
35463 */
35464 #define PAGER_MAX_PGNO 2147483647
35465
35466 /*
35467 ** The argument to this macro is a file descriptor (type sqlite3_file*).
35468 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
35469 **
35470 ** This is so that expressions can be written as:
35471 **
35472 **   if( isOpen(pPager->jfd) ){ ...
35473 **
35474 ** instead of
35475 **
35476 **   if( pPager->jfd->pMethods ){ ...
35477 */
35478 #define isOpen(pFd) ((pFd)->pMethods)
35479
35480 /*
35481 ** Return true if this pager uses a write-ahead log instead of the usual
35482 ** rollback journal. Otherwise false.
35483 */
35484 #ifndef SQLITE_OMIT_WAL
35485 static int pagerUseWal(Pager *pPager){
35486   return (pPager->pWal!=0);
35487 }
35488 #else
35489 # define pagerUseWal(x) 0
35490 # define pagerRollbackWal(x) 0
35491 # define pagerWalFrames(v,w,x,y,z) 0
35492 # define pagerOpenWalIfPresent(z) SQLITE_OK
35493 # define pagerBeginReadTransaction(z) SQLITE_OK
35494 #endif
35495
35496 #ifndef NDEBUG 
35497 /*
35498 ** Usage:
35499 **
35500 **   assert( assert_pager_state(pPager) );
35501 **
35502 ** This function runs many asserts to try to find inconsistencies in
35503 ** the internal state of the Pager object.
35504 */
35505 static int assert_pager_state(Pager *p){
35506   Pager *pPager = p;
35507
35508   /* State must be valid. */
35509   assert( p->eState==PAGER_OPEN
35510        || p->eState==PAGER_READER
35511        || p->eState==PAGER_WRITER_LOCKED
35512        || p->eState==PAGER_WRITER_CACHEMOD
35513        || p->eState==PAGER_WRITER_DBMOD
35514        || p->eState==PAGER_WRITER_FINISHED
35515        || p->eState==PAGER_ERROR
35516   );
35517
35518   /* Regardless of the current state, a temp-file connection always behaves
35519   ** as if it has an exclusive lock on the database file. It never updates
35520   ** the change-counter field, so the changeCountDone flag is always set.
35521   */
35522   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
35523   assert( p->tempFile==0 || pPager->changeCountDone );
35524
35525   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
35526   ** And if the journal-mode is "OFF", the journal file must not be open.
35527   */
35528   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
35529   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
35530
35531   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
35532   ** this means an in-memory pager performs no IO at all, it cannot encounter 
35533   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
35534   ** a journal file. (although the in-memory journal implementation may 
35535   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
35536   ** is therefore not possible for an in-memory pager to enter the ERROR 
35537   ** state.
35538   */
35539   if( MEMDB ){
35540     assert( p->noSync );
35541     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
35542          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
35543     );
35544     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
35545     assert( pagerUseWal(p)==0 );
35546   }
35547
35548   /* If changeCountDone is set, a RESERVED lock or greater must be held
35549   ** on the file.
35550   */
35551   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
35552   assert( p->eLock!=PENDING_LOCK );
35553
35554   switch( p->eState ){
35555     case PAGER_OPEN:
35556       assert( !MEMDB );
35557       assert( pPager->errCode==SQLITE_OK );
35558       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
35559       break;
35560
35561     case PAGER_READER:
35562       assert( pPager->errCode==SQLITE_OK );
35563       assert( p->eLock!=UNKNOWN_LOCK );
35564       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
35565       break;
35566
35567     case PAGER_WRITER_LOCKED:
35568       assert( p->eLock!=UNKNOWN_LOCK );
35569       assert( pPager->errCode==SQLITE_OK );
35570       if( !pagerUseWal(pPager) ){
35571         assert( p->eLock>=RESERVED_LOCK );
35572       }
35573       assert( pPager->dbSize==pPager->dbOrigSize );
35574       assert( pPager->dbOrigSize==pPager->dbFileSize );
35575       assert( pPager->dbOrigSize==pPager->dbHintSize );
35576       assert( pPager->setMaster==0 );
35577       break;
35578
35579     case PAGER_WRITER_CACHEMOD:
35580       assert( p->eLock!=UNKNOWN_LOCK );
35581       assert( pPager->errCode==SQLITE_OK );
35582       if( !pagerUseWal(pPager) ){
35583         /* It is possible that if journal_mode=wal here that neither the
35584         ** journal file nor the WAL file are open. This happens during
35585         ** a rollback transaction that switches from journal_mode=off
35586         ** to journal_mode=wal.
35587         */
35588         assert( p->eLock>=RESERVED_LOCK );
35589         assert( isOpen(p->jfd) 
35590              || p->journalMode==PAGER_JOURNALMODE_OFF 
35591              || p->journalMode==PAGER_JOURNALMODE_WAL 
35592         );
35593       }
35594       assert( pPager->dbOrigSize==pPager->dbFileSize );
35595       assert( pPager->dbOrigSize==pPager->dbHintSize );
35596       break;
35597
35598     case PAGER_WRITER_DBMOD:
35599       assert( p->eLock==EXCLUSIVE_LOCK );
35600       assert( pPager->errCode==SQLITE_OK );
35601       assert( !pagerUseWal(pPager) );
35602       assert( p->eLock>=EXCLUSIVE_LOCK );
35603       assert( isOpen(p->jfd) 
35604            || p->journalMode==PAGER_JOURNALMODE_OFF 
35605            || p->journalMode==PAGER_JOURNALMODE_WAL 
35606       );
35607       assert( pPager->dbOrigSize<=pPager->dbHintSize );
35608       break;
35609
35610     case PAGER_WRITER_FINISHED:
35611       assert( p->eLock==EXCLUSIVE_LOCK );
35612       assert( pPager->errCode==SQLITE_OK );
35613       assert( !pagerUseWal(pPager) );
35614       assert( isOpen(p->jfd) 
35615            || p->journalMode==PAGER_JOURNALMODE_OFF 
35616            || p->journalMode==PAGER_JOURNALMODE_WAL 
35617       );
35618       break;
35619
35620     case PAGER_ERROR:
35621       /* There must be at least one outstanding reference to the pager if
35622       ** in ERROR state. Otherwise the pager should have already dropped
35623       ** back to OPEN state.
35624       */
35625       assert( pPager->errCode!=SQLITE_OK );
35626       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
35627       break;
35628   }
35629
35630   return 1;
35631 }
35632 #endif /* ifndef NDEBUG */
35633
35634 #ifdef SQLITE_DEBUG 
35635 /*
35636 ** Return a pointer to a human readable string in a static buffer
35637 ** containing the state of the Pager object passed as an argument. This
35638 ** is intended to be used within debuggers. For example, as an alternative
35639 ** to "print *pPager" in gdb:
35640 **
35641 ** (gdb) printf "%s", print_pager_state(pPager)
35642 */
35643 static char *print_pager_state(Pager *p){
35644   static char zRet[1024];
35645
35646   sqlite3_snprintf(1024, zRet,
35647       "Filename:      %s\n"
35648       "State:         %s errCode=%d\n"
35649       "Lock:          %s\n"
35650       "Locking mode:  locking_mode=%s\n"
35651       "Journal mode:  journal_mode=%s\n"
35652       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
35653       "Journal:       journalOff=%lld journalHdr=%lld\n"
35654       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
35655       , p->zFilename
35656       , p->eState==PAGER_OPEN            ? "OPEN" :
35657         p->eState==PAGER_READER          ? "READER" :
35658         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
35659         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
35660         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
35661         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
35662         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
35663       , (int)p->errCode
35664       , p->eLock==NO_LOCK         ? "NO_LOCK" :
35665         p->eLock==RESERVED_LOCK   ? "RESERVED" :
35666         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
35667         p->eLock==SHARED_LOCK     ? "SHARED" :
35668         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
35669       , p->exclusiveMode ? "exclusive" : "normal"
35670       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
35671         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
35672         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
35673         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
35674         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
35675         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
35676       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
35677       , p->journalOff, p->journalHdr
35678       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
35679   );
35680
35681   return zRet;
35682 }
35683 #endif
35684
35685 /*
35686 ** Return true if it is necessary to write page *pPg into the sub-journal.
35687 ** A page needs to be written into the sub-journal if there exists one
35688 ** or more open savepoints for which:
35689 **
35690 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
35691 **   * The bit corresponding to the page-number is not set in
35692 **     PagerSavepoint.pInSavepoint.
35693 */
35694 static int subjRequiresPage(PgHdr *pPg){
35695   Pgno pgno = pPg->pgno;
35696   Pager *pPager = pPg->pPager;
35697   int i;
35698   for(i=0; i<pPager->nSavepoint; i++){
35699     PagerSavepoint *p = &pPager->aSavepoint[i];
35700     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
35701       return 1;
35702     }
35703   }
35704   return 0;
35705 }
35706
35707 /*
35708 ** Return true if the page is already in the journal file.
35709 */
35710 static int pageInJournal(PgHdr *pPg){
35711   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
35712 }
35713
35714 /*
35715 ** Read a 32-bit integer from the given file descriptor.  Store the integer
35716 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
35717 ** error code is something goes wrong.
35718 **
35719 ** All values are stored on disk as big-endian.
35720 */
35721 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
35722   unsigned char ac[4];
35723   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
35724   if( rc==SQLITE_OK ){
35725     *pRes = sqlite3Get4byte(ac);
35726   }
35727   return rc;
35728 }
35729
35730 /*
35731 ** Write a 32-bit integer into a string buffer in big-endian byte order.
35732 */
35733 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
35734
35735
35736 /*
35737 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
35738 ** on success or an error code is something goes wrong.
35739 */
35740 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
35741   char ac[4];
35742   put32bits(ac, val);
35743   return sqlite3OsWrite(fd, ac, 4, offset);
35744 }
35745
35746 /*
35747 ** Unlock the database file to level eLock, which must be either NO_LOCK
35748 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
35749 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
35750 **
35751 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
35752 ** called, do not modify it. See the comment above the #define of 
35753 ** UNKNOWN_LOCK for an explanation of this.
35754 */
35755 static int pagerUnlockDb(Pager *pPager, int eLock){
35756   int rc = SQLITE_OK;
35757
35758   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
35759   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
35760   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
35761   if( isOpen(pPager->fd) ){
35762     assert( pPager->eLock>=eLock );
35763     rc = sqlite3OsUnlock(pPager->fd, eLock);
35764     if( pPager->eLock!=UNKNOWN_LOCK ){
35765       pPager->eLock = (u8)eLock;
35766     }
35767     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
35768   }
35769   return rc;
35770 }
35771
35772 /*
35773 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
35774 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
35775 ** Pager.eLock variable to the new locking state. 
35776 **
35777 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
35778 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
35779 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
35780 ** of this.
35781 */
35782 static int pagerLockDb(Pager *pPager, int eLock){
35783   int rc = SQLITE_OK;
35784
35785   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
35786   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
35787     rc = sqlite3OsLock(pPager->fd, eLock);
35788     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
35789       pPager->eLock = (u8)eLock;
35790       IOTRACE(("LOCK %p %d\n", pPager, eLock))
35791     }
35792   }
35793   return rc;
35794 }
35795
35796 /*
35797 ** This function determines whether or not the atomic-write optimization
35798 ** can be used with this pager. The optimization can be used if:
35799 **
35800 **  (a) the value returned by OsDeviceCharacteristics() indicates that
35801 **      a database page may be written atomically, and
35802 **  (b) the value returned by OsSectorSize() is less than or equal
35803 **      to the page size.
35804 **
35805 ** The optimization is also always enabled for temporary files. It is
35806 ** an error to call this function if pPager is opened on an in-memory
35807 ** database.
35808 **
35809 ** If the optimization cannot be used, 0 is returned. If it can be used,
35810 ** then the value returned is the size of the journal file when it
35811 ** contains rollback data for exactly one page.
35812 */
35813 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
35814 static int jrnlBufferSize(Pager *pPager){
35815   assert( !MEMDB );
35816   if( !pPager->tempFile ){
35817     int dc;                           /* Device characteristics */
35818     int nSector;                      /* Sector size */
35819     int szPage;                       /* Page size */
35820
35821     assert( isOpen(pPager->fd) );
35822     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
35823     nSector = pPager->sectorSize;
35824     szPage = pPager->pageSize;
35825
35826     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
35827     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
35828     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
35829       return 0;
35830     }
35831   }
35832
35833   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
35834 }
35835 #endif
35836
35837 /*
35838 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
35839 ** on the cache using a hash function.  This is used for testing
35840 ** and debugging only.
35841 */
35842 #ifdef SQLITE_CHECK_PAGES
35843 /*
35844 ** Return a 32-bit hash of the page data for pPage.
35845 */
35846 static u32 pager_datahash(int nByte, unsigned char *pData){
35847   u32 hash = 0;
35848   int i;
35849   for(i=0; i<nByte; i++){
35850     hash = (hash*1039) + pData[i];
35851   }
35852   return hash;
35853 }
35854 static u32 pager_pagehash(PgHdr *pPage){
35855   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
35856 }
35857 static void pager_set_pagehash(PgHdr *pPage){
35858   pPage->pageHash = pager_pagehash(pPage);
35859 }
35860
35861 /*
35862 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
35863 ** is defined, and NDEBUG is not defined, an assert() statement checks
35864 ** that the page is either dirty or still matches the calculated page-hash.
35865 */
35866 #define CHECK_PAGE(x) checkPage(x)
35867 static void checkPage(PgHdr *pPg){
35868   Pager *pPager = pPg->pPager;
35869   assert( pPager->eState!=PAGER_ERROR );
35870   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
35871 }
35872
35873 #else
35874 #define pager_datahash(X,Y)  0
35875 #define pager_pagehash(X)  0
35876 #define pager_set_pagehash(X)
35877 #define CHECK_PAGE(x)
35878 #endif  /* SQLITE_CHECK_PAGES */
35879
35880 /*
35881 ** When this is called the journal file for pager pPager must be open.
35882 ** This function attempts to read a master journal file name from the 
35883 ** end of the file and, if successful, copies it into memory supplied 
35884 ** by the caller. See comments above writeMasterJournal() for the format
35885 ** used to store a master journal file name at the end of a journal file.
35886 **
35887 ** zMaster must point to a buffer of at least nMaster bytes allocated by
35888 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
35889 ** enough space to write the master journal name). If the master journal
35890 ** name in the journal is longer than nMaster bytes (including a
35891 ** nul-terminator), then this is handled as if no master journal name
35892 ** were present in the journal.
35893 **
35894 ** If a master journal file name is present at the end of the journal
35895 ** file, then it is copied into the buffer pointed to by zMaster. A
35896 ** nul-terminator byte is appended to the buffer following the master
35897 ** journal file name.
35898 **
35899 ** If it is determined that no master journal file name is present 
35900 ** zMaster[0] is set to 0 and SQLITE_OK returned.
35901 **
35902 ** If an error occurs while reading from the journal file, an SQLite
35903 ** error code is returned.
35904 */
35905 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
35906   int rc;                    /* Return code */
35907   u32 len;                   /* Length in bytes of master journal name */
35908   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
35909   u32 cksum;                 /* MJ checksum value read from journal */
35910   u32 u;                     /* Unsigned loop counter */
35911   unsigned char aMagic[8];   /* A buffer to hold the magic header */
35912   zMaster[0] = '\0';
35913
35914   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
35915    || szJ<16
35916    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
35917    || len>=nMaster 
35918    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
35919    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
35920    || memcmp(aMagic, aJournalMagic, 8)
35921    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
35922   ){
35923     return rc;
35924   }
35925
35926   /* See if the checksum matches the master journal name */
35927   for(u=0; u<len; u++){
35928     cksum -= zMaster[u];
35929   }
35930   if( cksum ){
35931     /* If the checksum doesn't add up, then one or more of the disk sectors
35932     ** containing the master journal filename is corrupted. This means
35933     ** definitely roll back, so just return SQLITE_OK and report a (nul)
35934     ** master-journal filename.
35935     */
35936     len = 0;
35937   }
35938   zMaster[len] = '\0';
35939    
35940   return SQLITE_OK;
35941 }
35942
35943 /*
35944 ** Return the offset of the sector boundary at or immediately 
35945 ** following the value in pPager->journalOff, assuming a sector 
35946 ** size of pPager->sectorSize bytes.
35947 **
35948 ** i.e for a sector size of 512:
35949 **
35950 **   Pager.journalOff          Return value
35951 **   ---------------------------------------
35952 **   0                         0
35953 **   512                       512
35954 **   100                       512
35955 **   2000                      2048
35956 ** 
35957 */
35958 static i64 journalHdrOffset(Pager *pPager){
35959   i64 offset = 0;
35960   i64 c = pPager->journalOff;
35961   if( c ){
35962     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
35963   }
35964   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
35965   assert( offset>=c );
35966   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
35967   return offset;
35968 }
35969
35970 /*
35971 ** The journal file must be open when this function is called.
35972 **
35973 ** This function is a no-op if the journal file has not been written to
35974 ** within the current transaction (i.e. if Pager.journalOff==0).
35975 **
35976 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
35977 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
35978 ** zero the 28-byte header at the start of the journal file. In either case, 
35979 ** if the pager is not in no-sync mode, sync the journal file immediately 
35980 ** after writing or truncating it.
35981 **
35982 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
35983 ** following the truncation or zeroing described above the size of the 
35984 ** journal file in bytes is larger than this value, then truncate the
35985 ** journal file to Pager.journalSizeLimit bytes. The journal file does
35986 ** not need to be synced following this operation.
35987 **
35988 ** If an IO error occurs, abandon processing and return the IO error code.
35989 ** Otherwise, return SQLITE_OK.
35990 */
35991 static int zeroJournalHdr(Pager *pPager, int doTruncate){
35992   int rc = SQLITE_OK;                               /* Return code */
35993   assert( isOpen(pPager->jfd) );
35994   if( pPager->journalOff ){
35995     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
35996
35997     IOTRACE(("JZEROHDR %p\n", pPager))
35998     if( doTruncate || iLimit==0 ){
35999       rc = sqlite3OsTruncate(pPager->jfd, 0);
36000     }else{
36001       static const char zeroHdr[28] = {0};
36002       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
36003     }
36004     if( rc==SQLITE_OK && !pPager->noSync ){
36005       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
36006     }
36007
36008     /* At this point the transaction is committed but the write lock 
36009     ** is still held on the file. If there is a size limit configured for 
36010     ** the persistent journal and the journal file currently consumes more
36011     ** space than that limit allows for, truncate it now. There is no need
36012     ** to sync the file following this operation.
36013     */
36014     if( rc==SQLITE_OK && iLimit>0 ){
36015       i64 sz;
36016       rc = sqlite3OsFileSize(pPager->jfd, &sz);
36017       if( rc==SQLITE_OK && sz>iLimit ){
36018         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
36019       }
36020     }
36021   }
36022   return rc;
36023 }
36024
36025 /*
36026 ** The journal file must be open when this routine is called. A journal
36027 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
36028 ** current location.
36029 **
36030 ** The format for the journal header is as follows:
36031 ** - 8 bytes: Magic identifying journal format.
36032 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
36033 ** - 4 bytes: Random number used for page hash.
36034 ** - 4 bytes: Initial database page count.
36035 ** - 4 bytes: Sector size used by the process that wrote this journal.
36036 ** - 4 bytes: Database page size.
36037 ** 
36038 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
36039 */
36040 static int writeJournalHdr(Pager *pPager){
36041   int rc = SQLITE_OK;                 /* Return code */
36042   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
36043   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
36044   u32 nWrite;                         /* Bytes of header sector written */
36045   int ii;                             /* Loop counter */
36046
36047   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
36048
36049   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
36050     nHeader = JOURNAL_HDR_SZ(pPager);
36051   }
36052
36053   /* If there are active savepoints and any of them were created 
36054   ** since the most recent journal header was written, update the 
36055   ** PagerSavepoint.iHdrOffset fields now.
36056   */
36057   for(ii=0; ii<pPager->nSavepoint; ii++){
36058     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
36059       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
36060     }
36061   }
36062
36063   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
36064
36065   /* 
36066   ** Write the nRec Field - the number of page records that follow this
36067   ** journal header. Normally, zero is written to this value at this time.
36068   ** After the records are added to the journal (and the journal synced, 
36069   ** if in full-sync mode), the zero is overwritten with the true number
36070   ** of records (see syncJournal()).
36071   **
36072   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
36073   ** reading the journal this value tells SQLite to assume that the
36074   ** rest of the journal file contains valid page records. This assumption
36075   ** is dangerous, as if a failure occurred whilst writing to the journal
36076   ** file it may contain some garbage data. There are two scenarios
36077   ** where this risk can be ignored:
36078   **
36079   **   * When the pager is in no-sync mode. Corruption can follow a
36080   **     power failure in this case anyway.
36081   **
36082   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
36083   **     that garbage data is never appended to the journal file.
36084   */
36085   assert( isOpen(pPager->fd) || pPager->noSync );
36086   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
36087    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
36088   ){
36089     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
36090     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
36091   }else{
36092     memset(zHeader, 0, sizeof(aJournalMagic)+4);
36093   }
36094
36095   /* The random check-hash initialiser */ 
36096   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
36097   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
36098   /* The initial database size */
36099   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
36100   /* The assumed sector size for this process */
36101   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
36102
36103   /* The page size */
36104   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
36105
36106   /* Initializing the tail of the buffer is not necessary.  Everything
36107   ** works find if the following memset() is omitted.  But initializing
36108   ** the memory prevents valgrind from complaining, so we are willing to
36109   ** take the performance hit.
36110   */
36111   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
36112          nHeader-(sizeof(aJournalMagic)+20));
36113
36114   /* In theory, it is only necessary to write the 28 bytes that the 
36115   ** journal header consumes to the journal file here. Then increment the 
36116   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
36117   ** record is written to the following sector (leaving a gap in the file
36118   ** that will be implicitly filled in by the OS).
36119   **
36120   ** However it has been discovered that on some systems this pattern can 
36121   ** be significantly slower than contiguously writing data to the file,
36122   ** even if that means explicitly writing data to the block of 
36123   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
36124   ** is done. 
36125   **
36126   ** The loop is required here in case the sector-size is larger than the 
36127   ** database page size. Since the zHeader buffer is only Pager.pageSize
36128   ** bytes in size, more than one call to sqlite3OsWrite() may be required
36129   ** to populate the entire journal header sector.
36130   */ 
36131   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
36132     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
36133     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
36134     assert( pPager->journalHdr <= pPager->journalOff );
36135     pPager->journalOff += nHeader;
36136   }
36137
36138   return rc;
36139 }
36140
36141 /*
36142 ** The journal file must be open when this is called. A journal header file
36143 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
36144 ** file. The current location in the journal file is given by
36145 ** pPager->journalOff. See comments above function writeJournalHdr() for
36146 ** a description of the journal header format.
36147 **
36148 ** If the header is read successfully, *pNRec is set to the number of
36149 ** page records following this header and *pDbSize is set to the size of the
36150 ** database before the transaction began, in pages. Also, pPager->cksumInit
36151 ** is set to the value read from the journal header. SQLITE_OK is returned
36152 ** in this case.
36153 **
36154 ** If the journal header file appears to be corrupted, SQLITE_DONE is
36155 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
36156 ** cannot be read from the journal file an error code is returned.
36157 */
36158 static int readJournalHdr(
36159   Pager *pPager,               /* Pager object */
36160   int isHot,
36161   i64 journalSize,             /* Size of the open journal file in bytes */
36162   u32 *pNRec,                  /* OUT: Value read from the nRec field */
36163   u32 *pDbSize                 /* OUT: Value of original database size field */
36164 ){
36165   int rc;                      /* Return code */
36166   unsigned char aMagic[8];     /* A buffer to hold the magic header */
36167   i64 iHdrOff;                 /* Offset of journal header being read */
36168
36169   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
36170
36171   /* Advance Pager.journalOff to the start of the next sector. If the
36172   ** journal file is too small for there to be a header stored at this
36173   ** point, return SQLITE_DONE.
36174   */
36175   pPager->journalOff = journalHdrOffset(pPager);
36176   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
36177     return SQLITE_DONE;
36178   }
36179   iHdrOff = pPager->journalOff;
36180
36181   /* Read in the first 8 bytes of the journal header. If they do not match
36182   ** the  magic string found at the start of each journal header, return
36183   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
36184   ** proceed.
36185   */
36186   if( isHot || iHdrOff!=pPager->journalHdr ){
36187     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
36188     if( rc ){
36189       return rc;
36190     }
36191     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
36192       return SQLITE_DONE;
36193     }
36194   }
36195
36196   /* Read the first three 32-bit fields of the journal header: The nRec
36197   ** field, the checksum-initializer and the database size at the start
36198   ** of the transaction. Return an error code if anything goes wrong.
36199   */
36200   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
36201    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
36202    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
36203   ){
36204     return rc;
36205   }
36206
36207   if( pPager->journalOff==0 ){
36208     u32 iPageSize;               /* Page-size field of journal header */
36209     u32 iSectorSize;             /* Sector-size field of journal header */
36210
36211     /* Read the page-size and sector-size journal header fields. */
36212     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
36213      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
36214     ){
36215       return rc;
36216     }
36217
36218     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
36219     ** journal header to zero. In this case, assume that the Pager.pageSize
36220     ** variable is already set to the correct page size.
36221     */
36222     if( iPageSize==0 ){
36223       iPageSize = pPager->pageSize;
36224     }
36225
36226     /* Check that the values read from the page-size and sector-size fields
36227     ** are within range. To be 'in range', both values need to be a power
36228     ** of two greater than or equal to 512 or 32, and not greater than their 
36229     ** respective compile time maximum limits.
36230     */
36231     if( iPageSize<512                  || iSectorSize<32
36232      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
36233      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
36234     ){
36235       /* If the either the page-size or sector-size in the journal-header is 
36236       ** invalid, then the process that wrote the journal-header must have 
36237       ** crashed before the header was synced. In this case stop reading 
36238       ** the journal file here.
36239       */
36240       return SQLITE_DONE;
36241     }
36242
36243     /* Update the page-size to match the value read from the journal. 
36244     ** Use a testcase() macro to make sure that malloc failure within 
36245     ** PagerSetPagesize() is tested.
36246     */
36247     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
36248     testcase( rc!=SQLITE_OK );
36249
36250     /* Update the assumed sector-size to match the value used by 
36251     ** the process that created this journal. If this journal was
36252     ** created by a process other than this one, then this routine
36253     ** is being called from within pager_playback(). The local value
36254     ** of Pager.sectorSize is restored at the end of that routine.
36255     */
36256     pPager->sectorSize = iSectorSize;
36257   }
36258
36259   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
36260   return rc;
36261 }
36262
36263
36264 /*
36265 ** Write the supplied master journal name into the journal file for pager
36266 ** pPager at the current location. The master journal name must be the last
36267 ** thing written to a journal file. If the pager is in full-sync mode, the
36268 ** journal file descriptor is advanced to the next sector boundary before
36269 ** anything is written. The format is:
36270 **
36271 **   + 4 bytes: PAGER_MJ_PGNO.
36272 **   + N bytes: Master journal filename in utf-8.
36273 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
36274 **   + 4 bytes: Master journal name checksum.
36275 **   + 8 bytes: aJournalMagic[].
36276 **
36277 ** The master journal page checksum is the sum of the bytes in the master
36278 ** journal name, where each byte is interpreted as a signed 8-bit integer.
36279 **
36280 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
36281 ** this call is a no-op.
36282 */
36283 static int writeMasterJournal(Pager *pPager, const char *zMaster){
36284   int rc;                          /* Return code */
36285   int nMaster;                     /* Length of string zMaster */
36286   i64 iHdrOff;                     /* Offset of header in journal file */
36287   i64 jrnlSize;                    /* Size of journal file on disk */
36288   u32 cksum = 0;                   /* Checksum of string zMaster */
36289
36290   assert( pPager->setMaster==0 );
36291   assert( !pagerUseWal(pPager) );
36292
36293   if( !zMaster 
36294    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
36295    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
36296   ){
36297     return SQLITE_OK;
36298   }
36299   pPager->setMaster = 1;
36300   assert( isOpen(pPager->jfd) );
36301   assert( pPager->journalHdr <= pPager->journalOff );
36302
36303   /* Calculate the length in bytes and the checksum of zMaster */
36304   for(nMaster=0; zMaster[nMaster]; nMaster++){
36305     cksum += zMaster[nMaster];
36306   }
36307
36308   /* If in full-sync mode, advance to the next disk sector before writing
36309   ** the master journal name. This is in case the previous page written to
36310   ** the journal has already been synced.
36311   */
36312   if( pPager->fullSync ){
36313     pPager->journalOff = journalHdrOffset(pPager);
36314   }
36315   iHdrOff = pPager->journalOff;
36316
36317   /* Write the master journal data to the end of the journal file. If
36318   ** an error occurs, return the error code to the caller.
36319   */
36320   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
36321    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
36322    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
36323    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
36324    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
36325   ){
36326     return rc;
36327   }
36328   pPager->journalOff += (nMaster+20);
36329
36330   /* If the pager is in peristent-journal mode, then the physical 
36331   ** journal-file may extend past the end of the master-journal name
36332   ** and 8 bytes of magic data just written to the file. This is 
36333   ** dangerous because the code to rollback a hot-journal file
36334   ** will not be able to find the master-journal name to determine 
36335   ** whether or not the journal is hot. 
36336   **
36337   ** Easiest thing to do in this scenario is to truncate the journal 
36338   ** file to the required size.
36339   */ 
36340   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
36341    && jrnlSize>pPager->journalOff
36342   ){
36343     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
36344   }
36345   return rc;
36346 }
36347
36348 /*
36349 ** Find a page in the hash table given its page number. Return
36350 ** a pointer to the page or NULL if the requested page is not 
36351 ** already in memory.
36352 */
36353 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
36354   PgHdr *p;                         /* Return value */
36355
36356   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
36357   ** fail, since no attempt to allocate dynamic memory will be made.
36358   */
36359   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
36360   return p;
36361 }
36362
36363 /*
36364 ** Discard the entire contents of the in-memory page-cache.
36365 */
36366 static void pager_reset(Pager *pPager){
36367   sqlite3BackupRestart(pPager->pBackup);
36368   sqlite3PcacheClear(pPager->pPCache);
36369 }
36370
36371 /*
36372 ** Free all structures in the Pager.aSavepoint[] array and set both
36373 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
36374 ** if it is open and the pager is not in exclusive mode.
36375 */
36376 static void releaseAllSavepoints(Pager *pPager){
36377   int ii;               /* Iterator for looping through Pager.aSavepoint */
36378   for(ii=0; ii<pPager->nSavepoint; ii++){
36379     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
36380   }
36381   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
36382     sqlite3OsClose(pPager->sjfd);
36383   }
36384   sqlite3_free(pPager->aSavepoint);
36385   pPager->aSavepoint = 0;
36386   pPager->nSavepoint = 0;
36387   pPager->nSubRec = 0;
36388 }
36389
36390 /*
36391 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
36392 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
36393 ** or SQLITE_NOMEM if a malloc failure occurs.
36394 */
36395 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
36396   int ii;                   /* Loop counter */
36397   int rc = SQLITE_OK;       /* Result code */
36398
36399   for(ii=0; ii<pPager->nSavepoint; ii++){
36400     PagerSavepoint *p = &pPager->aSavepoint[ii];
36401     if( pgno<=p->nOrig ){
36402       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
36403       testcase( rc==SQLITE_NOMEM );
36404       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
36405     }
36406   }
36407   return rc;
36408 }
36409
36410 /*
36411 ** This function is a no-op if the pager is in exclusive mode and not
36412 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
36413 ** state.
36414 **
36415 ** If the pager is not in exclusive-access mode, the database file is
36416 ** completely unlocked. If the file is unlocked and the file-system does
36417 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
36418 ** closed (if it is open).
36419 **
36420 ** If the pager is in ERROR state when this function is called, the 
36421 ** contents of the pager cache are discarded before switching back to 
36422 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
36423 ** or not, any journal file left in the file-system will be treated
36424 ** as a hot-journal and rolled back the next time a read-transaction
36425 ** is opened (by this or by any other connection).
36426 */
36427 static void pager_unlock(Pager *pPager){
36428
36429   assert( pPager->eState==PAGER_READER 
36430        || pPager->eState==PAGER_OPEN 
36431        || pPager->eState==PAGER_ERROR 
36432   );
36433
36434   sqlite3BitvecDestroy(pPager->pInJournal);
36435   pPager->pInJournal = 0;
36436   releaseAllSavepoints(pPager);
36437
36438   if( pagerUseWal(pPager) ){
36439     assert( !isOpen(pPager->jfd) );
36440     sqlite3WalEndReadTransaction(pPager->pWal);
36441     pPager->eState = PAGER_OPEN;
36442   }else if( !pPager->exclusiveMode ){
36443     int rc;                       /* Error code returned by pagerUnlockDb() */
36444     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
36445
36446     /* If the operating system support deletion of open files, then
36447     ** close the journal file when dropping the database lock.  Otherwise
36448     ** another connection with journal_mode=delete might delete the file
36449     ** out from under us.
36450     */
36451     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
36452     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
36453     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
36454     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
36455     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
36456     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
36457     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
36458      || 1!=(pPager->journalMode & 5)
36459     ){
36460       sqlite3OsClose(pPager->jfd);
36461     }
36462
36463     /* If the pager is in the ERROR state and the call to unlock the database
36464     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
36465     ** above the #define for UNKNOWN_LOCK for an explanation of why this
36466     ** is necessary.
36467     */
36468     rc = pagerUnlockDb(pPager, NO_LOCK);
36469     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
36470       pPager->eLock = UNKNOWN_LOCK;
36471     }
36472
36473     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
36474     ** without clearing the error code. This is intentional - the error
36475     ** code is cleared and the cache reset in the block below.
36476     */
36477     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
36478     pPager->changeCountDone = 0;
36479     pPager->eState = PAGER_OPEN;
36480   }
36481
36482   /* If Pager.errCode is set, the contents of the pager cache cannot be
36483   ** trusted. Now that there are no outstanding references to the pager,
36484   ** it can safely move back to PAGER_OPEN state. This happens in both
36485   ** normal and exclusive-locking mode.
36486   */
36487   if( pPager->errCode ){
36488     assert( !MEMDB );
36489     pager_reset(pPager);
36490     pPager->changeCountDone = pPager->tempFile;
36491     pPager->eState = PAGER_OPEN;
36492     pPager->errCode = SQLITE_OK;
36493   }
36494
36495   pPager->journalOff = 0;
36496   pPager->journalHdr = 0;
36497   pPager->setMaster = 0;
36498 }
36499
36500 /*
36501 ** This function is called whenever an IOERR or FULL error that requires
36502 ** the pager to transition into the ERROR state may ahve occurred.
36503 ** The first argument is a pointer to the pager structure, the second 
36504 ** the error-code about to be returned by a pager API function. The 
36505 ** value returned is a copy of the second argument to this function. 
36506 **
36507 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
36508 ** IOERR sub-codes, the pager enters the ERROR state and the error code
36509 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
36510 ** all major API calls on the Pager will immediately return Pager.errCode.
36511 **
36512 ** The ERROR state indicates that the contents of the pager-cache 
36513 ** cannot be trusted. This state can be cleared by completely discarding 
36514 ** the contents of the pager-cache. If a transaction was active when
36515 ** the persistent error occurred, then the rollback journal may need
36516 ** to be replayed to restore the contents of the database file (as if
36517 ** it were a hot-journal).
36518 */
36519 static int pager_error(Pager *pPager, int rc){
36520   int rc2 = rc & 0xff;
36521   assert( rc==SQLITE_OK || !MEMDB );
36522   assert(
36523        pPager->errCode==SQLITE_FULL ||
36524        pPager->errCode==SQLITE_OK ||
36525        (pPager->errCode & 0xff)==SQLITE_IOERR
36526   );
36527   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
36528     pPager->errCode = rc;
36529     pPager->eState = PAGER_ERROR;
36530   }
36531   return rc;
36532 }
36533
36534 /*
36535 ** This routine ends a transaction. A transaction is usually ended by 
36536 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
36537 ** after rollback of a hot-journal, or if an error occurs while opening
36538 ** the journal file or writing the very first journal-header of a
36539 ** database transaction.
36540 ** 
36541 ** This routine is never called in PAGER_ERROR state. If it is called
36542 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
36543 ** exclusive than a RESERVED lock, it is a no-op.
36544 **
36545 ** Otherwise, any active savepoints are released.
36546 **
36547 ** If the journal file is open, then it is "finalized". Once a journal 
36548 ** file has been finalized it is not possible to use it to roll back a 
36549 ** transaction. Nor will it be considered to be a hot-journal by this
36550 ** or any other database connection. Exactly how a journal is finalized
36551 ** depends on whether or not the pager is running in exclusive mode and
36552 ** the current journal-mode (Pager.journalMode value), as follows:
36553 **
36554 **   journalMode==MEMORY
36555 **     Journal file descriptor is simply closed. This destroys an 
36556 **     in-memory journal.
36557 **
36558 **   journalMode==TRUNCATE
36559 **     Journal file is truncated to zero bytes in size.
36560 **
36561 **   journalMode==PERSIST
36562 **     The first 28 bytes of the journal file are zeroed. This invalidates
36563 **     the first journal header in the file, and hence the entire journal
36564 **     file. An invalid journal file cannot be rolled back.
36565 **
36566 **   journalMode==DELETE
36567 **     The journal file is closed and deleted using sqlite3OsDelete().
36568 **
36569 **     If the pager is running in exclusive mode, this method of finalizing
36570 **     the journal file is never used. Instead, if the journalMode is
36571 **     DELETE and the pager is in exclusive mode, the method described under
36572 **     journalMode==PERSIST is used instead.
36573 **
36574 ** After the journal is finalized, the pager moves to PAGER_READER state.
36575 ** If running in non-exclusive rollback mode, the lock on the file is 
36576 ** downgraded to a SHARED_LOCK.
36577 **
36578 ** SQLITE_OK is returned if no error occurs. If an error occurs during
36579 ** any of the IO operations to finalize the journal file or unlock the
36580 ** database then the IO error code is returned to the user. If the 
36581 ** operation to finalize the journal file fails, then the code still
36582 ** tries to unlock the database file if not in exclusive mode. If the
36583 ** unlock operation fails as well, then the first error code related
36584 ** to the first error encountered (the journal finalization one) is
36585 ** returned.
36586 */
36587 static int pager_end_transaction(Pager *pPager, int hasMaster){
36588   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
36589   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
36590
36591   /* Do nothing if the pager does not have an open write transaction
36592   ** or at least a RESERVED lock. This function may be called when there
36593   ** is no write-transaction active but a RESERVED or greater lock is
36594   ** held under two circumstances:
36595   **
36596   **   1. After a successful hot-journal rollback, it is called with
36597   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
36598   **
36599   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
36600   **      lock switches back to locking_mode=normal and then executes a
36601   **      read-transaction, this function is called with eState==PAGER_READER 
36602   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
36603   */
36604   assert( assert_pager_state(pPager) );
36605   assert( pPager->eState!=PAGER_ERROR );
36606   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
36607     return SQLITE_OK;
36608   }
36609
36610   releaseAllSavepoints(pPager);
36611   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
36612   if( isOpen(pPager->jfd) ){
36613     assert( !pagerUseWal(pPager) );
36614
36615     /* Finalize the journal file. */
36616     if( sqlite3IsMemJournal(pPager->jfd) ){
36617       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
36618       sqlite3OsClose(pPager->jfd);
36619     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
36620       if( pPager->journalOff==0 ){
36621         rc = SQLITE_OK;
36622       }else{
36623         rc = sqlite3OsTruncate(pPager->jfd, 0);
36624       }
36625       pPager->journalOff = 0;
36626     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
36627       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
36628     ){
36629       rc = zeroJournalHdr(pPager, hasMaster);
36630       pPager->journalOff = 0;
36631     }else{
36632       /* This branch may be executed with Pager.journalMode==MEMORY if
36633       ** a hot-journal was just rolled back. In this case the journal
36634       ** file should be closed and deleted. If this connection writes to
36635       ** the database file, it will do so using an in-memory journal. 
36636       */
36637       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
36638            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
36639            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
36640       );
36641       sqlite3OsClose(pPager->jfd);
36642       if( !pPager->tempFile ){
36643         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
36644       }
36645     }
36646   }
36647
36648 #ifdef SQLITE_CHECK_PAGES
36649   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
36650   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
36651     PgHdr *p = pager_lookup(pPager, 1);
36652     if( p ){
36653       p->pageHash = 0;
36654       sqlite3PagerUnref(p);
36655     }
36656   }
36657 #endif
36658
36659   sqlite3BitvecDestroy(pPager->pInJournal);
36660   pPager->pInJournal = 0;
36661   pPager->nRec = 0;
36662   sqlite3PcacheCleanAll(pPager->pPCache);
36663   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
36664
36665   if( pagerUseWal(pPager) ){
36666     /* Drop the WAL write-lock, if any. Also, if the connection was in 
36667     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
36668     ** lock held on the database file.
36669     */
36670     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
36671     assert( rc2==SQLITE_OK );
36672   }
36673   if( !pPager->exclusiveMode 
36674    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
36675   ){
36676     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
36677     pPager->changeCountDone = 0;
36678   }
36679   pPager->eState = PAGER_READER;
36680   pPager->setMaster = 0;
36681
36682   return (rc==SQLITE_OK?rc2:rc);
36683 }
36684
36685 /*
36686 ** Execute a rollback if a transaction is active and unlock the 
36687 ** database file. 
36688 **
36689 ** If the pager has already entered the ERROR state, do not attempt 
36690 ** the rollback at this time. Instead, pager_unlock() is called. The
36691 ** call to pager_unlock() will discard all in-memory pages, unlock
36692 ** the database file and move the pager back to OPEN state. If this 
36693 ** means that there is a hot-journal left in the file-system, the next 
36694 ** connection to obtain a shared lock on the pager (which may be this one) 
36695 ** will roll it back.
36696 **
36697 ** If the pager has not already entered the ERROR state, but an IO or
36698 ** malloc error occurs during a rollback, then this will itself cause 
36699 ** the pager to enter the ERROR state. Which will be cleared by the
36700 ** call to pager_unlock(), as described above.
36701 */
36702 static void pagerUnlockAndRollback(Pager *pPager){
36703   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
36704     assert( assert_pager_state(pPager) );
36705     if( pPager->eState>=PAGER_WRITER_LOCKED ){
36706       sqlite3BeginBenignMalloc();
36707       sqlite3PagerRollback(pPager);
36708       sqlite3EndBenignMalloc();
36709     }else if( !pPager->exclusiveMode ){
36710       assert( pPager->eState==PAGER_READER );
36711       pager_end_transaction(pPager, 0);
36712     }
36713   }
36714   pager_unlock(pPager);
36715 }
36716
36717 /*
36718 ** Parameter aData must point to a buffer of pPager->pageSize bytes
36719 ** of data. Compute and return a checksum based ont the contents of the 
36720 ** page of data and the current value of pPager->cksumInit.
36721 **
36722 ** This is not a real checksum. It is really just the sum of the 
36723 ** random initial value (pPager->cksumInit) and every 200th byte
36724 ** of the page data, starting with byte offset (pPager->pageSize%200).
36725 ** Each byte is interpreted as an 8-bit unsigned integer.
36726 **
36727 ** Changing the formula used to compute this checksum results in an
36728 ** incompatible journal file format.
36729 **
36730 ** If journal corruption occurs due to a power failure, the most likely 
36731 ** scenario is that one end or the other of the record will be changed. 
36732 ** It is much less likely that the two ends of the journal record will be
36733 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
36734 ** though fast and simple, catches the mostly likely kind of corruption.
36735 */
36736 static u32 pager_cksum(Pager *pPager, const u8 *aData){
36737   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
36738   int i = pPager->pageSize-200;          /* Loop counter */
36739   while( i>0 ){
36740     cksum += aData[i];
36741     i -= 200;
36742   }
36743   return cksum;
36744 }
36745
36746 /*
36747 ** Report the current page size and number of reserved bytes back
36748 ** to the codec.
36749 */
36750 #ifdef SQLITE_HAS_CODEC
36751 static void pagerReportSize(Pager *pPager){
36752   if( pPager->xCodecSizeChng ){
36753     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
36754                            (int)pPager->nReserve);
36755   }
36756 }
36757 #else
36758 # define pagerReportSize(X)     /* No-op if we do not support a codec */
36759 #endif
36760
36761 /*
36762 ** Read a single page from either the journal file (if isMainJrnl==1) or
36763 ** from the sub-journal (if isMainJrnl==0) and playback that page.
36764 ** The page begins at offset *pOffset into the file. The *pOffset
36765 ** value is increased to the start of the next page in the journal.
36766 **
36767 ** The main rollback journal uses checksums - the statement journal does 
36768 ** not.
36769 **
36770 ** If the page number of the page record read from the (sub-)journal file
36771 ** is greater than the current value of Pager.dbSize, then playback is
36772 ** skipped and SQLITE_OK is returned.
36773 **
36774 ** If pDone is not NULL, then it is a record of pages that have already
36775 ** been played back.  If the page at *pOffset has already been played back
36776 ** (if the corresponding pDone bit is set) then skip the playback.
36777 ** Make sure the pDone bit corresponding to the *pOffset page is set
36778 ** prior to returning.
36779 **
36780 ** If the page record is successfully read from the (sub-)journal file
36781 ** and played back, then SQLITE_OK is returned. If an IO error occurs
36782 ** while reading the record from the (sub-)journal file or while writing
36783 ** to the database file, then the IO error code is returned. If data
36784 ** is successfully read from the (sub-)journal file but appears to be
36785 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
36786 ** two circumstances:
36787 ** 
36788 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
36789 **   * If the record is being rolled back from the main journal file
36790 **     and the checksum field does not match the record content.
36791 **
36792 ** Neither of these two scenarios are possible during a savepoint rollback.
36793 **
36794 ** If this is a savepoint rollback, then memory may have to be dynamically
36795 ** allocated by this function. If this is the case and an allocation fails,
36796 ** SQLITE_NOMEM is returned.
36797 */
36798 static int pager_playback_one_page(
36799   Pager *pPager,                /* The pager being played back */
36800   i64 *pOffset,                 /* Offset of record to playback */
36801   Bitvec *pDone,                /* Bitvec of pages already played back */
36802   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
36803   int isSavepnt                 /* True for a savepoint rollback */
36804 ){
36805   int rc;
36806   PgHdr *pPg;                   /* An existing page in the cache */
36807   Pgno pgno;                    /* The page number of a page in journal */
36808   u32 cksum;                    /* Checksum used for sanity checking */
36809   char *aData;                  /* Temporary storage for the page */
36810   sqlite3_file *jfd;            /* The file descriptor for the journal file */
36811   int isSynced;                 /* True if journal page is synced */
36812
36813   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
36814   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
36815   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
36816   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
36817
36818   aData = pPager->pTmpSpace;
36819   assert( aData );         /* Temp storage must have already been allocated */
36820   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
36821
36822   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
36823   ** or savepoint rollback done at the request of the caller) or this is
36824   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
36825   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
36826   ** only reads from the main journal, not the sub-journal.
36827   */
36828   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
36829        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
36830   );
36831   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
36832
36833   /* Read the page number and page data from the journal or sub-journal
36834   ** file. Return an error code to the caller if an IO error occurs.
36835   */
36836   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
36837   rc = read32bits(jfd, *pOffset, &pgno);
36838   if( rc!=SQLITE_OK ) return rc;
36839   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
36840   if( rc!=SQLITE_OK ) return rc;
36841   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
36842
36843   /* Sanity checking on the page.  This is more important that I originally
36844   ** thought.  If a power failure occurs while the journal is being written,
36845   ** it could cause invalid data to be written into the journal.  We need to
36846   ** detect this invalid data (with high probability) and ignore it.
36847   */
36848   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
36849     assert( !isSavepnt );
36850     return SQLITE_DONE;
36851   }
36852   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
36853     return SQLITE_OK;
36854   }
36855   if( isMainJrnl ){
36856     rc = read32bits(jfd, (*pOffset)-4, &cksum);
36857     if( rc ) return rc;
36858     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
36859       return SQLITE_DONE;
36860     }
36861   }
36862
36863   /* If this page has already been played by before during the current
36864   ** rollback, then don't bother to play it back again.
36865   */
36866   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
36867     return rc;
36868   }
36869
36870   /* When playing back page 1, restore the nReserve setting
36871   */
36872   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
36873     pPager->nReserve = ((u8*)aData)[20];
36874     pagerReportSize(pPager);
36875   }
36876
36877   /* If the pager is in CACHEMOD state, then there must be a copy of this
36878   ** page in the pager cache. In this case just update the pager cache,
36879   ** not the database file. The page is left marked dirty in this case.
36880   **
36881   ** An exception to the above rule: If the database is in no-sync mode
36882   ** and a page is moved during an incremental vacuum then the page may
36883   ** not be in the pager cache. Later: if a malloc() or IO error occurs
36884   ** during a Movepage() call, then the page may not be in the cache
36885   ** either. So the condition described in the above paragraph is not
36886   ** assert()able.
36887   **
36888   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
36889   ** pager cache if it exists and the main file. The page is then marked 
36890   ** not dirty. Since this code is only executed in PAGER_OPEN state for
36891   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
36892   ** if the pager is in OPEN state.
36893   **
36894   ** Ticket #1171:  The statement journal might contain page content that is
36895   ** different from the page content at the start of the transaction.
36896   ** This occurs when a page is changed prior to the start of a statement
36897   ** then changed again within the statement.  When rolling back such a
36898   ** statement we must not write to the original database unless we know
36899   ** for certain that original page contents are synced into the main rollback
36900   ** journal.  Otherwise, a power loss might leave modified data in the
36901   ** database file without an entry in the rollback journal that can
36902   ** restore the database to its original form.  Two conditions must be
36903   ** met before writing to the database files. (1) the database must be
36904   ** locked.  (2) we know that the original page content is fully synced
36905   ** in the main journal either because the page is not in cache or else
36906   ** the page is marked as needSync==0.
36907   **
36908   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
36909   ** is possible to fail a statement on a database that does not yet exist.
36910   ** Do not attempt to write if database file has never been opened.
36911   */
36912   if( pagerUseWal(pPager) ){
36913     pPg = 0;
36914   }else{
36915     pPg = pager_lookup(pPager, pgno);
36916   }
36917   assert( pPg || !MEMDB );
36918   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
36919   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
36920            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
36921            (isMainJrnl?"main-journal":"sub-journal")
36922   ));
36923   if( isMainJrnl ){
36924     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
36925   }else{
36926     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
36927   }
36928   if( isOpen(pPager->fd)
36929    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
36930    && isSynced
36931   ){
36932     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
36933     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
36934     assert( !pagerUseWal(pPager) );
36935     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
36936     if( pgno>pPager->dbFileSize ){
36937       pPager->dbFileSize = pgno;
36938     }
36939     if( pPager->pBackup ){
36940       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
36941       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
36942       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
36943     }
36944   }else if( !isMainJrnl && pPg==0 ){
36945     /* If this is a rollback of a savepoint and data was not written to
36946     ** the database and the page is not in-memory, there is a potential
36947     ** problem. When the page is next fetched by the b-tree layer, it 
36948     ** will be read from the database file, which may or may not be 
36949     ** current. 
36950     **
36951     ** There are a couple of different ways this can happen. All are quite
36952     ** obscure. When running in synchronous mode, this can only happen 
36953     ** if the page is on the free-list at the start of the transaction, then
36954     ** populated, then moved using sqlite3PagerMovepage().
36955     **
36956     ** The solution is to add an in-memory page to the cache containing
36957     ** the data just read from the sub-journal. Mark the page as dirty 
36958     ** and if the pager requires a journal-sync, then mark the page as 
36959     ** requiring a journal-sync before it is written.
36960     */
36961     assert( isSavepnt );
36962     assert( pPager->doNotSpill==0 );
36963     pPager->doNotSpill++;
36964     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
36965     assert( pPager->doNotSpill==1 );
36966     pPager->doNotSpill--;
36967     if( rc!=SQLITE_OK ) return rc;
36968     pPg->flags &= ~PGHDR_NEED_READ;
36969     sqlite3PcacheMakeDirty(pPg);
36970   }
36971   if( pPg ){
36972     /* No page should ever be explicitly rolled back that is in use, except
36973     ** for page 1 which is held in use in order to keep the lock on the
36974     ** database active. However such a page may be rolled back as a result
36975     ** of an internal error resulting in an automatic call to
36976     ** sqlite3PagerRollback().
36977     */
36978     void *pData;
36979     pData = pPg->pData;
36980     memcpy(pData, (u8*)aData, pPager->pageSize);
36981     pPager->xReiniter(pPg);
36982     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
36983       /* If the contents of this page were just restored from the main 
36984       ** journal file, then its content must be as they were when the 
36985       ** transaction was first opened. In this case we can mark the page
36986       ** as clean, since there will be no need to write it out to the
36987       ** database.
36988       **
36989       ** There is one exception to this rule. If the page is being rolled
36990       ** back as part of a savepoint (or statement) rollback from an 
36991       ** unsynced portion of the main journal file, then it is not safe
36992       ** to mark the page as clean. This is because marking the page as
36993       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
36994       ** already in the journal file (recorded in Pager.pInJournal) and
36995       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
36996       ** again within this transaction, it will be marked as dirty but
36997       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
36998       ** be written out into the database file before its journal file
36999       ** segment is synced. If a crash occurs during or following this,
37000       ** database corruption may ensue.
37001       */
37002       assert( !pagerUseWal(pPager) );
37003       sqlite3PcacheMakeClean(pPg);
37004     }
37005     pager_set_pagehash(pPg);
37006
37007     /* If this was page 1, then restore the value of Pager.dbFileVers.
37008     ** Do this before any decoding. */
37009     if( pgno==1 ){
37010       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
37011     }
37012
37013     /* Decode the page just read from disk */
37014     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
37015     sqlite3PcacheRelease(pPg);
37016   }
37017   return rc;
37018 }
37019
37020 /*
37021 ** Parameter zMaster is the name of a master journal file. A single journal
37022 ** file that referred to the master journal file has just been rolled back.
37023 ** This routine checks if it is possible to delete the master journal file,
37024 ** and does so if it is.
37025 **
37026 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
37027 ** available for use within this function.
37028 **
37029 ** When a master journal file is created, it is populated with the names 
37030 ** of all of its child journals, one after another, formatted as utf-8 
37031 ** encoded text. The end of each child journal file is marked with a 
37032 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
37033 ** file for a transaction involving two databases might be:
37034 **
37035 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
37036 **
37037 ** A master journal file may only be deleted once all of its child 
37038 ** journals have been rolled back.
37039 **
37040 ** This function reads the contents of the master-journal file into 
37041 ** memory and loops through each of the child journal names. For
37042 ** each child journal, it checks if:
37043 **
37044 **   * if the child journal exists, and if so
37045 **   * if the child journal contains a reference to master journal 
37046 **     file zMaster
37047 **
37048 ** If a child journal can be found that matches both of the criteria
37049 ** above, this function returns without doing anything. Otherwise, if
37050 ** no such child journal can be found, file zMaster is deleted from
37051 ** the file-system using sqlite3OsDelete().
37052 **
37053 ** If an IO error within this function, an error code is returned. This
37054 ** function allocates memory by calling sqlite3Malloc(). If an allocation
37055 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
37056 ** occur, SQLITE_OK is returned.
37057 **
37058 ** TODO: This function allocates a single block of memory to load
37059 ** the entire contents of the master journal file. This could be
37060 ** a couple of kilobytes or so - potentially larger than the page 
37061 ** size.
37062 */
37063 static int pager_delmaster(Pager *pPager, const char *zMaster){
37064   sqlite3_vfs *pVfs = pPager->pVfs;
37065   int rc;                   /* Return code */
37066   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
37067   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
37068   char *zMasterJournal = 0; /* Contents of master journal file */
37069   i64 nMasterJournal;       /* Size of master journal file */
37070   char *zJournal;           /* Pointer to one journal within MJ file */
37071   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
37072   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
37073
37074   /* Allocate space for both the pJournal and pMaster file descriptors.
37075   ** If successful, open the master journal file for reading.
37076   */
37077   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
37078   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
37079   if( !pMaster ){
37080     rc = SQLITE_NOMEM;
37081   }else{
37082     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
37083     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
37084   }
37085   if( rc!=SQLITE_OK ) goto delmaster_out;
37086
37087   /* Load the entire master journal file into space obtained from
37088   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
37089   ** sufficient space (in zMasterPtr) to hold the names of master
37090   ** journal files extracted from regular rollback-journals.
37091   */
37092   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
37093   if( rc!=SQLITE_OK ) goto delmaster_out;
37094   nMasterPtr = pVfs->mxPathname+1;
37095   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
37096   if( !zMasterJournal ){
37097     rc = SQLITE_NOMEM;
37098     goto delmaster_out;
37099   }
37100   zMasterPtr = &zMasterJournal[nMasterJournal+1];
37101   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
37102   if( rc!=SQLITE_OK ) goto delmaster_out;
37103   zMasterJournal[nMasterJournal] = 0;
37104
37105   zJournal = zMasterJournal;
37106   while( (zJournal-zMasterJournal)<nMasterJournal ){
37107     int exists;
37108     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
37109     if( rc!=SQLITE_OK ){
37110       goto delmaster_out;
37111     }
37112     if( exists ){
37113       /* One of the journals pointed to by the master journal exists.
37114       ** Open it and check if it points at the master journal. If
37115       ** so, return without deleting the master journal file.
37116       */
37117       int c;
37118       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
37119       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
37120       if( rc!=SQLITE_OK ){
37121         goto delmaster_out;
37122       }
37123
37124       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
37125       sqlite3OsClose(pJournal);
37126       if( rc!=SQLITE_OK ){
37127         goto delmaster_out;
37128       }
37129
37130       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
37131       if( c ){
37132         /* We have a match. Do not delete the master journal file. */
37133         goto delmaster_out;
37134       }
37135     }
37136     zJournal += (sqlite3Strlen30(zJournal)+1);
37137   }
37138  
37139   sqlite3OsClose(pMaster);
37140   rc = sqlite3OsDelete(pVfs, zMaster, 0);
37141
37142 delmaster_out:
37143   sqlite3_free(zMasterJournal);
37144   if( pMaster ){
37145     sqlite3OsClose(pMaster);
37146     assert( !isOpen(pJournal) );
37147     sqlite3_free(pMaster);
37148   }
37149   return rc;
37150 }
37151
37152
37153 /*
37154 ** This function is used to change the actual size of the database 
37155 ** file in the file-system. This only happens when committing a transaction,
37156 ** or rolling back a transaction (including rolling back a hot-journal).
37157 **
37158 ** If the main database file is not open, or the pager is not in either
37159 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
37160 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
37161 ** If the file on disk is currently larger than nPage pages, then use the VFS
37162 ** xTruncate() method to truncate it.
37163 **
37164 ** Or, it might might be the case that the file on disk is smaller than 
37165 ** nPage pages. Some operating system implementations can get confused if 
37166 ** you try to truncate a file to some size that is larger than it 
37167 ** currently is, so detect this case and write a single zero byte to 
37168 ** the end of the new file instead.
37169 **
37170 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
37171 ** the database file, return the error code to the caller.
37172 */
37173 static int pager_truncate(Pager *pPager, Pgno nPage){
37174   int rc = SQLITE_OK;
37175   assert( pPager->eState!=PAGER_ERROR );
37176   assert( pPager->eState!=PAGER_READER );
37177   
37178   if( isOpen(pPager->fd) 
37179    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
37180   ){
37181     i64 currentSize, newSize;
37182     assert( pPager->eLock==EXCLUSIVE_LOCK );
37183     /* TODO: Is it safe to use Pager.dbFileSize here? */
37184     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
37185     newSize = pPager->pageSize*(i64)nPage;
37186     if( rc==SQLITE_OK && currentSize!=newSize ){
37187       if( currentSize>newSize ){
37188         rc = sqlite3OsTruncate(pPager->fd, newSize);
37189       }else{
37190         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
37191       }
37192       if( rc==SQLITE_OK ){
37193         pPager->dbFileSize = nPage;
37194       }
37195     }
37196   }
37197   return rc;
37198 }
37199
37200 /*
37201 ** Set the value of the Pager.sectorSize variable for the given
37202 ** pager based on the value returned by the xSectorSize method
37203 ** of the open database file. The sector size will be used used 
37204 ** to determine the size and alignment of journal header and 
37205 ** master journal pointers within created journal files.
37206 **
37207 ** For temporary files the effective sector size is always 512 bytes.
37208 **
37209 ** Otherwise, for non-temporary files, the effective sector size is
37210 ** the value returned by the xSectorSize() method rounded up to 32 if
37211 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
37212 ** is greater than MAX_SECTOR_SIZE.
37213 */
37214 static void setSectorSize(Pager *pPager){
37215   assert( isOpen(pPager->fd) || pPager->tempFile );
37216
37217   if( !pPager->tempFile ){
37218     /* Sector size doesn't matter for temporary files. Also, the file
37219     ** may not have been opened yet, in which case the OsSectorSize()
37220     ** call will segfault.
37221     */
37222     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
37223   }
37224   if( pPager->sectorSize<32 ){
37225     pPager->sectorSize = 512;
37226   }
37227   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
37228     assert( MAX_SECTOR_SIZE>=512 );
37229     pPager->sectorSize = MAX_SECTOR_SIZE;
37230   }
37231 }
37232
37233 /*
37234 ** Playback the journal and thus restore the database file to
37235 ** the state it was in before we started making changes.  
37236 **
37237 ** The journal file format is as follows: 
37238 **
37239 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
37240 **  (2)  4 byte big-endian integer which is the number of valid page records
37241 **       in the journal.  If this value is 0xffffffff, then compute the
37242 **       number of page records from the journal size.
37243 **  (3)  4 byte big-endian integer which is the initial value for the 
37244 **       sanity checksum.
37245 **  (4)  4 byte integer which is the number of pages to truncate the
37246 **       database to during a rollback.
37247 **  (5)  4 byte big-endian integer which is the sector size.  The header
37248 **       is this many bytes in size.
37249 **  (6)  4 byte big-endian integer which is the page size.
37250 **  (7)  zero padding out to the next sector size.
37251 **  (8)  Zero or more pages instances, each as follows:
37252 **        +  4 byte page number.
37253 **        +  pPager->pageSize bytes of data.
37254 **        +  4 byte checksum
37255 **
37256 ** When we speak of the journal header, we mean the first 7 items above.
37257 ** Each entry in the journal is an instance of the 8th item.
37258 **
37259 ** Call the value from the second bullet "nRec".  nRec is the number of
37260 ** valid page entries in the journal.  In most cases, you can compute the
37261 ** value of nRec from the size of the journal file.  But if a power
37262 ** failure occurred while the journal was being written, it could be the
37263 ** case that the size of the journal file had already been increased but
37264 ** the extra entries had not yet made it safely to disk.  In such a case,
37265 ** the value of nRec computed from the file size would be too large.  For
37266 ** that reason, we always use the nRec value in the header.
37267 **
37268 ** If the nRec value is 0xffffffff it means that nRec should be computed
37269 ** from the file size.  This value is used when the user selects the
37270 ** no-sync option for the journal.  A power failure could lead to corruption
37271 ** in this case.  But for things like temporary table (which will be
37272 ** deleted when the power is restored) we don't care.  
37273 **
37274 ** If the file opened as the journal file is not a well-formed
37275 ** journal file then all pages up to the first corrupted page are rolled
37276 ** back (or no pages if the journal header is corrupted). The journal file
37277 ** is then deleted and SQLITE_OK returned, just as if no corruption had
37278 ** been encountered.
37279 **
37280 ** If an I/O or malloc() error occurs, the journal-file is not deleted
37281 ** and an error code is returned.
37282 **
37283 ** The isHot parameter indicates that we are trying to rollback a journal
37284 ** that might be a hot journal.  Or, it could be that the journal is 
37285 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
37286 ** If the journal really is hot, reset the pager cache prior rolling
37287 ** back any content.  If the journal is merely persistent, no reset is
37288 ** needed.
37289 */
37290 static int pager_playback(Pager *pPager, int isHot){
37291   sqlite3_vfs *pVfs = pPager->pVfs;
37292   i64 szJ;                 /* Size of the journal file in bytes */
37293   u32 nRec;                /* Number of Records in the journal */
37294   u32 u;                   /* Unsigned loop counter */
37295   Pgno mxPg = 0;           /* Size of the original file in pages */
37296   int rc;                  /* Result code of a subroutine */
37297   int res = 1;             /* Value returned by sqlite3OsAccess() */
37298   char *zMaster = 0;       /* Name of master journal file if any */
37299   int needPagerReset;      /* True to reset page prior to first page rollback */
37300
37301   /* Figure out how many records are in the journal.  Abort early if
37302   ** the journal is empty.
37303   */
37304   assert( isOpen(pPager->jfd) );
37305   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
37306   if( rc!=SQLITE_OK ){
37307     goto end_playback;
37308   }
37309
37310   /* Read the master journal name from the journal, if it is present.
37311   ** If a master journal file name is specified, but the file is not
37312   ** present on disk, then the journal is not hot and does not need to be
37313   ** played back.
37314   **
37315   ** TODO: Technically the following is an error because it assumes that
37316   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
37317   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
37318   **  mxPathname is 512, which is the same as the minimum allowable value
37319   ** for pageSize.
37320   */
37321   zMaster = pPager->pTmpSpace;
37322   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
37323   if( rc==SQLITE_OK && zMaster[0] ){
37324     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
37325   }
37326   zMaster = 0;
37327   if( rc!=SQLITE_OK || !res ){
37328     goto end_playback;
37329   }
37330   pPager->journalOff = 0;
37331   needPagerReset = isHot;
37332
37333   /* This loop terminates either when a readJournalHdr() or 
37334   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
37335   ** occurs. 
37336   */
37337   while( 1 ){
37338     /* Read the next journal header from the journal file.  If there are
37339     ** not enough bytes left in the journal file for a complete header, or
37340     ** it is corrupted, then a process must have failed while writing it.
37341     ** This indicates nothing more needs to be rolled back.
37342     */
37343     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
37344     if( rc!=SQLITE_OK ){ 
37345       if( rc==SQLITE_DONE ){
37346         rc = SQLITE_OK;
37347       }
37348       goto end_playback;
37349     }
37350
37351     /* If nRec is 0xffffffff, then this journal was created by a process
37352     ** working in no-sync mode. This means that the rest of the journal
37353     ** file consists of pages, there are no more journal headers. Compute
37354     ** the value of nRec based on this assumption.
37355     */
37356     if( nRec==0xffffffff ){
37357       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
37358       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
37359     }
37360
37361     /* If nRec is 0 and this rollback is of a transaction created by this
37362     ** process and if this is the final header in the journal, then it means
37363     ** that this part of the journal was being filled but has not yet been
37364     ** synced to disk.  Compute the number of pages based on the remaining
37365     ** size of the file.
37366     **
37367     ** The third term of the test was added to fix ticket #2565.
37368     ** When rolling back a hot journal, nRec==0 always means that the next
37369     ** chunk of the journal contains zero pages to be rolled back.  But
37370     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
37371     ** the journal, it means that the journal might contain additional
37372     ** pages that need to be rolled back and that the number of pages 
37373     ** should be computed based on the journal file size.
37374     */
37375     if( nRec==0 && !isHot &&
37376         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
37377       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
37378     }
37379
37380     /* If this is the first header read from the journal, truncate the
37381     ** database file back to its original size.
37382     */
37383     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
37384       rc = pager_truncate(pPager, mxPg);
37385       if( rc!=SQLITE_OK ){
37386         goto end_playback;
37387       }
37388       pPager->dbSize = mxPg;
37389     }
37390
37391     /* Copy original pages out of the journal and back into the 
37392     ** database file and/or page cache.
37393     */
37394     for(u=0; u<nRec; u++){
37395       if( needPagerReset ){
37396         pager_reset(pPager);
37397         needPagerReset = 0;
37398       }
37399       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
37400       if( rc!=SQLITE_OK ){
37401         if( rc==SQLITE_DONE ){
37402           rc = SQLITE_OK;
37403           pPager->journalOff = szJ;
37404           break;
37405         }else if( rc==SQLITE_IOERR_SHORT_READ ){
37406           /* If the journal has been truncated, simply stop reading and
37407           ** processing the journal. This might happen if the journal was
37408           ** not completely written and synced prior to a crash.  In that
37409           ** case, the database should have never been written in the
37410           ** first place so it is OK to simply abandon the rollback. */
37411           rc = SQLITE_OK;
37412           goto end_playback;
37413         }else{
37414           /* If we are unable to rollback, quit and return the error
37415           ** code.  This will cause the pager to enter the error state
37416           ** so that no further harm will be done.  Perhaps the next
37417           ** process to come along will be able to rollback the database.
37418           */
37419           goto end_playback;
37420         }
37421       }
37422     }
37423   }
37424   /*NOTREACHED*/
37425   assert( 0 );
37426
37427 end_playback:
37428   /* Following a rollback, the database file should be back in its original
37429   ** state prior to the start of the transaction, so invoke the
37430   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
37431   ** assertion that the transaction counter was modified.
37432   */
37433   assert(
37434     pPager->fd->pMethods==0 ||
37435     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
37436   );
37437
37438   /* If this playback is happening automatically as a result of an IO or 
37439   ** malloc error that occurred after the change-counter was updated but 
37440   ** before the transaction was committed, then the change-counter 
37441   ** modification may just have been reverted. If this happens in exclusive 
37442   ** mode, then subsequent transactions performed by the connection will not
37443   ** update the change-counter at all. This may lead to cache inconsistency
37444   ** problems for other processes at some point in the future. So, just
37445   ** in case this has happened, clear the changeCountDone flag now.
37446   */
37447   pPager->changeCountDone = pPager->tempFile;
37448
37449   if( rc==SQLITE_OK ){
37450     zMaster = pPager->pTmpSpace;
37451     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
37452     testcase( rc!=SQLITE_OK );
37453   }
37454   if( rc==SQLITE_OK && !pPager->noSync 
37455    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
37456   ){
37457     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
37458   }
37459   if( rc==SQLITE_OK ){
37460     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
37461     testcase( rc!=SQLITE_OK );
37462   }
37463   if( rc==SQLITE_OK && zMaster[0] && res ){
37464     /* If there was a master journal and this routine will return success,
37465     ** see if it is possible to delete the master journal.
37466     */
37467     rc = pager_delmaster(pPager, zMaster);
37468     testcase( rc!=SQLITE_OK );
37469   }
37470
37471   /* The Pager.sectorSize variable may have been updated while rolling
37472   ** back a journal created by a process with a different sector size
37473   ** value. Reset it to the correct value for this process.
37474   */
37475   setSectorSize(pPager);
37476   return rc;
37477 }
37478
37479
37480 /*
37481 ** Read the content for page pPg out of the database file and into 
37482 ** pPg->pData. A shared lock or greater must be held on the database
37483 ** file before this function is called.
37484 **
37485 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
37486 ** the value read from the database file.
37487 **
37488 ** If an IO error occurs, then the IO error is returned to the caller.
37489 ** Otherwise, SQLITE_OK is returned.
37490 */
37491 static int readDbPage(PgHdr *pPg){
37492   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
37493   Pgno pgno = pPg->pgno;       /* Page number to read */
37494   int rc = SQLITE_OK;          /* Return code */
37495   int isInWal = 0;             /* True if page is in log file */
37496   int pgsz = pPager->pageSize; /* Number of bytes to read */
37497
37498   assert( pPager->eState>=PAGER_READER && !MEMDB );
37499   assert( isOpen(pPager->fd) );
37500
37501   if( NEVER(!isOpen(pPager->fd)) ){
37502     assert( pPager->tempFile );
37503     memset(pPg->pData, 0, pPager->pageSize);
37504     return SQLITE_OK;
37505   }
37506
37507   if( pagerUseWal(pPager) ){
37508     /* Try to pull the page from the write-ahead log. */
37509     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
37510   }
37511   if( rc==SQLITE_OK && !isInWal ){
37512     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
37513     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
37514     if( rc==SQLITE_IOERR_SHORT_READ ){
37515       rc = SQLITE_OK;
37516     }
37517   }
37518
37519   if( pgno==1 ){
37520     if( rc ){
37521       /* If the read is unsuccessful, set the dbFileVers[] to something
37522       ** that will never be a valid file version.  dbFileVers[] is a copy
37523       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
37524       ** zero or the size of the database in page. Bytes 32..35 and 35..39
37525       ** should be page numbers which are never 0xffffffff.  So filling
37526       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
37527       **
37528       ** For an encrypted database, the situation is more complex:  bytes
37529       ** 24..39 of the database are white noise.  But the probability of
37530       ** white noising equaling 16 bytes of 0xff is vanishingly small so
37531       ** we should still be ok.
37532       */
37533       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
37534     }else{
37535       u8 *dbFileVers = &((u8*)pPg->pData)[24];
37536       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
37537     }
37538   }
37539   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
37540
37541   PAGER_INCR(sqlite3_pager_readdb_count);
37542   PAGER_INCR(pPager->nRead);
37543   IOTRACE(("PGIN %p %d\n", pPager, pgno));
37544   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
37545                PAGERID(pPager), pgno, pager_pagehash(pPg)));
37546
37547   return rc;
37548 }
37549
37550 #ifndef SQLITE_OMIT_WAL
37551 /*
37552 ** This function is invoked once for each page that has already been 
37553 ** written into the log file when a WAL transaction is rolled back.
37554 ** Parameter iPg is the page number of said page. The pCtx argument 
37555 ** is actually a pointer to the Pager structure.
37556 **
37557 ** If page iPg is present in the cache, and has no outstanding references,
37558 ** it is discarded. Otherwise, if there are one or more outstanding
37559 ** references, the page content is reloaded from the database. If the
37560 ** attempt to reload content from the database is required and fails, 
37561 ** return an SQLite error code. Otherwise, SQLITE_OK.
37562 */
37563 static int pagerUndoCallback(void *pCtx, Pgno iPg){
37564   int rc = SQLITE_OK;
37565   Pager *pPager = (Pager *)pCtx;
37566   PgHdr *pPg;
37567
37568   pPg = sqlite3PagerLookup(pPager, iPg);
37569   if( pPg ){
37570     if( sqlite3PcachePageRefcount(pPg)==1 ){
37571       sqlite3PcacheDrop(pPg);
37572     }else{
37573       rc = readDbPage(pPg);
37574       if( rc==SQLITE_OK ){
37575         pPager->xReiniter(pPg);
37576       }
37577       sqlite3PagerUnref(pPg);
37578     }
37579   }
37580
37581   /* Normally, if a transaction is rolled back, any backup processes are
37582   ** updated as data is copied out of the rollback journal and into the
37583   ** database. This is not generally possible with a WAL database, as
37584   ** rollback involves simply truncating the log file. Therefore, if one
37585   ** or more frames have already been written to the log (and therefore 
37586   ** also copied into the backup databases) as part of this transaction,
37587   ** the backups must be restarted.
37588   */
37589   sqlite3BackupRestart(pPager->pBackup);
37590
37591   return rc;
37592 }
37593
37594 /*
37595 ** This function is called to rollback a transaction on a WAL database.
37596 */
37597 static int pagerRollbackWal(Pager *pPager){
37598   int rc;                         /* Return Code */
37599   PgHdr *pList;                   /* List of dirty pages to revert */
37600
37601   /* For all pages in the cache that are currently dirty or have already
37602   ** been written (but not committed) to the log file, do one of the 
37603   ** following:
37604   **
37605   **   + Discard the cached page (if refcount==0), or
37606   **   + Reload page content from the database (if refcount>0).
37607   */
37608   pPager->dbSize = pPager->dbOrigSize;
37609   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
37610   pList = sqlite3PcacheDirtyList(pPager->pPCache);
37611   while( pList && rc==SQLITE_OK ){
37612     PgHdr *pNext = pList->pDirty;
37613     rc = pagerUndoCallback((void *)pPager, pList->pgno);
37614     pList = pNext;
37615   }
37616
37617   return rc;
37618 }
37619
37620 /*
37621 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
37622 ** the contents of the list of pages headed by pList (connected by pDirty),
37623 ** this function notifies any active backup processes that the pages have
37624 ** changed. 
37625 */ 
37626 static int pagerWalFrames(
37627   Pager *pPager,                  /* Pager object */
37628   PgHdr *pList,                   /* List of frames to log */
37629   Pgno nTruncate,                 /* Database size after this commit */
37630   int isCommit,                   /* True if this is a commit */
37631   int syncFlags                   /* Flags to pass to OsSync() (or 0) */
37632 ){
37633   int rc;                         /* Return code */
37634
37635   assert( pPager->pWal );
37636   rc = sqlite3WalFrames(pPager->pWal, 
37637       pPager->pageSize, pList, nTruncate, isCommit, syncFlags
37638   );
37639   if( rc==SQLITE_OK && pPager->pBackup ){
37640     PgHdr *p;
37641     for(p=pList; p; p=p->pDirty){
37642       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
37643     }
37644   }
37645
37646 #ifdef SQLITE_CHECK_PAGES
37647   {
37648     PgHdr *p;
37649     for(p=pList; p; p=p->pDirty) pager_set_pagehash(p);
37650   }
37651 #endif
37652
37653   return rc;
37654 }
37655
37656 /*
37657 ** Begin a read transaction on the WAL.
37658 **
37659 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
37660 ** makes a snapshot of the database at the current point in time and preserves
37661 ** that snapshot for use by the reader in spite of concurrently changes by
37662 ** other writers or checkpointers.
37663 */
37664 static int pagerBeginReadTransaction(Pager *pPager){
37665   int rc;                         /* Return code */
37666   int changed = 0;                /* True if cache must be reset */
37667
37668   assert( pagerUseWal(pPager) );
37669   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
37670
37671   /* sqlite3WalEndReadTransaction() was not called for the previous
37672   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
37673   ** are in locking_mode=NORMAL and EndRead() was previously called,
37674   ** the duplicate call is harmless.
37675   */
37676   sqlite3WalEndReadTransaction(pPager->pWal);
37677
37678   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
37679   if( rc!=SQLITE_OK || changed ){
37680     pager_reset(pPager);
37681   }
37682
37683   return rc;
37684 }
37685 #endif
37686
37687 /*
37688 ** This function is called as part of the transition from PAGER_OPEN
37689 ** to PAGER_READER state to determine the size of the database file
37690 ** in pages (assuming the page size currently stored in Pager.pageSize).
37691 **
37692 ** If no error occurs, SQLITE_OK is returned and the size of the database
37693 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
37694 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
37695 */
37696 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
37697   Pgno nPage;                     /* Value to return via *pnPage */
37698
37699   /* Query the WAL sub-system for the database size. The WalDbsize()
37700   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
37701   ** if the database size is not available. The database size is not
37702   ** available from the WAL sub-system if the log file is empty or
37703   ** contains no valid committed transactions.
37704   */
37705   assert( pPager->eState==PAGER_OPEN );
37706   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
37707   nPage = sqlite3WalDbsize(pPager->pWal);
37708
37709   /* If the database size was not available from the WAL sub-system,
37710   ** determine it based on the size of the database file. If the size
37711   ** of the database file is not an integer multiple of the page-size,
37712   ** round down to the nearest page. Except, any file larger than 0
37713   ** bytes in size is considered to contain at least one page.
37714   */
37715   if( nPage==0 ){
37716     i64 n = 0;                    /* Size of db file in bytes */
37717     assert( isOpen(pPager->fd) || pPager->tempFile );
37718     if( isOpen(pPager->fd) ){
37719       int rc = sqlite3OsFileSize(pPager->fd, &n);
37720       if( rc!=SQLITE_OK ){
37721         return rc;
37722       }
37723     }
37724     nPage = (Pgno)(n / pPager->pageSize);
37725     if( nPage==0 && n>0 ){
37726       nPage = 1;
37727     }
37728   }
37729
37730   /* If the current number of pages in the file is greater than the
37731   ** configured maximum pager number, increase the allowed limit so
37732   ** that the file can be read.
37733   */
37734   if( nPage>pPager->mxPgno ){
37735     pPager->mxPgno = (Pgno)nPage;
37736   }
37737
37738   *pnPage = nPage;
37739   return SQLITE_OK;
37740 }
37741
37742 #ifndef SQLITE_OMIT_WAL
37743 /*
37744 ** Check if the *-wal file that corresponds to the database opened by pPager
37745 ** exists if the database is not empy, or verify that the *-wal file does
37746 ** not exist (by deleting it) if the database file is empty.
37747 **
37748 ** If the database is not empty and the *-wal file exists, open the pager
37749 ** in WAL mode.  If the database is empty or if no *-wal file exists and
37750 ** if no error occurs, make sure Pager.journalMode is not set to
37751 ** PAGER_JOURNALMODE_WAL.
37752 **
37753 ** Return SQLITE_OK or an error code.
37754 **
37755 ** The caller must hold a SHARED lock on the database file to call this
37756 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
37757 ** a WAL on a none-empty database, this ensures there is no race condition 
37758 ** between the xAccess() below and an xDelete() being executed by some 
37759 ** other connection.
37760 */
37761 static int pagerOpenWalIfPresent(Pager *pPager){
37762   int rc = SQLITE_OK;
37763   assert( pPager->eState==PAGER_OPEN );
37764   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
37765
37766   if( !pPager->tempFile ){
37767     int isWal;                    /* True if WAL file exists */
37768     Pgno nPage;                   /* Size of the database file */
37769
37770     rc = pagerPagecount(pPager, &nPage);
37771     if( rc ) return rc;
37772     if( nPage==0 ){
37773       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
37774       isWal = 0;
37775     }else{
37776       rc = sqlite3OsAccess(
37777           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
37778       );
37779     }
37780     if( rc==SQLITE_OK ){
37781       if( isWal ){
37782         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
37783         rc = sqlite3PagerOpenWal(pPager, 0);
37784       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
37785         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
37786       }
37787     }
37788   }
37789   return rc;
37790 }
37791 #endif
37792
37793 /*
37794 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
37795 ** the entire master journal file. The case pSavepoint==NULL occurs when 
37796 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
37797 ** savepoint.
37798 **
37799 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
37800 ** being rolled back), then the rollback consists of up to three stages,
37801 ** performed in the order specified:
37802 **
37803 **   * Pages are played back from the main journal starting at byte
37804 **     offset PagerSavepoint.iOffset and continuing to 
37805 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
37806 **     file if PagerSavepoint.iHdrOffset is zero.
37807 **
37808 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
37809 **     back starting from the journal header immediately following 
37810 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
37811 **
37812 **   * Pages are then played back from the sub-journal file, starting
37813 **     with the PagerSavepoint.iSubRec and continuing to the end of
37814 **     the journal file.
37815 **
37816 ** Throughout the rollback process, each time a page is rolled back, the
37817 ** corresponding bit is set in a bitvec structure (variable pDone in the
37818 ** implementation below). This is used to ensure that a page is only
37819 ** rolled back the first time it is encountered in either journal.
37820 **
37821 ** If pSavepoint is NULL, then pages are only played back from the main
37822 ** journal file. There is no need for a bitvec in this case.
37823 **
37824 ** In either case, before playback commences the Pager.dbSize variable
37825 ** is reset to the value that it held at the start of the savepoint 
37826 ** (or transaction). No page with a page-number greater than this value
37827 ** is played back. If one is encountered it is simply skipped.
37828 */
37829 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
37830   i64 szJ;                 /* Effective size of the main journal */
37831   i64 iHdrOff;             /* End of first segment of main-journal records */
37832   int rc = SQLITE_OK;      /* Return code */
37833   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
37834
37835   assert( pPager->eState!=PAGER_ERROR );
37836   assert( pPager->eState>=PAGER_WRITER_LOCKED );
37837
37838   /* Allocate a bitvec to use to store the set of pages rolled back */
37839   if( pSavepoint ){
37840     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
37841     if( !pDone ){
37842       return SQLITE_NOMEM;
37843     }
37844   }
37845
37846   /* Set the database size back to the value it was before the savepoint 
37847   ** being reverted was opened.
37848   */
37849   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
37850   pPager->changeCountDone = pPager->tempFile;
37851
37852   if( !pSavepoint && pagerUseWal(pPager) ){
37853     return pagerRollbackWal(pPager);
37854   }
37855
37856   /* Use pPager->journalOff as the effective size of the main rollback
37857   ** journal.  The actual file might be larger than this in
37858   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
37859   ** past pPager->journalOff is off-limits to us.
37860   */
37861   szJ = pPager->journalOff;
37862   assert( pagerUseWal(pPager)==0 || szJ==0 );
37863
37864   /* Begin by rolling back records from the main journal starting at
37865   ** PagerSavepoint.iOffset and continuing to the next journal header.
37866   ** There might be records in the main journal that have a page number
37867   ** greater than the current database size (pPager->dbSize) but those
37868   ** will be skipped automatically.  Pages are added to pDone as they
37869   ** are played back.
37870   */
37871   if( pSavepoint && !pagerUseWal(pPager) ){
37872     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
37873     pPager->journalOff = pSavepoint->iOffset;
37874     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
37875       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
37876     }
37877     assert( rc!=SQLITE_DONE );
37878   }else{
37879     pPager->journalOff = 0;
37880   }
37881
37882   /* Continue rolling back records out of the main journal starting at
37883   ** the first journal header seen and continuing until the effective end
37884   ** of the main journal file.  Continue to skip out-of-range pages and
37885   ** continue adding pages rolled back to pDone.
37886   */
37887   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
37888     u32 ii;            /* Loop counter */
37889     u32 nJRec = 0;     /* Number of Journal Records */
37890     u32 dummy;
37891     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
37892     assert( rc!=SQLITE_DONE );
37893
37894     /*
37895     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
37896     ** test is related to ticket #2565.  See the discussion in the
37897     ** pager_playback() function for additional information.
37898     */
37899     if( nJRec==0 
37900      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
37901     ){
37902       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
37903     }
37904     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
37905       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
37906     }
37907     assert( rc!=SQLITE_DONE );
37908   }
37909   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
37910
37911   /* Finally,  rollback pages from the sub-journal.  Page that were
37912   ** previously rolled back out of the main journal (and are hence in pDone)
37913   ** will be skipped.  Out-of-range pages are also skipped.
37914   */
37915   if( pSavepoint ){
37916     u32 ii;            /* Loop counter */
37917     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
37918
37919     if( pagerUseWal(pPager) ){
37920       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
37921     }
37922     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
37923       assert( offset==ii*(4+pPager->pageSize) );
37924       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
37925     }
37926     assert( rc!=SQLITE_DONE );
37927   }
37928
37929   sqlite3BitvecDestroy(pDone);
37930   if( rc==SQLITE_OK ){
37931     pPager->journalOff = szJ;
37932   }
37933
37934   return rc;
37935 }
37936
37937 /*
37938 ** Change the maximum number of in-memory pages that are allowed.
37939 */
37940 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
37941   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
37942 }
37943
37944 /*
37945 ** Adjust the robustness of the database to damage due to OS crashes
37946 ** or power failures by changing the number of syncs()s when writing
37947 ** the rollback journal.  There are three levels:
37948 **
37949 **    OFF       sqlite3OsSync() is never called.  This is the default
37950 **              for temporary and transient files.
37951 **
37952 **    NORMAL    The journal is synced once before writes begin on the
37953 **              database.  This is normally adequate protection, but
37954 **              it is theoretically possible, though very unlikely,
37955 **              that an inopertune power failure could leave the journal
37956 **              in a state which would cause damage to the database
37957 **              when it is rolled back.
37958 **
37959 **    FULL      The journal is synced twice before writes begin on the
37960 **              database (with some additional information - the nRec field
37961 **              of the journal header - being written in between the two
37962 **              syncs).  If we assume that writing a
37963 **              single disk sector is atomic, then this mode provides
37964 **              assurance that the journal will not be corrupted to the
37965 **              point of causing damage to the database during rollback.
37966 **
37967 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
37968 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
37969 ** prior to the start of checkpoint and that the database file is synced
37970 ** at the conclusion of the checkpoint if the entire content of the WAL
37971 ** was written back into the database.  But no sync operations occur for
37972 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
37973 ** file is synced following each commit operation, in addition to the
37974 ** syncs associated with NORMAL.
37975 **
37976 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
37977 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
37978 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
37979 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
37980 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
37981 ** synchronous=FULL versus synchronous=NORMAL setting determines when
37982 ** the xSync primitive is called and is relevant to all platforms.
37983 **
37984 ** Numeric values associated with these states are OFF==1, NORMAL=2,
37985 ** and FULL=3.
37986 */
37987 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
37988 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
37989   Pager *pPager,        /* The pager to set safety level for */
37990   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
37991   int bFullFsync,       /* PRAGMA fullfsync */
37992   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
37993 ){
37994   assert( level>=1 && level<=3 );
37995   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
37996   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
37997   if( pPager->noSync ){
37998     pPager->syncFlags = 0;
37999     pPager->ckptSyncFlags = 0;
38000   }else if( bFullFsync ){
38001     pPager->syncFlags = SQLITE_SYNC_FULL;
38002     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
38003   }else if( bCkptFullFsync ){
38004     pPager->syncFlags = SQLITE_SYNC_NORMAL;
38005     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
38006   }else{
38007     pPager->syncFlags = SQLITE_SYNC_NORMAL;
38008     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
38009   }
38010 }
38011 #endif
38012
38013 /*
38014 ** The following global variable is incremented whenever the library
38015 ** attempts to open a temporary file.  This information is used for
38016 ** testing and analysis only.  
38017 */
38018 #ifdef SQLITE_TEST
38019 SQLITE_API int sqlite3_opentemp_count = 0;
38020 #endif
38021
38022 /*
38023 ** Open a temporary file.
38024 **
38025 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
38026 ** or some other error code if we fail. The OS will automatically 
38027 ** delete the temporary file when it is closed.
38028 **
38029 ** The flags passed to the VFS layer xOpen() call are those specified
38030 ** by parameter vfsFlags ORed with the following:
38031 **
38032 **     SQLITE_OPEN_READWRITE
38033 **     SQLITE_OPEN_CREATE
38034 **     SQLITE_OPEN_EXCLUSIVE
38035 **     SQLITE_OPEN_DELETEONCLOSE
38036 */
38037 static int pagerOpentemp(
38038   Pager *pPager,        /* The pager object */
38039   sqlite3_file *pFile,  /* Write the file descriptor here */
38040   int vfsFlags          /* Flags passed through to the VFS */
38041 ){
38042   int rc;               /* Return code */
38043
38044 #ifdef SQLITE_TEST
38045   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
38046 #endif
38047
38048   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
38049             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
38050   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
38051   assert( rc!=SQLITE_OK || isOpen(pFile) );
38052   return rc;
38053 }
38054
38055 /*
38056 ** Set the busy handler function.
38057 **
38058 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
38059 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
38060 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
38061 ** lock. It does *not* invoke the busy handler when upgrading from
38062 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
38063 ** (which occurs during hot-journal rollback). Summary:
38064 **
38065 **   Transition                        | Invokes xBusyHandler
38066 **   --------------------------------------------------------
38067 **   NO_LOCK       -> SHARED_LOCK      | Yes
38068 **   SHARED_LOCK   -> RESERVED_LOCK    | No
38069 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
38070 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
38071 **
38072 ** If the busy-handler callback returns non-zero, the lock is 
38073 ** retried. If it returns zero, then the SQLITE_BUSY error is
38074 ** returned to the caller of the pager API function.
38075 */
38076 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
38077   Pager *pPager,                       /* Pager object */
38078   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
38079   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
38080 ){  
38081   pPager->xBusyHandler = xBusyHandler;
38082   pPager->pBusyHandlerArg = pBusyHandlerArg;
38083 }
38084
38085 /*
38086 ** Change the page size used by the Pager object. The new page size 
38087 ** is passed in *pPageSize.
38088 **
38089 ** If the pager is in the error state when this function is called, it
38090 ** is a no-op. The value returned is the error state error code (i.e. 
38091 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
38092 **
38093 ** Otherwise, if all of the following are true:
38094 **
38095 **   * the new page size (value of *pPageSize) is valid (a power 
38096 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
38097 **
38098 **   * there are no outstanding page references, and
38099 **
38100 **   * the database is either not an in-memory database or it is
38101 **     an in-memory database that currently consists of zero pages.
38102 **
38103 ** then the pager object page size is set to *pPageSize.
38104 **
38105 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
38106 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
38107 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
38108 ** In all other cases, SQLITE_OK is returned.
38109 **
38110 ** If the page size is not changed, either because one of the enumerated
38111 ** conditions above is not true, the pager was in error state when this
38112 ** function was called, or because the memory allocation attempt failed, 
38113 ** then *pPageSize is set to the old, retained page size before returning.
38114 */
38115 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
38116   int rc = SQLITE_OK;
38117
38118   /* It is not possible to do a full assert_pager_state() here, as this
38119   ** function may be called from within PagerOpen(), before the state
38120   ** of the Pager object is internally consistent.
38121   **
38122   ** At one point this function returned an error if the pager was in 
38123   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
38124   ** there is at least one outstanding page reference, this function
38125   ** is a no-op for that case anyhow.
38126   */
38127
38128   u32 pageSize = *pPageSize;
38129   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
38130   if( (pPager->memDb==0 || pPager->dbSize==0)
38131    && sqlite3PcacheRefCount(pPager->pPCache)==0 
38132    && pageSize && pageSize!=(u32)pPager->pageSize 
38133   ){
38134     char *pNew = NULL;             /* New temp space */
38135     i64 nByte = 0;
38136
38137     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
38138       rc = sqlite3OsFileSize(pPager->fd, &nByte);
38139     }
38140     if( rc==SQLITE_OK ){
38141       pNew = (char *)sqlite3PageMalloc(pageSize);
38142       if( !pNew ) rc = SQLITE_NOMEM;
38143     }
38144
38145     if( rc==SQLITE_OK ){
38146       pager_reset(pPager);
38147       pPager->dbSize = (Pgno)(nByte/pageSize);
38148       pPager->pageSize = pageSize;
38149       sqlite3PageFree(pPager->pTmpSpace);
38150       pPager->pTmpSpace = pNew;
38151       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
38152     }
38153   }
38154
38155   *pPageSize = pPager->pageSize;
38156   if( rc==SQLITE_OK ){
38157     if( nReserve<0 ) nReserve = pPager->nReserve;
38158     assert( nReserve>=0 && nReserve<1000 );
38159     pPager->nReserve = (i16)nReserve;
38160     pagerReportSize(pPager);
38161   }
38162   return rc;
38163 }
38164
38165 /*
38166 ** Return a pointer to the "temporary page" buffer held internally
38167 ** by the pager.  This is a buffer that is big enough to hold the
38168 ** entire content of a database page.  This buffer is used internally
38169 ** during rollback and will be overwritten whenever a rollback
38170 ** occurs.  But other modules are free to use it too, as long as
38171 ** no rollbacks are happening.
38172 */
38173 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
38174   return pPager->pTmpSpace;
38175 }
38176
38177 /*
38178 ** Attempt to set the maximum database page count if mxPage is positive. 
38179 ** Make no changes if mxPage is zero or negative.  And never reduce the
38180 ** maximum page count below the current size of the database.
38181 **
38182 ** Regardless of mxPage, return the current maximum page count.
38183 */
38184 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
38185   if( mxPage>0 ){
38186     pPager->mxPgno = mxPage;
38187   }
38188   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
38189   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
38190   return pPager->mxPgno;
38191 }
38192
38193 /*
38194 ** The following set of routines are used to disable the simulated
38195 ** I/O error mechanism.  These routines are used to avoid simulated
38196 ** errors in places where we do not care about errors.
38197 **
38198 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
38199 ** and generate no code.
38200 */
38201 #ifdef SQLITE_TEST
38202 SQLITE_API extern int sqlite3_io_error_pending;
38203 SQLITE_API extern int sqlite3_io_error_hit;
38204 static int saved_cnt;
38205 void disable_simulated_io_errors(void){
38206   saved_cnt = sqlite3_io_error_pending;
38207   sqlite3_io_error_pending = -1;
38208 }
38209 void enable_simulated_io_errors(void){
38210   sqlite3_io_error_pending = saved_cnt;
38211 }
38212 #else
38213 # define disable_simulated_io_errors()
38214 # define enable_simulated_io_errors()
38215 #endif
38216
38217 /*
38218 ** Read the first N bytes from the beginning of the file into memory
38219 ** that pDest points to. 
38220 **
38221 ** If the pager was opened on a transient file (zFilename==""), or
38222 ** opened on a file less than N bytes in size, the output buffer is
38223 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
38224 ** function is used to read database headers, and a new transient or
38225 ** zero sized database has a header than consists entirely of zeroes.
38226 **
38227 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
38228 ** the error code is returned to the caller and the contents of the
38229 ** output buffer undefined.
38230 */
38231 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
38232   int rc = SQLITE_OK;
38233   memset(pDest, 0, N);
38234   assert( isOpen(pPager->fd) || pPager->tempFile );
38235
38236   /* This routine is only called by btree immediately after creating
38237   ** the Pager object.  There has not been an opportunity to transition
38238   ** to WAL mode yet.
38239   */
38240   assert( !pagerUseWal(pPager) );
38241
38242   if( isOpen(pPager->fd) ){
38243     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
38244     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
38245     if( rc==SQLITE_IOERR_SHORT_READ ){
38246       rc = SQLITE_OK;
38247     }
38248   }
38249   return rc;
38250 }
38251
38252 /*
38253 ** This function may only be called when a read-transaction is open on
38254 ** the pager. It returns the total number of pages in the database.
38255 **
38256 ** However, if the file is between 1 and <page-size> bytes in size, then 
38257 ** this is considered a 1 page file.
38258 */
38259 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
38260   assert( pPager->eState>=PAGER_READER );
38261   assert( pPager->eState!=PAGER_WRITER_FINISHED );
38262   *pnPage = (int)pPager->dbSize;
38263 }
38264
38265
38266 /*
38267 ** Try to obtain a lock of type locktype on the database file. If
38268 ** a similar or greater lock is already held, this function is a no-op
38269 ** (returning SQLITE_OK immediately).
38270 **
38271 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
38272 ** the busy callback if the lock is currently not available. Repeat 
38273 ** until the busy callback returns false or until the attempt to 
38274 ** obtain the lock succeeds.
38275 **
38276 ** Return SQLITE_OK on success and an error code if we cannot obtain
38277 ** the lock. If the lock is obtained successfully, set the Pager.state 
38278 ** variable to locktype before returning.
38279 */
38280 static int pager_wait_on_lock(Pager *pPager, int locktype){
38281   int rc;                              /* Return code */
38282
38283   /* Check that this is either a no-op (because the requested lock is 
38284   ** already held, or one of the transistions that the busy-handler
38285   ** may be invoked during, according to the comment above
38286   ** sqlite3PagerSetBusyhandler().
38287   */
38288   assert( (pPager->eLock>=locktype)
38289        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
38290        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
38291   );
38292
38293   do {
38294     rc = pagerLockDb(pPager, locktype);
38295   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
38296   return rc;
38297 }
38298
38299 /*
38300 ** Function assertTruncateConstraint(pPager) checks that one of the 
38301 ** following is true for all dirty pages currently in the page-cache:
38302 **
38303 **   a) The page number is less than or equal to the size of the 
38304 **      current database image, in pages, OR
38305 **
38306 **   b) if the page content were written at this time, it would not
38307 **      be necessary to write the current content out to the sub-journal
38308 **      (as determined by function subjRequiresPage()).
38309 **
38310 ** If the condition asserted by this function were not true, and the
38311 ** dirty page were to be discarded from the cache via the pagerStress()
38312 ** routine, pagerStress() would not write the current page content to
38313 ** the database file. If a savepoint transaction were rolled back after
38314 ** this happened, the correct behaviour would be to restore the current
38315 ** content of the page. However, since this content is not present in either
38316 ** the database file or the portion of the rollback journal and 
38317 ** sub-journal rolled back the content could not be restored and the
38318 ** database image would become corrupt. It is therefore fortunate that 
38319 ** this circumstance cannot arise.
38320 */
38321 #if defined(SQLITE_DEBUG)
38322 static void assertTruncateConstraintCb(PgHdr *pPg){
38323   assert( pPg->flags&PGHDR_DIRTY );
38324   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
38325 }
38326 static void assertTruncateConstraint(Pager *pPager){
38327   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
38328 }
38329 #else
38330 # define assertTruncateConstraint(pPager)
38331 #endif
38332
38333 /*
38334 ** Truncate the in-memory database file image to nPage pages. This 
38335 ** function does not actually modify the database file on disk. It 
38336 ** just sets the internal state of the pager object so that the 
38337 ** truncation will be done when the current transaction is committed.
38338 */
38339 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
38340   assert( pPager->dbSize>=nPage );
38341   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
38342   pPager->dbSize = nPage;
38343   assertTruncateConstraint(pPager);
38344 }
38345
38346
38347 /*
38348 ** This function is called before attempting a hot-journal rollback. It
38349 ** syncs the journal file to disk, then sets pPager->journalHdr to the
38350 ** size of the journal file so that the pager_playback() routine knows
38351 ** that the entire journal file has been synced.
38352 **
38353 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
38354 ** that if a power-failure occurs during the rollback, the process that
38355 ** attempts rollback following system recovery sees the same journal
38356 ** content as this process.
38357 **
38358 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
38359 ** an SQLite error code.
38360 */
38361 static int pagerSyncHotJournal(Pager *pPager){
38362   int rc = SQLITE_OK;
38363   if( !pPager->noSync ){
38364     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
38365   }
38366   if( rc==SQLITE_OK ){
38367     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
38368   }
38369   return rc;
38370 }
38371
38372 /*
38373 ** Shutdown the page cache.  Free all memory and close all files.
38374 **
38375 ** If a transaction was in progress when this routine is called, that
38376 ** transaction is rolled back.  All outstanding pages are invalidated
38377 ** and their memory is freed.  Any attempt to use a page associated
38378 ** with this page cache after this function returns will likely
38379 ** result in a coredump.
38380 **
38381 ** This function always succeeds. If a transaction is active an attempt
38382 ** is made to roll it back. If an error occurs during the rollback 
38383 ** a hot journal may be left in the filesystem but no error is returned
38384 ** to the caller.
38385 */
38386 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
38387   u8 *pTmp = (u8 *)pPager->pTmpSpace;
38388
38389   disable_simulated_io_errors();
38390   sqlite3BeginBenignMalloc();
38391   /* pPager->errCode = 0; */
38392   pPager->exclusiveMode = 0;
38393 #ifndef SQLITE_OMIT_WAL
38394   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
38395   pPager->pWal = 0;
38396 #endif
38397   pager_reset(pPager);
38398   if( MEMDB ){
38399     pager_unlock(pPager);
38400   }else{
38401     /* If it is open, sync the journal file before calling UnlockAndRollback.
38402     ** If this is not done, then an unsynced portion of the open journal 
38403     ** file may be played back into the database. If a power failure occurs 
38404     ** while this is happening, the database could become corrupt.
38405     **
38406     ** If an error occurs while trying to sync the journal, shift the pager
38407     ** into the ERROR state. This causes UnlockAndRollback to unlock the
38408     ** database and close the journal file without attempting to roll it
38409     ** back or finalize it. The next database user will have to do hot-journal
38410     ** rollback before accessing the database file.
38411     */
38412     if( isOpen(pPager->jfd) ){
38413       pager_error(pPager, pagerSyncHotJournal(pPager));
38414     }
38415     pagerUnlockAndRollback(pPager);
38416   }
38417   sqlite3EndBenignMalloc();
38418   enable_simulated_io_errors();
38419   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
38420   IOTRACE(("CLOSE %p\n", pPager))
38421   sqlite3OsClose(pPager->jfd);
38422   sqlite3OsClose(pPager->fd);
38423   sqlite3PageFree(pTmp);
38424   sqlite3PcacheClose(pPager->pPCache);
38425
38426 #ifdef SQLITE_HAS_CODEC
38427   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
38428 #endif
38429
38430   assert( !pPager->aSavepoint && !pPager->pInJournal );
38431   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
38432
38433   sqlite3_free(pPager);
38434   return SQLITE_OK;
38435 }
38436
38437 #if !defined(NDEBUG) || defined(SQLITE_TEST)
38438 /*
38439 ** Return the page number for page pPg.
38440 */
38441 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
38442   return pPg->pgno;
38443 }
38444 #endif
38445
38446 /*
38447 ** Increment the reference count for page pPg.
38448 */
38449 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
38450   sqlite3PcacheRef(pPg);
38451 }
38452
38453 /*
38454 ** Sync the journal. In other words, make sure all the pages that have
38455 ** been written to the journal have actually reached the surface of the
38456 ** disk and can be restored in the event of a hot-journal rollback.
38457 **
38458 ** If the Pager.noSync flag is set, then this function is a no-op.
38459 ** Otherwise, the actions required depend on the journal-mode and the 
38460 ** device characteristics of the the file-system, as follows:
38461 **
38462 **   * If the journal file is an in-memory journal file, no action need
38463 **     be taken.
38464 **
38465 **   * Otherwise, if the device does not support the SAFE_APPEND property,
38466 **     then the nRec field of the most recently written journal header
38467 **     is updated to contain the number of journal records that have
38468 **     been written following it. If the pager is operating in full-sync
38469 **     mode, then the journal file is synced before this field is updated.
38470 **
38471 **   * If the device does not support the SEQUENTIAL property, then 
38472 **     journal file is synced.
38473 **
38474 ** Or, in pseudo-code:
38475 **
38476 **   if( NOT <in-memory journal> ){
38477 **     if( NOT SAFE_APPEND ){
38478 **       if( <full-sync mode> ) xSync(<journal file>);
38479 **       <update nRec field>
38480 **     } 
38481 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
38482 **   }
38483 **
38484 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
38485 ** page currently held in memory before returning SQLITE_OK. If an IO
38486 ** error is encountered, then the IO error code is returned to the caller.
38487 */
38488 static int syncJournal(Pager *pPager, int newHdr){
38489   int rc;                         /* Return code */
38490
38491   assert( pPager->eState==PAGER_WRITER_CACHEMOD
38492        || pPager->eState==PAGER_WRITER_DBMOD
38493   );
38494   assert( assert_pager_state(pPager) );
38495   assert( !pagerUseWal(pPager) );
38496
38497   rc = sqlite3PagerExclusiveLock(pPager);
38498   if( rc!=SQLITE_OK ) return rc;
38499
38500   if( !pPager->noSync ){
38501     assert( !pPager->tempFile );
38502     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
38503       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
38504       assert( isOpen(pPager->jfd) );
38505
38506       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
38507         /* This block deals with an obscure problem. If the last connection
38508         ** that wrote to this database was operating in persistent-journal
38509         ** mode, then the journal file may at this point actually be larger
38510         ** than Pager.journalOff bytes. If the next thing in the journal
38511         ** file happens to be a journal-header (written as part of the
38512         ** previous connection's transaction), and a crash or power-failure 
38513         ** occurs after nRec is updated but before this connection writes 
38514         ** anything else to the journal file (or commits/rolls back its 
38515         ** transaction), then SQLite may become confused when doing the 
38516         ** hot-journal rollback following recovery. It may roll back all
38517         ** of this connections data, then proceed to rolling back the old,
38518         ** out-of-date data that follows it. Database corruption.
38519         **
38520         ** To work around this, if the journal file does appear to contain
38521         ** a valid header following Pager.journalOff, then write a 0x00
38522         ** byte to the start of it to prevent it from being recognized.
38523         **
38524         ** Variable iNextHdrOffset is set to the offset at which this
38525         ** problematic header will occur, if it exists. aMagic is used 
38526         ** as a temporary buffer to inspect the first couple of bytes of
38527         ** the potential journal header.
38528         */
38529         i64 iNextHdrOffset;
38530         u8 aMagic[8];
38531         u8 zHeader[sizeof(aJournalMagic)+4];
38532
38533         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
38534         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
38535
38536         iNextHdrOffset = journalHdrOffset(pPager);
38537         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
38538         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
38539           static const u8 zerobyte = 0;
38540           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
38541         }
38542         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
38543           return rc;
38544         }
38545
38546         /* Write the nRec value into the journal file header. If in
38547         ** full-synchronous mode, sync the journal first. This ensures that
38548         ** all data has really hit the disk before nRec is updated to mark
38549         ** it as a candidate for rollback.
38550         **
38551         ** This is not required if the persistent media supports the
38552         ** SAFE_APPEND property. Because in this case it is not possible 
38553         ** for garbage data to be appended to the file, the nRec field
38554         ** is populated with 0xFFFFFFFF when the journal header is written
38555         ** and never needs to be updated.
38556         */
38557         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
38558           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
38559           IOTRACE(("JSYNC %p\n", pPager))
38560           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
38561           if( rc!=SQLITE_OK ) return rc;
38562         }
38563         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
38564         rc = sqlite3OsWrite(
38565             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
38566         );
38567         if( rc!=SQLITE_OK ) return rc;
38568       }
38569       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
38570         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
38571         IOTRACE(("JSYNC %p\n", pPager))
38572         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
38573           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
38574         );
38575         if( rc!=SQLITE_OK ) return rc;
38576       }
38577
38578       pPager->journalHdr = pPager->journalOff;
38579       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
38580         pPager->nRec = 0;
38581         rc = writeJournalHdr(pPager);
38582         if( rc!=SQLITE_OK ) return rc;
38583       }
38584     }else{
38585       pPager->journalHdr = pPager->journalOff;
38586     }
38587   }
38588
38589   /* Unless the pager is in noSync mode, the journal file was just 
38590   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
38591   ** all pages.
38592   */
38593   sqlite3PcacheClearSyncFlags(pPager->pPCache);
38594   pPager->eState = PAGER_WRITER_DBMOD;
38595   assert( assert_pager_state(pPager) );
38596   return SQLITE_OK;
38597 }
38598
38599 /*
38600 ** The argument is the first in a linked list of dirty pages connected
38601 ** by the PgHdr.pDirty pointer. This function writes each one of the
38602 ** in-memory pages in the list to the database file. The argument may
38603 ** be NULL, representing an empty list. In this case this function is
38604 ** a no-op.
38605 **
38606 ** The pager must hold at least a RESERVED lock when this function
38607 ** is called. Before writing anything to the database file, this lock
38608 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
38609 ** SQLITE_BUSY is returned and no data is written to the database file.
38610 ** 
38611 ** If the pager is a temp-file pager and the actual file-system file
38612 ** is not yet open, it is created and opened before any data is 
38613 ** written out.
38614 **
38615 ** Once the lock has been upgraded and, if necessary, the file opened,
38616 ** the pages are written out to the database file in list order. Writing
38617 ** a page is skipped if it meets either of the following criteria:
38618 **
38619 **   * The page number is greater than Pager.dbSize, or
38620 **   * The PGHDR_DONT_WRITE flag is set on the page.
38621 **
38622 ** If writing out a page causes the database file to grow, Pager.dbFileSize
38623 ** is updated accordingly. If page 1 is written out, then the value cached
38624 ** in Pager.dbFileVers[] is updated to match the new value stored in
38625 ** the database file.
38626 **
38627 ** If everything is successful, SQLITE_OK is returned. If an IO error 
38628 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
38629 ** be obtained, SQLITE_BUSY is returned.
38630 */
38631 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
38632   int rc = SQLITE_OK;                  /* Return code */
38633
38634   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
38635   assert( !pagerUseWal(pPager) );
38636   assert( pPager->eState==PAGER_WRITER_DBMOD );
38637   assert( pPager->eLock==EXCLUSIVE_LOCK );
38638
38639   /* If the file is a temp-file has not yet been opened, open it now. It
38640   ** is not possible for rc to be other than SQLITE_OK if this branch
38641   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
38642   */
38643   if( !isOpen(pPager->fd) ){
38644     assert( pPager->tempFile && rc==SQLITE_OK );
38645     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
38646   }
38647
38648   /* Before the first write, give the VFS a hint of what the final
38649   ** file size will be.
38650   */
38651   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
38652   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
38653     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
38654     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
38655     pPager->dbHintSize = pPager->dbSize;
38656   }
38657
38658   while( rc==SQLITE_OK && pList ){
38659     Pgno pgno = pList->pgno;
38660
38661     /* If there are dirty pages in the page cache with page numbers greater
38662     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
38663     ** make the file smaller (presumably by auto-vacuum code). Do not write
38664     ** any such pages to the file.
38665     **
38666     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
38667     ** set (set by sqlite3PagerDontWrite()).
38668     */
38669     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
38670       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
38671       char *pData;                                   /* Data to write */    
38672
38673       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
38674
38675       /* Encode the database */
38676       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
38677
38678       /* Write out the page data. */
38679       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
38680
38681       /* If page 1 was just written, update Pager.dbFileVers to match
38682       ** the value now stored in the database file. If writing this 
38683       ** page caused the database file to grow, update dbFileSize. 
38684       */
38685       if( pgno==1 ){
38686         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
38687       }
38688       if( pgno>pPager->dbFileSize ){
38689         pPager->dbFileSize = pgno;
38690       }
38691
38692       /* Update any backup objects copying the contents of this pager. */
38693       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
38694
38695       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
38696                    PAGERID(pPager), pgno, pager_pagehash(pList)));
38697       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
38698       PAGER_INCR(sqlite3_pager_writedb_count);
38699       PAGER_INCR(pPager->nWrite);
38700     }else{
38701       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
38702     }
38703     pager_set_pagehash(pList);
38704     pList = pList->pDirty;
38705   }
38706
38707   return rc;
38708 }
38709
38710 /*
38711 ** Ensure that the sub-journal file is open. If it is already open, this 
38712 ** function is a no-op.
38713 **
38714 ** SQLITE_OK is returned if everything goes according to plan. An 
38715 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
38716 ** fails.
38717 */
38718 static int openSubJournal(Pager *pPager){
38719   int rc = SQLITE_OK;
38720   if( !isOpen(pPager->sjfd) ){
38721     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
38722       sqlite3MemJournalOpen(pPager->sjfd);
38723     }else{
38724       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
38725     }
38726   }
38727   return rc;
38728 }
38729
38730 /*
38731 ** Append a record of the current state of page pPg to the sub-journal. 
38732 ** It is the callers responsibility to use subjRequiresPage() to check 
38733 ** that it is really required before calling this function.
38734 **
38735 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
38736 ** for all open savepoints before returning.
38737 **
38738 ** This function returns SQLITE_OK if everything is successful, an IO
38739 ** error code if the attempt to write to the sub-journal fails, or 
38740 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
38741 ** bitvec.
38742 */
38743 static int subjournalPage(PgHdr *pPg){
38744   int rc = SQLITE_OK;
38745   Pager *pPager = pPg->pPager;
38746   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
38747
38748     /* Open the sub-journal, if it has not already been opened */
38749     assert( pPager->useJournal );
38750     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
38751     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
38752     assert( pagerUseWal(pPager) 
38753          || pageInJournal(pPg) 
38754          || pPg->pgno>pPager->dbOrigSize 
38755     );
38756     rc = openSubJournal(pPager);
38757
38758     /* If the sub-journal was opened successfully (or was already open),
38759     ** write the journal record into the file.  */
38760     if( rc==SQLITE_OK ){
38761       void *pData = pPg->pData;
38762       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
38763       char *pData2;
38764   
38765       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
38766       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
38767       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
38768       if( rc==SQLITE_OK ){
38769         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
38770       }
38771     }
38772   }
38773   if( rc==SQLITE_OK ){
38774     pPager->nSubRec++;
38775     assert( pPager->nSavepoint>0 );
38776     rc = addToSavepointBitvecs(pPager, pPg->pgno);
38777   }
38778   return rc;
38779 }
38780
38781 /*
38782 ** This function is called by the pcache layer when it has reached some
38783 ** soft memory limit. The first argument is a pointer to a Pager object
38784 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
38785 ** database). The second argument is a reference to a page that is 
38786 ** currently dirty but has no outstanding references. The page
38787 ** is always associated with the Pager object passed as the first 
38788 ** argument.
38789 **
38790 ** The job of this function is to make pPg clean by writing its contents
38791 ** out to the database file, if possible. This may involve syncing the
38792 ** journal file. 
38793 **
38794 ** If successful, sqlite3PcacheMakeClean() is called on the page and
38795 ** SQLITE_OK returned. If an IO error occurs while trying to make the
38796 ** page clean, the IO error code is returned. If the page cannot be
38797 ** made clean for some other reason, but no error occurs, then SQLITE_OK
38798 ** is returned by sqlite3PcacheMakeClean() is not called.
38799 */
38800 static int pagerStress(void *p, PgHdr *pPg){
38801   Pager *pPager = (Pager *)p;
38802   int rc = SQLITE_OK;
38803
38804   assert( pPg->pPager==pPager );
38805   assert( pPg->flags&PGHDR_DIRTY );
38806
38807   /* The doNotSyncSpill flag is set during times when doing a sync of
38808   ** journal (and adding a new header) is not allowed.  This occurs
38809   ** during calls to sqlite3PagerWrite() while trying to journal multiple
38810   ** pages belonging to the same sector.
38811   **
38812   ** The doNotSpill flag inhibits all cache spilling regardless of whether
38813   ** or not a sync is required.  This is set during a rollback.
38814   **
38815   ** Spilling is also prohibited when in an error state since that could
38816   ** lead to database corruption.   In the current implementaton it 
38817   ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
38818   ** while in the error state, hence it is impossible for this routine to
38819   ** be called in the error state.  Nevertheless, we include a NEVER()
38820   ** test for the error state as a safeguard against future changes.
38821   */
38822   if( NEVER(pPager->errCode) ) return SQLITE_OK;
38823   if( pPager->doNotSpill ) return SQLITE_OK;
38824   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
38825     return SQLITE_OK;
38826   }
38827
38828   pPg->pDirty = 0;
38829   if( pagerUseWal(pPager) ){
38830     /* Write a single frame for this page to the log. */
38831     if( subjRequiresPage(pPg) ){ 
38832       rc = subjournalPage(pPg); 
38833     }
38834     if( rc==SQLITE_OK ){
38835       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
38836     }
38837   }else{
38838   
38839     /* Sync the journal file if required. */
38840     if( pPg->flags&PGHDR_NEED_SYNC 
38841      || pPager->eState==PAGER_WRITER_CACHEMOD
38842     ){
38843       rc = syncJournal(pPager, 1);
38844     }
38845   
38846     /* If the page number of this page is larger than the current size of
38847     ** the database image, it may need to be written to the sub-journal.
38848     ** This is because the call to pager_write_pagelist() below will not
38849     ** actually write data to the file in this case.
38850     **
38851     ** Consider the following sequence of events:
38852     **
38853     **   BEGIN;
38854     **     <journal page X>
38855     **     <modify page X>
38856     **     SAVEPOINT sp;
38857     **       <shrink database file to Y pages>
38858     **       pagerStress(page X)
38859     **     ROLLBACK TO sp;
38860     **
38861     ** If (X>Y), then when pagerStress is called page X will not be written
38862     ** out to the database file, but will be dropped from the cache. Then,
38863     ** following the "ROLLBACK TO sp" statement, reading page X will read
38864     ** data from the database file. This will be the copy of page X as it
38865     ** was when the transaction started, not as it was when "SAVEPOINT sp"
38866     ** was executed.
38867     **
38868     ** The solution is to write the current data for page X into the 
38869     ** sub-journal file now (if it is not already there), so that it will
38870     ** be restored to its current value when the "ROLLBACK TO sp" is 
38871     ** executed.
38872     */
38873     if( NEVER(
38874         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
38875     ) ){
38876       rc = subjournalPage(pPg);
38877     }
38878   
38879     /* Write the contents of the page out to the database file. */
38880     if( rc==SQLITE_OK ){
38881       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
38882       rc = pager_write_pagelist(pPager, pPg);
38883     }
38884   }
38885
38886   /* Mark the page as clean. */
38887   if( rc==SQLITE_OK ){
38888     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
38889     sqlite3PcacheMakeClean(pPg);
38890   }
38891
38892   return pager_error(pPager, rc); 
38893 }
38894
38895
38896 /*
38897 ** Allocate and initialize a new Pager object and put a pointer to it
38898 ** in *ppPager. The pager should eventually be freed by passing it
38899 ** to sqlite3PagerClose().
38900 **
38901 ** The zFilename argument is the path to the database file to open.
38902 ** If zFilename is NULL then a randomly-named temporary file is created
38903 ** and used as the file to be cached. Temporary files are be deleted
38904 ** automatically when they are closed. If zFilename is ":memory:" then 
38905 ** all information is held in cache. It is never written to disk. 
38906 ** This can be used to implement an in-memory database.
38907 **
38908 ** The nExtra parameter specifies the number of bytes of space allocated
38909 ** along with each page reference. This space is available to the user
38910 ** via the sqlite3PagerGetExtra() API.
38911 **
38912 ** The flags argument is used to specify properties that affect the
38913 ** operation of the pager. It should be passed some bitwise combination
38914 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
38915 **
38916 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
38917 ** of the xOpen() method of the supplied VFS when opening files. 
38918 **
38919 ** If the pager object is allocated and the specified file opened 
38920 ** successfully, SQLITE_OK is returned and *ppPager set to point to
38921 ** the new pager object. If an error occurs, *ppPager is set to NULL
38922 ** and error code returned. This function may return SQLITE_NOMEM
38923 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
38924 ** various SQLITE_IO_XXX errors.
38925 */
38926 SQLITE_PRIVATE int sqlite3PagerOpen(
38927   sqlite3_vfs *pVfs,       /* The virtual file system to use */
38928   Pager **ppPager,         /* OUT: Return the Pager structure here */
38929   const char *zFilename,   /* Name of the database file to open */
38930   int nExtra,              /* Extra bytes append to each in-memory page */
38931   int flags,               /* flags controlling this file */
38932   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
38933   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
38934 ){
38935   u8 *pPtr;
38936   Pager *pPager = 0;       /* Pager object to allocate and return */
38937   int rc = SQLITE_OK;      /* Return code */
38938   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
38939   int memDb = 0;           /* True if this is an in-memory file */
38940   int readOnly = 0;        /* True if this is a read-only file */
38941   int journalFileSize;     /* Bytes to allocate for each journal fd */
38942   char *zPathname = 0;     /* Full path to database file */
38943   int nPathname = 0;       /* Number of bytes in zPathname */
38944   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
38945   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
38946   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
38947   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
38948
38949   /* Figure out how much space is required for each journal file-handle
38950   ** (there are two of them, the main journal and the sub-journal). This
38951   ** is the maximum space required for an in-memory journal file handle 
38952   ** and a regular journal file-handle. Note that a "regular journal-handle"
38953   ** may be a wrapper capable of caching the first portion of the journal
38954   ** file in memory to implement the atomic-write optimization (see 
38955   ** source file journal.c).
38956   */
38957   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
38958     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
38959   }else{
38960     journalFileSize = ROUND8(sqlite3MemJournalSize());
38961   }
38962
38963   /* Set the output variable to NULL in case an error occurs. */
38964   *ppPager = 0;
38965
38966 #ifndef SQLITE_OMIT_MEMORYDB
38967   if( flags & PAGER_MEMORY ){
38968     memDb = 1;
38969     zFilename = 0;
38970   }
38971 #endif
38972
38973   /* Compute and store the full pathname in an allocated buffer pointed
38974   ** to by zPathname, length nPathname. Or, if this is a temporary file,
38975   ** leave both nPathname and zPathname set to 0.
38976   */
38977   if( zFilename && zFilename[0] ){
38978     nPathname = pVfs->mxPathname+1;
38979     zPathname = sqlite3Malloc(nPathname*2);
38980     if( zPathname==0 ){
38981       return SQLITE_NOMEM;
38982     }
38983     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
38984     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
38985     nPathname = sqlite3Strlen30(zPathname);
38986     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
38987       /* This branch is taken when the journal path required by
38988       ** the database being opened will be more than pVfs->mxPathname
38989       ** bytes in length. This means the database cannot be opened,
38990       ** as it will not be possible to open the journal file or even
38991       ** check for a hot-journal before reading.
38992       */
38993       rc = SQLITE_CANTOPEN_BKPT;
38994     }
38995     if( rc!=SQLITE_OK ){
38996       sqlite3_free(zPathname);
38997       return rc;
38998     }
38999   }
39000
39001   /* Allocate memory for the Pager structure, PCache object, the
39002   ** three file descriptors, the database file name and the journal 
39003   ** file name. The layout in memory is as follows:
39004   **
39005   **     Pager object                    (sizeof(Pager) bytes)
39006   **     PCache object                   (sqlite3PcacheSize() bytes)
39007   **     Database file handle            (pVfs->szOsFile bytes)
39008   **     Sub-journal file handle         (journalFileSize bytes)
39009   **     Main journal file handle        (journalFileSize bytes)
39010   **     Database file name              (nPathname+1 bytes)
39011   **     Journal file name               (nPathname+8+1 bytes)
39012   */
39013   pPtr = (u8 *)sqlite3MallocZero(
39014     ROUND8(sizeof(*pPager)) +      /* Pager structure */
39015     ROUND8(pcacheSize) +           /* PCache object */
39016     ROUND8(pVfs->szOsFile) +       /* The main db file */
39017     journalFileSize * 2 +          /* The two journal files */ 
39018     nPathname + 1 +                /* zFilename */
39019     nPathname + 8 + 1              /* zJournal */
39020 #ifndef SQLITE_OMIT_WAL
39021     + nPathname + 4 + 1              /* zWal */
39022 #endif
39023   );
39024   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
39025   if( !pPtr ){
39026     sqlite3_free(zPathname);
39027     return SQLITE_NOMEM;
39028   }
39029   pPager =              (Pager*)(pPtr);
39030   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
39031   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
39032   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
39033   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
39034   pPager->zFilename =    (char*)(pPtr += journalFileSize);
39035   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
39036
39037   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
39038   if( zPathname ){
39039     assert( nPathname>0 );
39040     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
39041     memcpy(pPager->zFilename, zPathname, nPathname);
39042     memcpy(pPager->zJournal, zPathname, nPathname);
39043     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
39044 #ifndef SQLITE_OMIT_WAL
39045     pPager->zWal = &pPager->zJournal[nPathname+8+1];
39046     memcpy(pPager->zWal, zPathname, nPathname);
39047     memcpy(&pPager->zWal[nPathname], "-wal", 4);
39048 #endif
39049     sqlite3_free(zPathname);
39050   }
39051   pPager->pVfs = pVfs;
39052   pPager->vfsFlags = vfsFlags;
39053
39054   /* Open the pager file.
39055   */
39056   if( zFilename && zFilename[0] ){
39057     int fout = 0;                    /* VFS flags returned by xOpen() */
39058     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
39059     assert( !memDb );
39060     readOnly = (fout&SQLITE_OPEN_READONLY);
39061
39062     /* If the file was successfully opened for read/write access,
39063     ** choose a default page size in case we have to create the
39064     ** database file. The default page size is the maximum of:
39065     **
39066     **    + SQLITE_DEFAULT_PAGE_SIZE,
39067     **    + The value returned by sqlite3OsSectorSize()
39068     **    + The largest page size that can be written atomically.
39069     */
39070     if( rc==SQLITE_OK && !readOnly ){
39071       setSectorSize(pPager);
39072       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
39073       if( szPageDflt<pPager->sectorSize ){
39074         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
39075           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
39076         }else{
39077           szPageDflt = (u32)pPager->sectorSize;
39078         }
39079       }
39080 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
39081       {
39082         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
39083         int ii;
39084         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
39085         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
39086         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
39087         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
39088           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
39089             szPageDflt = ii;
39090           }
39091         }
39092       }
39093 #endif
39094     }
39095   }else{
39096     /* If a temporary file is requested, it is not opened immediately.
39097     ** In this case we accept the default page size and delay actually
39098     ** opening the file until the first call to OsWrite().
39099     **
39100     ** This branch is also run for an in-memory database. An in-memory
39101     ** database is the same as a temp-file that is never written out to
39102     ** disk and uses an in-memory rollback journal.
39103     */ 
39104     tempFile = 1;
39105     pPager->eState = PAGER_READER;
39106     pPager->eLock = EXCLUSIVE_LOCK;
39107     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
39108   }
39109
39110   /* The following call to PagerSetPagesize() serves to set the value of 
39111   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
39112   */
39113   if( rc==SQLITE_OK ){
39114     assert( pPager->memDb==0 );
39115     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
39116     testcase( rc!=SQLITE_OK );
39117   }
39118
39119   /* If an error occurred in either of the blocks above, free the 
39120   ** Pager structure and close the file.
39121   */
39122   if( rc!=SQLITE_OK ){
39123     assert( !pPager->pTmpSpace );
39124     sqlite3OsClose(pPager->fd);
39125     sqlite3_free(pPager);
39126     return rc;
39127   }
39128
39129   /* Initialize the PCache object. */
39130   assert( nExtra<1000 );
39131   nExtra = ROUND8(nExtra);
39132   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
39133                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
39134
39135   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
39136   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
39137
39138   pPager->useJournal = (u8)useJournal;
39139   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
39140   /* pPager->stmtOpen = 0; */
39141   /* pPager->stmtInUse = 0; */
39142   /* pPager->nRef = 0; */
39143   /* pPager->stmtSize = 0; */
39144   /* pPager->stmtJSize = 0; */
39145   /* pPager->nPage = 0; */
39146   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
39147   /* pPager->state = PAGER_UNLOCK; */
39148 #if 0
39149   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
39150 #endif
39151   /* pPager->errMask = 0; */
39152   pPager->tempFile = (u8)tempFile;
39153   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
39154           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
39155   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
39156   pPager->exclusiveMode = (u8)tempFile; 
39157   pPager->changeCountDone = pPager->tempFile;
39158   pPager->memDb = (u8)memDb;
39159   pPager->readOnly = (u8)readOnly;
39160   assert( useJournal || pPager->tempFile );
39161   pPager->noSync = pPager->tempFile;
39162   pPager->fullSync = pPager->noSync ?0:1;
39163   pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
39164   pPager->ckptSyncFlags = pPager->syncFlags;
39165   /* pPager->pFirst = 0; */
39166   /* pPager->pFirstSynced = 0; */
39167   /* pPager->pLast = 0; */
39168   pPager->nExtra = (u16)nExtra;
39169   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
39170   assert( isOpen(pPager->fd) || tempFile );
39171   setSectorSize(pPager);
39172   if( !useJournal ){
39173     pPager->journalMode = PAGER_JOURNALMODE_OFF;
39174   }else if( memDb ){
39175     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
39176   }
39177   /* pPager->xBusyHandler = 0; */
39178   /* pPager->pBusyHandlerArg = 0; */
39179   pPager->xReiniter = xReinit;
39180   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
39181
39182   *ppPager = pPager;
39183   return SQLITE_OK;
39184 }
39185
39186
39187
39188 /*
39189 ** This function is called after transitioning from PAGER_UNLOCK to
39190 ** PAGER_SHARED state. It tests if there is a hot journal present in
39191 ** the file-system for the given pager. A hot journal is one that 
39192 ** needs to be played back. According to this function, a hot-journal
39193 ** file exists if the following criteria are met:
39194 **
39195 **   * The journal file exists in the file system, and
39196 **   * No process holds a RESERVED or greater lock on the database file, and
39197 **   * The database file itself is greater than 0 bytes in size, and
39198 **   * The first byte of the journal file exists and is not 0x00.
39199 **
39200 ** If the current size of the database file is 0 but a journal file
39201 ** exists, that is probably an old journal left over from a prior
39202 ** database with the same name. In this case the journal file is
39203 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
39204 ** is returned.
39205 **
39206 ** This routine does not check if there is a master journal filename
39207 ** at the end of the file. If there is, and that master journal file
39208 ** does not exist, then the journal file is not really hot. In this
39209 ** case this routine will return a false-positive. The pager_playback()
39210 ** routine will discover that the journal file is not really hot and 
39211 ** will not roll it back. 
39212 **
39213 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
39214 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
39215 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
39216 ** to determine whether or not a hot-journal file exists, the IO error
39217 ** code is returned and the value of *pExists is undefined.
39218 */
39219 static int hasHotJournal(Pager *pPager, int *pExists){
39220   sqlite3_vfs * const pVfs = pPager->pVfs;
39221   int rc = SQLITE_OK;           /* Return code */
39222   int exists = 1;               /* True if a journal file is present */
39223   int jrnlOpen = !!isOpen(pPager->jfd);
39224
39225   assert( pPager->useJournal );
39226   assert( isOpen(pPager->fd) );
39227   assert( pPager->eState==PAGER_OPEN );
39228
39229   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
39230     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
39231   ));
39232
39233   *pExists = 0;
39234   if( !jrnlOpen ){
39235     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
39236   }
39237   if( rc==SQLITE_OK && exists ){
39238     int locked = 0;             /* True if some process holds a RESERVED lock */
39239
39240     /* Race condition here:  Another process might have been holding the
39241     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
39242     ** call above, but then delete the journal and drop the lock before
39243     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
39244     ** is the case, this routine might think there is a hot journal when
39245     ** in fact there is none.  This results in a false-positive which will
39246     ** be dealt with by the playback routine.  Ticket #3883.
39247     */
39248     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
39249     if( rc==SQLITE_OK && !locked ){
39250       Pgno nPage;                 /* Number of pages in database file */
39251
39252       /* Check the size of the database file. If it consists of 0 pages,
39253       ** then delete the journal file. See the header comment above for 
39254       ** the reasoning here.  Delete the obsolete journal file under
39255       ** a RESERVED lock to avoid race conditions and to avoid violating
39256       ** [H33020].
39257       */
39258       rc = pagerPagecount(pPager, &nPage);
39259       if( rc==SQLITE_OK ){
39260         if( nPage==0 ){
39261           sqlite3BeginBenignMalloc();
39262           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
39263             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
39264             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
39265           }
39266           sqlite3EndBenignMalloc();
39267         }else{
39268           /* The journal file exists and no other connection has a reserved
39269           ** or greater lock on the database file. Now check that there is
39270           ** at least one non-zero bytes at the start of the journal file.
39271           ** If there is, then we consider this journal to be hot. If not, 
39272           ** it can be ignored.
39273           */
39274           if( !jrnlOpen ){
39275             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
39276             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
39277           }
39278           if( rc==SQLITE_OK ){
39279             u8 first = 0;
39280             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
39281             if( rc==SQLITE_IOERR_SHORT_READ ){
39282               rc = SQLITE_OK;
39283             }
39284             if( !jrnlOpen ){
39285               sqlite3OsClose(pPager->jfd);
39286             }
39287             *pExists = (first!=0);
39288           }else if( rc==SQLITE_CANTOPEN ){
39289             /* If we cannot open the rollback journal file in order to see if
39290             ** its has a zero header, that might be due to an I/O error, or
39291             ** it might be due to the race condition described above and in
39292             ** ticket #3883.  Either way, assume that the journal is hot.
39293             ** This might be a false positive.  But if it is, then the
39294             ** automatic journal playback and recovery mechanism will deal
39295             ** with it under an EXCLUSIVE lock where we do not need to
39296             ** worry so much with race conditions.
39297             */
39298             *pExists = 1;
39299             rc = SQLITE_OK;
39300           }
39301         }
39302       }
39303     }
39304   }
39305
39306   return rc;
39307 }
39308
39309 /*
39310 ** This function is called to obtain a shared lock on the database file.
39311 ** It is illegal to call sqlite3PagerAcquire() until after this function
39312 ** has been successfully called. If a shared-lock is already held when
39313 ** this function is called, it is a no-op.
39314 **
39315 ** The following operations are also performed by this function.
39316 **
39317 **   1) If the pager is currently in PAGER_OPEN state (no lock held
39318 **      on the database file), then an attempt is made to obtain a
39319 **      SHARED lock on the database file. Immediately after obtaining
39320 **      the SHARED lock, the file-system is checked for a hot-journal,
39321 **      which is played back if present. Following any hot-journal 
39322 **      rollback, the contents of the cache are validated by checking
39323 **      the 'change-counter' field of the database file header and
39324 **      discarded if they are found to be invalid.
39325 **
39326 **   2) If the pager is running in exclusive-mode, and there are currently
39327 **      no outstanding references to any pages, and is in the error state,
39328 **      then an attempt is made to clear the error state by discarding
39329 **      the contents of the page cache and rolling back any open journal
39330 **      file.
39331 **
39332 ** If everything is successful, SQLITE_OK is returned. If an IO error 
39333 ** occurs while locking the database, checking for a hot-journal file or 
39334 ** rolling back a journal file, the IO error code is returned.
39335 */
39336 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
39337   int rc = SQLITE_OK;                /* Return code */
39338
39339   /* This routine is only called from b-tree and only when there are no
39340   ** outstanding pages. This implies that the pager state should either
39341   ** be OPEN or READER. READER is only possible if the pager is or was in 
39342   ** exclusive access mode.
39343   */
39344   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
39345   assert( assert_pager_state(pPager) );
39346   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
39347   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
39348
39349   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
39350     int bHotJournal = 1;          /* True if there exists a hot journal-file */
39351
39352     assert( !MEMDB );
39353     assert( pPager->noReadlock==0 || pPager->readOnly );
39354
39355     if( pPager->noReadlock==0 ){
39356       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
39357       if( rc!=SQLITE_OK ){
39358         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
39359         goto failed;
39360       }
39361     }
39362
39363     /* If a journal file exists, and there is no RESERVED lock on the
39364     ** database file, then it either needs to be played back or deleted.
39365     */
39366     if( pPager->eLock<=SHARED_LOCK ){
39367       rc = hasHotJournal(pPager, &bHotJournal);
39368     }
39369     if( rc!=SQLITE_OK ){
39370       goto failed;
39371     }
39372     if( bHotJournal ){
39373       /* Get an EXCLUSIVE lock on the database file. At this point it is
39374       ** important that a RESERVED lock is not obtained on the way to the
39375       ** EXCLUSIVE lock. If it were, another process might open the
39376       ** database file, detect the RESERVED lock, and conclude that the
39377       ** database is safe to read while this process is still rolling the 
39378       ** hot-journal back.
39379       ** 
39380       ** Because the intermediate RESERVED lock is not requested, any
39381       ** other process attempting to access the database file will get to 
39382       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
39383       ** on the database file.
39384       **
39385       ** Unless the pager is in locking_mode=exclusive mode, the lock is
39386       ** downgraded to SHARED_LOCK before this function returns.
39387       */
39388       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
39389       if( rc!=SQLITE_OK ){
39390         goto failed;
39391       }
39392  
39393       /* If it is not already open and the file exists on disk, open the 
39394       ** journal for read/write access. Write access is required because 
39395       ** in exclusive-access mode the file descriptor will be kept open 
39396       ** and possibly used for a transaction later on. Also, write-access 
39397       ** is usually required to finalize the journal in journal_mode=persist 
39398       ** mode (and also for journal_mode=truncate on some systems).
39399       **
39400       ** If the journal does not exist, it usually means that some 
39401       ** other connection managed to get in and roll it back before 
39402       ** this connection obtained the exclusive lock above. Or, it 
39403       ** may mean that the pager was in the error-state when this
39404       ** function was called and the journal file does not exist.
39405       */
39406       if( !isOpen(pPager->jfd) ){
39407         sqlite3_vfs * const pVfs = pPager->pVfs;
39408         int bExists;              /* True if journal file exists */
39409         rc = sqlite3OsAccess(
39410             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
39411         if( rc==SQLITE_OK && bExists ){
39412           int fout = 0;
39413           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
39414           assert( !pPager->tempFile );
39415           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
39416           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
39417           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
39418             rc = SQLITE_CANTOPEN_BKPT;
39419             sqlite3OsClose(pPager->jfd);
39420           }
39421         }
39422       }
39423  
39424       /* Playback and delete the journal.  Drop the database write
39425       ** lock and reacquire the read lock. Purge the cache before
39426       ** playing back the hot-journal so that we don't end up with
39427       ** an inconsistent cache.  Sync the hot journal before playing
39428       ** it back since the process that crashed and left the hot journal
39429       ** probably did not sync it and we are required to always sync
39430       ** the journal before playing it back.
39431       */
39432       if( isOpen(pPager->jfd) ){
39433         assert( rc==SQLITE_OK );
39434         rc = pagerSyncHotJournal(pPager);
39435         if( rc==SQLITE_OK ){
39436           rc = pager_playback(pPager, 1);
39437           pPager->eState = PAGER_OPEN;
39438         }
39439       }else if( !pPager->exclusiveMode ){
39440         pagerUnlockDb(pPager, SHARED_LOCK);
39441       }
39442
39443       if( rc!=SQLITE_OK ){
39444         /* This branch is taken if an error occurs while trying to open
39445         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
39446         ** pager_unlock() routine will be called before returning to unlock
39447         ** the file. If the unlock attempt fails, then Pager.eLock must be
39448         ** set to UNKNOWN_LOCK (see the comment above the #define for 
39449         ** UNKNOWN_LOCK above for an explanation). 
39450         **
39451         ** In order to get pager_unlock() to do this, set Pager.eState to
39452         ** PAGER_ERROR now. This is not actually counted as a transition
39453         ** to ERROR state in the state diagram at the top of this file,
39454         ** since we know that the same call to pager_unlock() will very
39455         ** shortly transition the pager object to the OPEN state. Calling
39456         ** assert_pager_state() would fail now, as it should not be possible
39457         ** to be in ERROR state when there are zero outstanding page 
39458         ** references.
39459         */
39460         pager_error(pPager, rc);
39461         goto failed;
39462       }
39463
39464       assert( pPager->eState==PAGER_OPEN );
39465       assert( (pPager->eLock==SHARED_LOCK)
39466            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
39467       );
39468     }
39469
39470     if( !pPager->tempFile 
39471      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) 
39472     ){
39473       /* The shared-lock has just been acquired on the database file
39474       ** and there are already pages in the cache (from a previous
39475       ** read or write transaction).  Check to see if the database
39476       ** has been modified.  If the database has changed, flush the
39477       ** cache.
39478       **
39479       ** Database changes is detected by looking at 15 bytes beginning
39480       ** at offset 24 into the file.  The first 4 of these 16 bytes are
39481       ** a 32-bit counter that is incremented with each change.  The
39482       ** other bytes change randomly with each file change when
39483       ** a codec is in use.
39484       ** 
39485       ** There is a vanishingly small chance that a change will not be 
39486       ** detected.  The chance of an undetected change is so small that
39487       ** it can be neglected.
39488       */
39489       Pgno nPage = 0;
39490       char dbFileVers[sizeof(pPager->dbFileVers)];
39491
39492       rc = pagerPagecount(pPager, &nPage);
39493       if( rc ) goto failed;
39494
39495       if( nPage>0 ){
39496         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
39497         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
39498         if( rc!=SQLITE_OK ){
39499           goto failed;
39500         }
39501       }else{
39502         memset(dbFileVers, 0, sizeof(dbFileVers));
39503       }
39504
39505       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
39506         pager_reset(pPager);
39507       }
39508     }
39509
39510     /* If there is a WAL file in the file-system, open this database in WAL
39511     ** mode. Otherwise, the following function call is a no-op.
39512     */
39513     rc = pagerOpenWalIfPresent(pPager);
39514 #ifndef SQLITE_OMIT_WAL
39515     assert( pPager->pWal==0 || rc==SQLITE_OK );
39516 #endif
39517   }
39518
39519   if( pagerUseWal(pPager) ){
39520     assert( rc==SQLITE_OK );
39521     rc = pagerBeginReadTransaction(pPager);
39522   }
39523
39524   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
39525     rc = pagerPagecount(pPager, &pPager->dbSize);
39526   }
39527
39528  failed:
39529   if( rc!=SQLITE_OK ){
39530     assert( !MEMDB );
39531     pager_unlock(pPager);
39532     assert( pPager->eState==PAGER_OPEN );
39533   }else{
39534     pPager->eState = PAGER_READER;
39535   }
39536   return rc;
39537 }
39538
39539 /*
39540 ** If the reference count has reached zero, rollback any active
39541 ** transaction and unlock the pager.
39542 **
39543 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
39544 ** the rollback journal, the unlock is not performed and there is
39545 ** nothing to rollback, so this routine is a no-op.
39546 */ 
39547 static void pagerUnlockIfUnused(Pager *pPager){
39548   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
39549     pagerUnlockAndRollback(pPager);
39550   }
39551 }
39552
39553 /*
39554 ** Acquire a reference to page number pgno in pager pPager (a page
39555 ** reference has type DbPage*). If the requested reference is 
39556 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
39557 **
39558 ** If the requested page is already in the cache, it is returned. 
39559 ** Otherwise, a new page object is allocated and populated with data
39560 ** read from the database file. In some cases, the pcache module may
39561 ** choose not to allocate a new page object and may reuse an existing
39562 ** object with no outstanding references.
39563 **
39564 ** The extra data appended to a page is always initialized to zeros the 
39565 ** first time a page is loaded into memory. If the page requested is 
39566 ** already in the cache when this function is called, then the extra
39567 ** data is left as it was when the page object was last used.
39568 **
39569 ** If the database image is smaller than the requested page or if a 
39570 ** non-zero value is passed as the noContent parameter and the 
39571 ** requested page is not already stored in the cache, then no 
39572 ** actual disk read occurs. In this case the memory image of the 
39573 ** page is initialized to all zeros. 
39574 **
39575 ** If noContent is true, it means that we do not care about the contents
39576 ** of the page. This occurs in two seperate scenarios:
39577 **
39578 **   a) When reading a free-list leaf page from the database, and
39579 **
39580 **   b) When a savepoint is being rolled back and we need to load
39581 **      a new page into the cache to be filled with the data read
39582 **      from the savepoint journal.
39583 **
39584 ** If noContent is true, then the data returned is zeroed instead of
39585 ** being read from the database. Additionally, the bits corresponding
39586 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
39587 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
39588 ** savepoints are set. This means if the page is made writable at any
39589 ** point in the future, using a call to sqlite3PagerWrite(), its contents
39590 ** will not be journaled. This saves IO.
39591 **
39592 ** The acquisition might fail for several reasons.  In all cases,
39593 ** an appropriate error code is returned and *ppPage is set to NULL.
39594 **
39595 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
39596 ** to find a page in the in-memory cache first.  If the page is not already
39597 ** in memory, this routine goes to disk to read it in whereas Lookup()
39598 ** just returns 0.  This routine acquires a read-lock the first time it
39599 ** has to go to disk, and could also playback an old journal if necessary.
39600 ** Since Lookup() never goes to disk, it never has to deal with locks
39601 ** or journal files.
39602 */
39603 SQLITE_PRIVATE int sqlite3PagerAcquire(
39604   Pager *pPager,      /* The pager open on the database file */
39605   Pgno pgno,          /* Page number to fetch */
39606   DbPage **ppPage,    /* Write a pointer to the page here */
39607   int noContent       /* Do not bother reading content from disk if true */
39608 ){
39609   int rc;
39610   PgHdr *pPg;
39611
39612   assert( pPager->eState>=PAGER_READER );
39613   assert( assert_pager_state(pPager) );
39614
39615   if( pgno==0 ){
39616     return SQLITE_CORRUPT_BKPT;
39617   }
39618
39619   /* If the pager is in the error state, return an error immediately. 
39620   ** Otherwise, request the page from the PCache layer. */
39621   if( pPager->errCode!=SQLITE_OK ){
39622     rc = pPager->errCode;
39623   }else{
39624     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
39625   }
39626
39627   if( rc!=SQLITE_OK ){
39628     /* Either the call to sqlite3PcacheFetch() returned an error or the
39629     ** pager was already in the error-state when this function was called.
39630     ** Set pPg to 0 and jump to the exception handler.  */
39631     pPg = 0;
39632     goto pager_acquire_err;
39633   }
39634   assert( (*ppPage)->pgno==pgno );
39635   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
39636
39637   if( (*ppPage)->pPager && !noContent ){
39638     /* In this case the pcache already contains an initialized copy of
39639     ** the page. Return without further ado.  */
39640     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
39641     PAGER_INCR(pPager->nHit);
39642     return SQLITE_OK;
39643
39644   }else{
39645     /* The pager cache has created a new page. Its content needs to 
39646     ** be initialized.  */
39647
39648     PAGER_INCR(pPager->nMiss);
39649     pPg = *ppPage;
39650     pPg->pPager = pPager;
39651
39652     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
39653     ** number greater than this, or the unused locking-page, is requested. */
39654     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
39655       rc = SQLITE_CORRUPT_BKPT;
39656       goto pager_acquire_err;
39657     }
39658
39659     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
39660       if( pgno>pPager->mxPgno ){
39661         rc = SQLITE_FULL;
39662         goto pager_acquire_err;
39663       }
39664       if( noContent ){
39665         /* Failure to set the bits in the InJournal bit-vectors is benign.
39666         ** It merely means that we might do some extra work to journal a 
39667         ** page that does not need to be journaled.  Nevertheless, be sure 
39668         ** to test the case where a malloc error occurs while trying to set 
39669         ** a bit in a bit vector.
39670         */
39671         sqlite3BeginBenignMalloc();
39672         if( pgno<=pPager->dbOrigSize ){
39673           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
39674           testcase( rc==SQLITE_NOMEM );
39675         }
39676         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
39677         testcase( rc==SQLITE_NOMEM );
39678         sqlite3EndBenignMalloc();
39679       }
39680       memset(pPg->pData, 0, pPager->pageSize);
39681       IOTRACE(("ZERO %p %d\n", pPager, pgno));
39682     }else{
39683       assert( pPg->pPager==pPager );
39684       rc = readDbPage(pPg);
39685       if( rc!=SQLITE_OK ){
39686         goto pager_acquire_err;
39687       }
39688     }
39689     pager_set_pagehash(pPg);
39690   }
39691
39692   return SQLITE_OK;
39693
39694 pager_acquire_err:
39695   assert( rc!=SQLITE_OK );
39696   if( pPg ){
39697     sqlite3PcacheDrop(pPg);
39698   }
39699   pagerUnlockIfUnused(pPager);
39700
39701   *ppPage = 0;
39702   return rc;
39703 }
39704
39705 /*
39706 ** Acquire a page if it is already in the in-memory cache.  Do
39707 ** not read the page from disk.  Return a pointer to the page,
39708 ** or 0 if the page is not in cache. 
39709 **
39710 ** See also sqlite3PagerGet().  The difference between this routine
39711 ** and sqlite3PagerGet() is that _get() will go to the disk and read
39712 ** in the page if the page is not already in cache.  This routine
39713 ** returns NULL if the page is not in cache or if a disk I/O error 
39714 ** has ever happened.
39715 */
39716 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
39717   PgHdr *pPg = 0;
39718   assert( pPager!=0 );
39719   assert( pgno!=0 );
39720   assert( pPager->pPCache!=0 );
39721   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
39722   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
39723   return pPg;
39724 }
39725
39726 /*
39727 ** Release a page reference.
39728 **
39729 ** If the number of references to the page drop to zero, then the
39730 ** page is added to the LRU list.  When all references to all pages
39731 ** are released, a rollback occurs and the lock on the database is
39732 ** removed.
39733 */
39734 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
39735   if( pPg ){
39736     Pager *pPager = pPg->pPager;
39737     sqlite3PcacheRelease(pPg);
39738     pagerUnlockIfUnused(pPager);
39739   }
39740 }
39741
39742 /*
39743 ** This function is called at the start of every write transaction.
39744 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
39745 ** file when this routine is called.
39746 **
39747 ** Open the journal file for pager pPager and write a journal header
39748 ** to the start of it. If there are active savepoints, open the sub-journal
39749 ** as well. This function is only used when the journal file is being 
39750 ** opened to write a rollback log for a transaction. It is not used 
39751 ** when opening a hot journal file to roll it back.
39752 **
39753 ** If the journal file is already open (as it may be in exclusive mode),
39754 ** then this function just writes a journal header to the start of the
39755 ** already open file. 
39756 **
39757 ** Whether or not the journal file is opened by this function, the
39758 ** Pager.pInJournal bitvec structure is allocated.
39759 **
39760 ** Return SQLITE_OK if everything is successful. Otherwise, return 
39761 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
39762 ** an IO error code if opening or writing the journal file fails.
39763 */
39764 static int pager_open_journal(Pager *pPager){
39765   int rc = SQLITE_OK;                        /* Return code */
39766   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
39767
39768   assert( pPager->eState==PAGER_WRITER_LOCKED );
39769   assert( assert_pager_state(pPager) );
39770   assert( pPager->pInJournal==0 );
39771   
39772   /* If already in the error state, this function is a no-op.  But on
39773   ** the other hand, this routine is never called if we are already in
39774   ** an error state. */
39775   if( NEVER(pPager->errCode) ) return pPager->errCode;
39776
39777   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
39778     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
39779     if( pPager->pInJournal==0 ){
39780       return SQLITE_NOMEM;
39781     }
39782   
39783     /* Open the journal file if it is not already open. */
39784     if( !isOpen(pPager->jfd) ){
39785       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
39786         sqlite3MemJournalOpen(pPager->jfd);
39787       }else{
39788         const int flags =                   /* VFS flags to open journal file */
39789           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
39790           (pPager->tempFile ? 
39791             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
39792             (SQLITE_OPEN_MAIN_JOURNAL)
39793           );
39794   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
39795         rc = sqlite3JournalOpen(
39796             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
39797         );
39798   #else
39799         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
39800   #endif
39801       }
39802       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
39803     }
39804   
39805   
39806     /* Write the first journal header to the journal file and open 
39807     ** the sub-journal if necessary.
39808     */
39809     if( rc==SQLITE_OK ){
39810       /* TODO: Check if all of these are really required. */
39811       pPager->nRec = 0;
39812       pPager->journalOff = 0;
39813       pPager->setMaster = 0;
39814       pPager->journalHdr = 0;
39815       rc = writeJournalHdr(pPager);
39816     }
39817   }
39818
39819   if( rc!=SQLITE_OK ){
39820     sqlite3BitvecDestroy(pPager->pInJournal);
39821     pPager->pInJournal = 0;
39822   }else{
39823     assert( pPager->eState==PAGER_WRITER_LOCKED );
39824     pPager->eState = PAGER_WRITER_CACHEMOD;
39825   }
39826
39827   return rc;
39828 }
39829
39830 /*
39831 ** Begin a write-transaction on the specified pager object. If a 
39832 ** write-transaction has already been opened, this function is a no-op.
39833 **
39834 ** If the exFlag argument is false, then acquire at least a RESERVED
39835 ** lock on the database file. If exFlag is true, then acquire at least
39836 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
39837 ** functions need be called.
39838 **
39839 ** If the subjInMemory argument is non-zero, then any sub-journal opened
39840 ** within this transaction will be opened as an in-memory file. This
39841 ** has no effect if the sub-journal is already opened (as it may be when
39842 ** running in exclusive mode) or if the transaction does not require a
39843 ** sub-journal. If the subjInMemory argument is zero, then any required
39844 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
39845 ** or using a temporary file otherwise.
39846 */
39847 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
39848   int rc = SQLITE_OK;
39849
39850   if( pPager->errCode ) return pPager->errCode;
39851   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
39852   pPager->subjInMemory = (u8)subjInMemory;
39853
39854   if( ALWAYS(pPager->eState==PAGER_READER) ){
39855     assert( pPager->pInJournal==0 );
39856
39857     if( pagerUseWal(pPager) ){
39858       /* If the pager is configured to use locking_mode=exclusive, and an
39859       ** exclusive lock on the database is not already held, obtain it now.
39860       */
39861       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
39862         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
39863         if( rc!=SQLITE_OK ){
39864           return rc;
39865         }
39866         sqlite3WalExclusiveMode(pPager->pWal, 1);
39867       }
39868
39869       /* Grab the write lock on the log file. If successful, upgrade to
39870       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
39871       ** The busy-handler is not invoked if another connection already
39872       ** holds the write-lock. If possible, the upper layer will call it.
39873       */
39874       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
39875     }else{
39876       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
39877       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
39878       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
39879       ** lock, but not when obtaining the RESERVED lock.
39880       */
39881       rc = pagerLockDb(pPager, RESERVED_LOCK);
39882       if( rc==SQLITE_OK && exFlag ){
39883         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
39884       }
39885     }
39886
39887     if( rc==SQLITE_OK ){
39888       /* Change to WRITER_LOCKED state.
39889       **
39890       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
39891       ** when it has an open transaction, but never to DBMOD or FINISHED.
39892       ** This is because in those states the code to roll back savepoint 
39893       ** transactions may copy data from the sub-journal into the database 
39894       ** file as well as into the page cache. Which would be incorrect in 
39895       ** WAL mode.
39896       */
39897       pPager->eState = PAGER_WRITER_LOCKED;
39898       pPager->dbHintSize = pPager->dbSize;
39899       pPager->dbFileSize = pPager->dbSize;
39900       pPager->dbOrigSize = pPager->dbSize;
39901       pPager->journalOff = 0;
39902     }
39903
39904     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
39905     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
39906     assert( assert_pager_state(pPager) );
39907   }
39908
39909   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
39910   return rc;
39911 }
39912
39913 /*
39914 ** Mark a single data page as writeable. The page is written into the 
39915 ** main journal or sub-journal as required. If the page is written into
39916 ** one of the journals, the corresponding bit is set in the 
39917 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
39918 ** of any open savepoints as appropriate.
39919 */
39920 static int pager_write(PgHdr *pPg){
39921   void *pData = pPg->pData;
39922   Pager *pPager = pPg->pPager;
39923   int rc = SQLITE_OK;
39924
39925   /* This routine is not called unless a write-transaction has already 
39926   ** been started. The journal file may or may not be open at this point.
39927   ** It is never called in the ERROR state.
39928   */
39929   assert( pPager->eState==PAGER_WRITER_LOCKED
39930        || pPager->eState==PAGER_WRITER_CACHEMOD
39931        || pPager->eState==PAGER_WRITER_DBMOD
39932   );
39933   assert( assert_pager_state(pPager) );
39934
39935   /* If an error has been previously detected, report the same error
39936   ** again. This should not happen, but the check provides robustness. */
39937   if( NEVER(pPager->errCode) )  return pPager->errCode;
39938
39939   /* Higher-level routines never call this function if database is not
39940   ** writable.  But check anyway, just for robustness. */
39941   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
39942
39943   CHECK_PAGE(pPg);
39944
39945   /* The journal file needs to be opened. Higher level routines have already
39946   ** obtained the necessary locks to begin the write-transaction, but the
39947   ** rollback journal might not yet be open. Open it now if this is the case.
39948   **
39949   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
39950   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
39951   ** an error might occur and the pager would end up in WRITER_LOCKED state
39952   ** with pages marked as dirty in the cache.
39953   */
39954   if( pPager->eState==PAGER_WRITER_LOCKED ){
39955     rc = pager_open_journal(pPager);
39956     if( rc!=SQLITE_OK ) return rc;
39957   }
39958   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
39959   assert( assert_pager_state(pPager) );
39960
39961   /* Mark the page as dirty.  If the page has already been written
39962   ** to the journal then we can return right away.
39963   */
39964   sqlite3PcacheMakeDirty(pPg);
39965   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
39966     assert( !pagerUseWal(pPager) );
39967   }else{
39968   
39969     /* The transaction journal now exists and we have a RESERVED or an
39970     ** EXCLUSIVE lock on the main database file.  Write the current page to
39971     ** the transaction journal if it is not there already.
39972     */
39973     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
39974       assert( pagerUseWal(pPager)==0 );
39975       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
39976         u32 cksum;
39977         char *pData2;
39978         i64 iOff = pPager->journalOff;
39979
39980         /* We should never write to the journal file the page that
39981         ** contains the database locks.  The following assert verifies
39982         ** that we do not. */
39983         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
39984
39985         assert( pPager->journalHdr<=pPager->journalOff );
39986         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
39987         cksum = pager_cksum(pPager, (u8*)pData2);
39988
39989         /* Even if an IO or diskfull error occurs while journalling the
39990         ** page in the block above, set the need-sync flag for the page.
39991         ** Otherwise, when the transaction is rolled back, the logic in
39992         ** playback_one_page() will think that the page needs to be restored
39993         ** in the database file. And if an IO error occurs while doing so,
39994         ** then corruption may follow.
39995         */
39996         pPg->flags |= PGHDR_NEED_SYNC;
39997
39998         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
39999         if( rc!=SQLITE_OK ) return rc;
40000         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
40001         if( rc!=SQLITE_OK ) return rc;
40002         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
40003         if( rc!=SQLITE_OK ) return rc;
40004
40005         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
40006                  pPager->journalOff, pPager->pageSize));
40007         PAGER_INCR(sqlite3_pager_writej_count);
40008         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
40009              PAGERID(pPager), pPg->pgno, 
40010              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
40011
40012         pPager->journalOff += 8 + pPager->pageSize;
40013         pPager->nRec++;
40014         assert( pPager->pInJournal!=0 );
40015         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
40016         testcase( rc==SQLITE_NOMEM );
40017         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
40018         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
40019         if( rc!=SQLITE_OK ){
40020           assert( rc==SQLITE_NOMEM );
40021           return rc;
40022         }
40023       }else{
40024         if( pPager->eState!=PAGER_WRITER_DBMOD ){
40025           pPg->flags |= PGHDR_NEED_SYNC;
40026         }
40027         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
40028                 PAGERID(pPager), pPg->pgno,
40029                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
40030       }
40031     }
40032   
40033     /* If the statement journal is open and the page is not in it,
40034     ** then write the current page to the statement journal.  Note that
40035     ** the statement journal format differs from the standard journal format
40036     ** in that it omits the checksums and the header.
40037     */
40038     if( subjRequiresPage(pPg) ){
40039       rc = subjournalPage(pPg);
40040     }
40041   }
40042
40043   /* Update the database size and return.
40044   */
40045   if( pPager->dbSize<pPg->pgno ){
40046     pPager->dbSize = pPg->pgno;
40047   }
40048   return rc;
40049 }
40050
40051 /*
40052 ** Mark a data page as writeable. This routine must be called before 
40053 ** making changes to a page. The caller must check the return value 
40054 ** of this function and be careful not to change any page data unless 
40055 ** this routine returns SQLITE_OK.
40056 **
40057 ** The difference between this function and pager_write() is that this
40058 ** function also deals with the special case where 2 or more pages
40059 ** fit on a single disk sector. In this case all co-resident pages
40060 ** must have been written to the journal file before returning.
40061 **
40062 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
40063 ** as appropriate. Otherwise, SQLITE_OK.
40064 */
40065 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
40066   int rc = SQLITE_OK;
40067
40068   PgHdr *pPg = pDbPage;
40069   Pager *pPager = pPg->pPager;
40070   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
40071
40072   assert( pPager->eState>=PAGER_WRITER_LOCKED );
40073   assert( pPager->eState!=PAGER_ERROR );
40074   assert( assert_pager_state(pPager) );
40075
40076   if( nPagePerSector>1 ){
40077     Pgno nPageCount;          /* Total number of pages in database file */
40078     Pgno pg1;                 /* First page of the sector pPg is located on. */
40079     int nPage = 0;            /* Number of pages starting at pg1 to journal */
40080     int ii;                   /* Loop counter */
40081     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
40082
40083     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
40084     ** a journal header to be written between the pages journaled by
40085     ** this function.
40086     */
40087     assert( !MEMDB );
40088     assert( pPager->doNotSyncSpill==0 );
40089     pPager->doNotSyncSpill++;
40090
40091     /* This trick assumes that both the page-size and sector-size are
40092     ** an integer power of 2. It sets variable pg1 to the identifier
40093     ** of the first page of the sector pPg is located on.
40094     */
40095     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
40096
40097     nPageCount = pPager->dbSize;
40098     if( pPg->pgno>nPageCount ){
40099       nPage = (pPg->pgno - pg1)+1;
40100     }else if( (pg1+nPagePerSector-1)>nPageCount ){
40101       nPage = nPageCount+1-pg1;
40102     }else{
40103       nPage = nPagePerSector;
40104     }
40105     assert(nPage>0);
40106     assert(pg1<=pPg->pgno);
40107     assert((pg1+nPage)>pPg->pgno);
40108
40109     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
40110       Pgno pg = pg1+ii;
40111       PgHdr *pPage;
40112       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
40113         if( pg!=PAGER_MJ_PGNO(pPager) ){
40114           rc = sqlite3PagerGet(pPager, pg, &pPage);
40115           if( rc==SQLITE_OK ){
40116             rc = pager_write(pPage);
40117             if( pPage->flags&PGHDR_NEED_SYNC ){
40118               needSync = 1;
40119             }
40120             sqlite3PagerUnref(pPage);
40121           }
40122         }
40123       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
40124         if( pPage->flags&PGHDR_NEED_SYNC ){
40125           needSync = 1;
40126         }
40127         sqlite3PagerUnref(pPage);
40128       }
40129     }
40130
40131     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
40132     ** starting at pg1, then it needs to be set for all of them. Because
40133     ** writing to any of these nPage pages may damage the others, the
40134     ** journal file must contain sync()ed copies of all of them
40135     ** before any of them can be written out to the database file.
40136     */
40137     if( rc==SQLITE_OK && needSync ){
40138       assert( !MEMDB );
40139       for(ii=0; ii<nPage; ii++){
40140         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
40141         if( pPage ){
40142           pPage->flags |= PGHDR_NEED_SYNC;
40143           sqlite3PagerUnref(pPage);
40144         }
40145       }
40146     }
40147
40148     assert( pPager->doNotSyncSpill==1 );
40149     pPager->doNotSyncSpill--;
40150   }else{
40151     rc = pager_write(pDbPage);
40152   }
40153   return rc;
40154 }
40155
40156 /*
40157 ** Return TRUE if the page given in the argument was previously passed
40158 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
40159 ** to change the content of the page.
40160 */
40161 #ifndef NDEBUG
40162 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
40163   return pPg->flags&PGHDR_DIRTY;
40164 }
40165 #endif
40166
40167 /*
40168 ** A call to this routine tells the pager that it is not necessary to
40169 ** write the information on page pPg back to the disk, even though
40170 ** that page might be marked as dirty.  This happens, for example, when
40171 ** the page has been added as a leaf of the freelist and so its
40172 ** content no longer matters.
40173 **
40174 ** The overlying software layer calls this routine when all of the data
40175 ** on the given page is unused. The pager marks the page as clean so
40176 ** that it does not get written to disk.
40177 **
40178 ** Tests show that this optimization can quadruple the speed of large 
40179 ** DELETE operations.
40180 */
40181 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
40182   Pager *pPager = pPg->pPager;
40183   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
40184     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
40185     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
40186     pPg->flags |= PGHDR_DONT_WRITE;
40187     pager_set_pagehash(pPg);
40188   }
40189 }
40190
40191 /*
40192 ** This routine is called to increment the value of the database file 
40193 ** change-counter, stored as a 4-byte big-endian integer starting at 
40194 ** byte offset 24 of the pager file.
40195 **
40196 ** If the isDirectMode flag is zero, then this is done by calling 
40197 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
40198 ** page data. In this case the file will be updated when the current
40199 ** transaction is committed.
40200 **
40201 ** The isDirectMode flag may only be non-zero if the library was compiled
40202 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
40203 ** if isDirect is non-zero, then the database file is updated directly
40204 ** by writing an updated version of page 1 using a call to the 
40205 ** sqlite3OsWrite() function.
40206 */
40207 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
40208   int rc = SQLITE_OK;
40209
40210   assert( pPager->eState==PAGER_WRITER_CACHEMOD
40211        || pPager->eState==PAGER_WRITER_DBMOD
40212   );
40213   assert( assert_pager_state(pPager) );
40214
40215   /* Declare and initialize constant integer 'isDirect'. If the
40216   ** atomic-write optimization is enabled in this build, then isDirect
40217   ** is initialized to the value passed as the isDirectMode parameter
40218   ** to this function. Otherwise, it is always set to zero.
40219   **
40220   ** The idea is that if the atomic-write optimization is not
40221   ** enabled at compile time, the compiler can omit the tests of
40222   ** 'isDirect' below, as well as the block enclosed in the
40223   ** "if( isDirect )" condition.
40224   */
40225 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
40226 # define DIRECT_MODE 0
40227   assert( isDirectMode==0 );
40228   UNUSED_PARAMETER(isDirectMode);
40229 #else
40230 # define DIRECT_MODE isDirectMode
40231 #endif
40232
40233   if( !pPager->changeCountDone && pPager->dbSize>0 ){
40234     PgHdr *pPgHdr;                /* Reference to page 1 */
40235     u32 change_counter;           /* Initial value of change-counter field */
40236
40237     assert( !pPager->tempFile && isOpen(pPager->fd) );
40238
40239     /* Open page 1 of the file for writing. */
40240     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
40241     assert( pPgHdr==0 || rc==SQLITE_OK );
40242
40243     /* If page one was fetched successfully, and this function is not
40244     ** operating in direct-mode, make page 1 writable.  When not in 
40245     ** direct mode, page 1 is always held in cache and hence the PagerGet()
40246     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
40247     */
40248     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
40249       rc = sqlite3PagerWrite(pPgHdr);
40250     }
40251
40252     if( rc==SQLITE_OK ){
40253       /* Increment the value just read and write it back to byte 24. */
40254       change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
40255       change_counter++;
40256       put32bits(((char*)pPgHdr->pData)+24, change_counter);
40257
40258       /* Also store the SQLite version number in bytes 96..99 and in
40259       ** bytes 92..95 store the change counter for which the version number
40260       ** is valid. */
40261       put32bits(((char*)pPgHdr->pData)+92, change_counter);
40262       put32bits(((char*)pPgHdr->pData)+96, SQLITE_VERSION_NUMBER);
40263
40264       /* If running in direct mode, write the contents of page 1 to the file. */
40265       if( DIRECT_MODE ){
40266         const void *zBuf;
40267         assert( pPager->dbFileSize>0 );
40268         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
40269         if( rc==SQLITE_OK ){
40270           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
40271         }
40272         if( rc==SQLITE_OK ){
40273           pPager->changeCountDone = 1;
40274         }
40275       }else{
40276         pPager->changeCountDone = 1;
40277       }
40278     }
40279
40280     /* Release the page reference. */
40281     sqlite3PagerUnref(pPgHdr);
40282   }
40283   return rc;
40284 }
40285
40286 /*
40287 ** Sync the database file to disk. This is a no-op for in-memory databases
40288 ** or pages with the Pager.noSync flag set.
40289 **
40290 ** If successful, or if called on a pager for which it is a no-op, this
40291 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
40292 */
40293 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
40294   int rc;                              /* Return code */
40295   assert( !MEMDB );
40296   if( pPager->noSync ){
40297     rc = SQLITE_OK;
40298   }else{
40299     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
40300   }
40301   return rc;
40302 }
40303
40304 /*
40305 ** This function may only be called while a write-transaction is active in
40306 ** rollback. If the connection is in WAL mode, this call is a no-op. 
40307 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
40308 ** the database file, an attempt is made to obtain one.
40309 **
40310 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
40311 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
40312 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
40313 ** returned.
40314 */
40315 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
40316   int rc = SQLITE_OK;
40317   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
40318        || pPager->eState==PAGER_WRITER_DBMOD 
40319        || pPager->eState==PAGER_WRITER_LOCKED 
40320   );
40321   assert( assert_pager_state(pPager) );
40322   if( 0==pagerUseWal(pPager) ){
40323     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
40324   }
40325   return rc;
40326 }
40327
40328 /*
40329 ** Sync the database file for the pager pPager. zMaster points to the name
40330 ** of a master journal file that should be written into the individual
40331 ** journal file. zMaster may be NULL, which is interpreted as no master
40332 ** journal (a single database transaction).
40333 **
40334 ** This routine ensures that:
40335 **
40336 **   * The database file change-counter is updated,
40337 **   * the journal is synced (unless the atomic-write optimization is used),
40338 **   * all dirty pages are written to the database file, 
40339 **   * the database file is truncated (if required), and
40340 **   * the database file synced. 
40341 **
40342 ** The only thing that remains to commit the transaction is to finalize 
40343 ** (delete, truncate or zero the first part of) the journal file (or 
40344 ** delete the master journal file if specified).
40345 **
40346 ** Note that if zMaster==NULL, this does not overwrite a previous value
40347 ** passed to an sqlite3PagerCommitPhaseOne() call.
40348 **
40349 ** If the final parameter - noSync - is true, then the database file itself
40350 ** is not synced. The caller must call sqlite3PagerSync() directly to
40351 ** sync the database file before calling CommitPhaseTwo() to delete the
40352 ** journal file in this case.
40353 */
40354 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
40355   Pager *pPager,                  /* Pager object */
40356   const char *zMaster,            /* If not NULL, the master journal name */
40357   int noSync                      /* True to omit the xSync on the db file */
40358 ){
40359   int rc = SQLITE_OK;             /* Return code */
40360
40361   assert( pPager->eState==PAGER_WRITER_LOCKED
40362        || pPager->eState==PAGER_WRITER_CACHEMOD
40363        || pPager->eState==PAGER_WRITER_DBMOD
40364        || pPager->eState==PAGER_ERROR
40365   );
40366   assert( assert_pager_state(pPager) );
40367
40368   /* If a prior error occurred, report that error again. */
40369   if( NEVER(pPager->errCode) ) return pPager->errCode;
40370
40371   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
40372       pPager->zFilename, zMaster, pPager->dbSize));
40373
40374   /* If no database changes have been made, return early. */
40375   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
40376
40377   if( MEMDB ){
40378     /* If this is an in-memory db, or no pages have been written to, or this
40379     ** function has already been called, it is mostly a no-op.  However, any
40380     ** backup in progress needs to be restarted.
40381     */
40382     sqlite3BackupRestart(pPager->pBackup);
40383   }else{
40384     if( pagerUseWal(pPager) ){
40385       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
40386       if( pList ){
40387         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
40388             (pPager->fullSync ? pPager->syncFlags : 0)
40389         );
40390       }
40391       if( rc==SQLITE_OK ){
40392         sqlite3PcacheCleanAll(pPager->pPCache);
40393       }
40394     }else{
40395       /* The following block updates the change-counter. Exactly how it
40396       ** does this depends on whether or not the atomic-update optimization
40397       ** was enabled at compile time, and if this transaction meets the 
40398       ** runtime criteria to use the operation: 
40399       **
40400       **    * The file-system supports the atomic-write property for
40401       **      blocks of size page-size, and 
40402       **    * This commit is not part of a multi-file transaction, and
40403       **    * Exactly one page has been modified and store in the journal file.
40404       **
40405       ** If the optimization was not enabled at compile time, then the
40406       ** pager_incr_changecounter() function is called to update the change
40407       ** counter in 'indirect-mode'. If the optimization is compiled in but
40408       ** is not applicable to this transaction, call sqlite3JournalCreate()
40409       ** to make sure the journal file has actually been created, then call
40410       ** pager_incr_changecounter() to update the change-counter in indirect
40411       ** mode. 
40412       **
40413       ** Otherwise, if the optimization is both enabled and applicable,
40414       ** then call pager_incr_changecounter() to update the change-counter
40415       ** in 'direct' mode. In this case the journal file will never be
40416       ** created for this transaction.
40417       */
40418   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40419       PgHdr *pPg;
40420       assert( isOpen(pPager->jfd) 
40421            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
40422            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
40423       );
40424       if( !zMaster && isOpen(pPager->jfd) 
40425        && pPager->journalOff==jrnlBufferSize(pPager) 
40426        && pPager->dbSize>=pPager->dbOrigSize
40427        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
40428       ){
40429         /* Update the db file change counter via the direct-write method. The 
40430         ** following call will modify the in-memory representation of page 1 
40431         ** to include the updated change counter and then write page 1 
40432         ** directly to the database file. Because of the atomic-write 
40433         ** property of the host file-system, this is safe.
40434         */
40435         rc = pager_incr_changecounter(pPager, 1);
40436       }else{
40437         rc = sqlite3JournalCreate(pPager->jfd);
40438         if( rc==SQLITE_OK ){
40439           rc = pager_incr_changecounter(pPager, 0);
40440         }
40441       }
40442   #else
40443       rc = pager_incr_changecounter(pPager, 0);
40444   #endif
40445       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40446   
40447       /* If this transaction has made the database smaller, then all pages
40448       ** being discarded by the truncation must be written to the journal
40449       ** file. This can only happen in auto-vacuum mode.
40450       **
40451       ** Before reading the pages with page numbers larger than the 
40452       ** current value of Pager.dbSize, set dbSize back to the value
40453       ** that it took at the start of the transaction. Otherwise, the
40454       ** calls to sqlite3PagerGet() return zeroed pages instead of 
40455       ** reading data from the database file.
40456       */
40457   #ifndef SQLITE_OMIT_AUTOVACUUM
40458       if( pPager->dbSize<pPager->dbOrigSize 
40459        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
40460       ){
40461         Pgno i;                                   /* Iterator variable */
40462         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
40463         const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
40464         pPager->dbSize = pPager->dbOrigSize;
40465         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
40466           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
40467             PgHdr *pPage;             /* Page to journal */
40468             rc = sqlite3PagerGet(pPager, i, &pPage);
40469             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40470             rc = sqlite3PagerWrite(pPage);
40471             sqlite3PagerUnref(pPage);
40472             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40473           }
40474         }
40475         pPager->dbSize = dbSize;
40476       } 
40477   #endif
40478   
40479       /* Write the master journal name into the journal file. If a master 
40480       ** journal file name has already been written to the journal file, 
40481       ** or if zMaster is NULL (no master journal), then this call is a no-op.
40482       */
40483       rc = writeMasterJournal(pPager, zMaster);
40484       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40485   
40486       /* Sync the journal file and write all dirty pages to the database.
40487       ** If the atomic-update optimization is being used, this sync will not 
40488       ** create the journal file or perform any real IO.
40489       **
40490       ** Because the change-counter page was just modified, unless the
40491       ** atomic-update optimization is used it is almost certain that the
40492       ** journal requires a sync here. However, in locking_mode=exclusive
40493       ** on a system under memory pressure it is just possible that this is 
40494       ** not the case. In this case it is likely enough that the redundant
40495       ** xSync() call will be changed to a no-op by the OS anyhow. 
40496       */
40497       rc = syncJournal(pPager, 0);
40498       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40499   
40500       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
40501       if( rc!=SQLITE_OK ){
40502         assert( rc!=SQLITE_IOERR_BLOCKED );
40503         goto commit_phase_one_exit;
40504       }
40505       sqlite3PcacheCleanAll(pPager->pPCache);
40506   
40507       /* If the file on disk is not the same size as the database image,
40508       ** then use pager_truncate to grow or shrink the file here.
40509       */
40510       if( pPager->dbSize!=pPager->dbFileSize ){
40511         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
40512         assert( pPager->eState==PAGER_WRITER_DBMOD );
40513         rc = pager_truncate(pPager, nNew);
40514         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
40515       }
40516   
40517       /* Finally, sync the database file. */
40518       if( !pPager->noSync && !noSync ){
40519         rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
40520       }
40521       IOTRACE(("DBSYNC %p\n", pPager))
40522     }
40523   }
40524
40525 commit_phase_one_exit:
40526   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
40527     pPager->eState = PAGER_WRITER_FINISHED;
40528   }
40529   return rc;
40530 }
40531
40532
40533 /*
40534 ** When this function is called, the database file has been completely
40535 ** updated to reflect the changes made by the current transaction and
40536 ** synced to disk. The journal file still exists in the file-system 
40537 ** though, and if a failure occurs at this point it will eventually
40538 ** be used as a hot-journal and the current transaction rolled back.
40539 **
40540 ** This function finalizes the journal file, either by deleting, 
40541 ** truncating or partially zeroing it, so that it cannot be used 
40542 ** for hot-journal rollback. Once this is done the transaction is
40543 ** irrevocably committed.
40544 **
40545 ** If an error occurs, an IO error code is returned and the pager
40546 ** moves into the error state. Otherwise, SQLITE_OK is returned.
40547 */
40548 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
40549   int rc = SQLITE_OK;                  /* Return code */
40550
40551   /* This routine should not be called if a prior error has occurred.
40552   ** But if (due to a coding error elsewhere in the system) it does get
40553   ** called, just return the same error code without doing anything. */
40554   if( NEVER(pPager->errCode) ) return pPager->errCode;
40555
40556   assert( pPager->eState==PAGER_WRITER_LOCKED
40557        || pPager->eState==PAGER_WRITER_FINISHED
40558        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
40559   );
40560   assert( assert_pager_state(pPager) );
40561
40562   /* An optimization. If the database was not actually modified during
40563   ** this transaction, the pager is running in exclusive-mode and is
40564   ** using persistent journals, then this function is a no-op.
40565   **
40566   ** The start of the journal file currently contains a single journal 
40567   ** header with the nRec field set to 0. If such a journal is used as
40568   ** a hot-journal during hot-journal rollback, 0 changes will be made
40569   ** to the database file. So there is no need to zero the journal 
40570   ** header. Since the pager is in exclusive mode, there is no need
40571   ** to drop any locks either.
40572   */
40573   if( pPager->eState==PAGER_WRITER_LOCKED 
40574    && pPager->exclusiveMode 
40575    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
40576   ){
40577     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
40578     pPager->eState = PAGER_READER;
40579     return SQLITE_OK;
40580   }
40581
40582   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
40583   rc = pager_end_transaction(pPager, pPager->setMaster);
40584   return pager_error(pPager, rc);
40585 }
40586
40587 /*
40588 ** If a write transaction is open, then all changes made within the 
40589 ** transaction are reverted and the current write-transaction is closed.
40590 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
40591 ** state if an error occurs.
40592 **
40593 ** If the pager is already in PAGER_ERROR state when this function is called,
40594 ** it returns Pager.errCode immediately. No work is performed in this case.
40595 **
40596 ** Otherwise, in rollback mode, this function performs two functions:
40597 **
40598 **   1) It rolls back the journal file, restoring all database file and 
40599 **      in-memory cache pages to the state they were in when the transaction
40600 **      was opened, and
40601 **
40602 **   2) It finalizes the journal file, so that it is not used for hot
40603 **      rollback at any point in the future.
40604 **
40605 ** Finalization of the journal file (task 2) is only performed if the 
40606 ** rollback is successful.
40607 **
40608 ** In WAL mode, all cache-entries containing data modified within the
40609 ** current transaction are either expelled from the cache or reverted to
40610 ** their pre-transaction state by re-reading data from the database or
40611 ** WAL files. The WAL transaction is then closed.
40612 */
40613 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
40614   int rc = SQLITE_OK;                  /* Return code */
40615   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
40616
40617   /* PagerRollback() is a no-op if called in READER or OPEN state. If
40618   ** the pager is already in the ERROR state, the rollback is not 
40619   ** attempted here. Instead, the error code is returned to the caller.
40620   */
40621   assert( assert_pager_state(pPager) );
40622   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
40623   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
40624
40625   if( pagerUseWal(pPager) ){
40626     int rc2;
40627     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
40628     rc2 = pager_end_transaction(pPager, pPager->setMaster);
40629     if( rc==SQLITE_OK ) rc = rc2;
40630   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
40631     rc = pager_end_transaction(pPager, 0);
40632   }else{
40633     rc = pager_playback(pPager, 0);
40634   }
40635
40636   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
40637   assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
40638
40639   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
40640   ** cache. So call pager_error() on the way out to make any error persistent.
40641   */
40642   return pager_error(pPager, rc);
40643 }
40644
40645 /*
40646 ** Return TRUE if the database file is opened read-only.  Return FALSE
40647 ** if the database is (in theory) writable.
40648 */
40649 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
40650   return pPager->readOnly;
40651 }
40652
40653 /*
40654 ** Return the number of references to the pager.
40655 */
40656 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
40657   return sqlite3PcacheRefCount(pPager->pPCache);
40658 }
40659
40660 /*
40661 ** Return the approximate number of bytes of memory currently
40662 ** used by the pager and its associated cache.
40663 */
40664 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
40665   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
40666                                      + 5*sizeof(void*);
40667   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
40668            + sqlite3MallocSize(pPager)
40669            + pPager->pageSize;
40670 }
40671
40672 /*
40673 ** Return the number of references to the specified page.
40674 */
40675 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
40676   return sqlite3PcachePageRefcount(pPage);
40677 }
40678
40679 #ifdef SQLITE_TEST
40680 /*
40681 ** This routine is used for testing and analysis only.
40682 */
40683 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
40684   static int a[11];
40685   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
40686   a[1] = sqlite3PcachePagecount(pPager->pPCache);
40687   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
40688   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
40689   a[4] = pPager->eState;
40690   a[5] = pPager->errCode;
40691   a[6] = pPager->nHit;
40692   a[7] = pPager->nMiss;
40693   a[8] = 0;  /* Used to be pPager->nOvfl */
40694   a[9] = pPager->nRead;
40695   a[10] = pPager->nWrite;
40696   return a;
40697 }
40698 #endif
40699
40700 /*
40701 ** Return true if this is an in-memory pager.
40702 */
40703 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
40704   return MEMDB;
40705 }
40706
40707 /*
40708 ** Check that there are at least nSavepoint savepoints open. If there are
40709 ** currently less than nSavepoints open, then open one or more savepoints
40710 ** to make up the difference. If the number of savepoints is already
40711 ** equal to nSavepoint, then this function is a no-op.
40712 **
40713 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
40714 ** occurs while opening the sub-journal file, then an IO error code is
40715 ** returned. Otherwise, SQLITE_OK.
40716 */
40717 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
40718   int rc = SQLITE_OK;                       /* Return code */
40719   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
40720
40721   assert( pPager->eState>=PAGER_WRITER_LOCKED );
40722   assert( assert_pager_state(pPager) );
40723
40724   if( nSavepoint>nCurrent && pPager->useJournal ){
40725     int ii;                                 /* Iterator variable */
40726     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
40727
40728     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
40729     ** if the allocation fails. Otherwise, zero the new portion in case a 
40730     ** malloc failure occurs while populating it in the for(...) loop below.
40731     */
40732     aNew = (PagerSavepoint *)sqlite3Realloc(
40733         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
40734     );
40735     if( !aNew ){
40736       return SQLITE_NOMEM;
40737     }
40738     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
40739     pPager->aSavepoint = aNew;
40740
40741     /* Populate the PagerSavepoint structures just allocated. */
40742     for(ii=nCurrent; ii<nSavepoint; ii++){
40743       aNew[ii].nOrig = pPager->dbSize;
40744       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
40745         aNew[ii].iOffset = pPager->journalOff;
40746       }else{
40747         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
40748       }
40749       aNew[ii].iSubRec = pPager->nSubRec;
40750       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
40751       if( !aNew[ii].pInSavepoint ){
40752         return SQLITE_NOMEM;
40753       }
40754       if( pagerUseWal(pPager) ){
40755         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
40756       }
40757       pPager->nSavepoint = ii+1;
40758     }
40759     assert( pPager->nSavepoint==nSavepoint );
40760     assertTruncateConstraint(pPager);
40761   }
40762
40763   return rc;
40764 }
40765
40766 /*
40767 ** This function is called to rollback or release (commit) a savepoint.
40768 ** The savepoint to release or rollback need not be the most recently 
40769 ** created savepoint.
40770 **
40771 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
40772 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
40773 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
40774 ** that have occurred since the specified savepoint was created.
40775 **
40776 ** The savepoint to rollback or release is identified by parameter 
40777 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
40778 ** (the first created). A value of (Pager.nSavepoint-1) means operate
40779 ** on the most recently created savepoint. If iSavepoint is greater than
40780 ** (Pager.nSavepoint-1), then this function is a no-op.
40781 **
40782 ** If a negative value is passed to this function, then the current
40783 ** transaction is rolled back. This is different to calling 
40784 ** sqlite3PagerRollback() because this function does not terminate
40785 ** the transaction or unlock the database, it just restores the 
40786 ** contents of the database to its original state. 
40787 **
40788 ** In any case, all savepoints with an index greater than iSavepoint 
40789 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
40790 ** then savepoint iSavepoint is also destroyed.
40791 **
40792 ** This function may return SQLITE_NOMEM if a memory allocation fails,
40793 ** or an IO error code if an IO error occurs while rolling back a 
40794 ** savepoint. If no errors occur, SQLITE_OK is returned.
40795 */ 
40796 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
40797   int rc = pPager->errCode;       /* Return code */
40798
40799   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
40800   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
40801
40802   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
40803     int ii;            /* Iterator variable */
40804     int nNew;          /* Number of remaining savepoints after this op. */
40805
40806     /* Figure out how many savepoints will still be active after this
40807     ** operation. Store this value in nNew. Then free resources associated 
40808     ** with any savepoints that are destroyed by this operation.
40809     */
40810     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
40811     for(ii=nNew; ii<pPager->nSavepoint; ii++){
40812       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
40813     }
40814     pPager->nSavepoint = nNew;
40815
40816     /* If this is a release of the outermost savepoint, truncate 
40817     ** the sub-journal to zero bytes in size. */
40818     if( op==SAVEPOINT_RELEASE ){
40819       if( nNew==0 && isOpen(pPager->sjfd) ){
40820         /* Only truncate if it is an in-memory sub-journal. */
40821         if( sqlite3IsMemJournal(pPager->sjfd) ){
40822           rc = sqlite3OsTruncate(pPager->sjfd, 0);
40823           assert( rc==SQLITE_OK );
40824         }
40825         pPager->nSubRec = 0;
40826       }
40827     }
40828     /* Else this is a rollback operation, playback the specified savepoint.
40829     ** If this is a temp-file, it is possible that the journal file has
40830     ** not yet been opened. In this case there have been no changes to
40831     ** the database file, so the playback operation can be skipped.
40832     */
40833     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
40834       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
40835       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
40836       assert(rc!=SQLITE_DONE);
40837     }
40838   }
40839
40840   return rc;
40841 }
40842
40843 /*
40844 ** Return the full pathname of the database file.
40845 */
40846 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
40847   return pPager->zFilename;
40848 }
40849
40850 /*
40851 ** Return the VFS structure for the pager.
40852 */
40853 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
40854   return pPager->pVfs;
40855 }
40856
40857 /*
40858 ** Return the file handle for the database file associated
40859 ** with the pager.  This might return NULL if the file has
40860 ** not yet been opened.
40861 */
40862 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
40863   return pPager->fd;
40864 }
40865
40866 /*
40867 ** Return the full pathname of the journal file.
40868 */
40869 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
40870   return pPager->zJournal;
40871 }
40872
40873 /*
40874 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
40875 ** if fsync()s are executed normally.
40876 */
40877 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
40878   return pPager->noSync;
40879 }
40880
40881 #ifdef SQLITE_HAS_CODEC
40882 /*
40883 ** Set or retrieve the codec for this pager
40884 */
40885 SQLITE_PRIVATE void sqlite3PagerSetCodec(
40886   Pager *pPager,
40887   void *(*xCodec)(void*,void*,Pgno,int),
40888   void (*xCodecSizeChng)(void*,int,int),
40889   void (*xCodecFree)(void*),
40890   void *pCodec
40891 ){
40892   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
40893   pPager->xCodec = pPager->memDb ? 0 : xCodec;
40894   pPager->xCodecSizeChng = xCodecSizeChng;
40895   pPager->xCodecFree = xCodecFree;
40896   pPager->pCodec = pCodec;
40897   pagerReportSize(pPager);
40898 }
40899 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
40900   return pPager->pCodec;
40901 }
40902 #endif
40903
40904 #ifndef SQLITE_OMIT_AUTOVACUUM
40905 /*
40906 ** Move the page pPg to location pgno in the file.
40907 **
40908 ** There must be no references to the page previously located at
40909 ** pgno (which we call pPgOld) though that page is allowed to be
40910 ** in cache.  If the page previously located at pgno is not already
40911 ** in the rollback journal, it is not put there by by this routine.
40912 **
40913 ** References to the page pPg remain valid. Updating any
40914 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
40915 ** allocated along with the page) is the responsibility of the caller.
40916 **
40917 ** A transaction must be active when this routine is called. It used to be
40918 ** required that a statement transaction was not active, but this restriction
40919 ** has been removed (CREATE INDEX needs to move a page when a statement
40920 ** transaction is active).
40921 **
40922 ** If the fourth argument, isCommit, is non-zero, then this page is being
40923 ** moved as part of a database reorganization just before the transaction 
40924 ** is being committed. In this case, it is guaranteed that the database page 
40925 ** pPg refers to will not be written to again within this transaction.
40926 **
40927 ** This function may return SQLITE_NOMEM or an IO error code if an error
40928 ** occurs. Otherwise, it returns SQLITE_OK.
40929 */
40930 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
40931   PgHdr *pPgOld;               /* The page being overwritten. */
40932   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
40933   int rc;                      /* Return code */
40934   Pgno origPgno;               /* The original page number */
40935
40936   assert( pPg->nRef>0 );
40937   assert( pPager->eState==PAGER_WRITER_CACHEMOD
40938        || pPager->eState==PAGER_WRITER_DBMOD
40939   );
40940   assert( assert_pager_state(pPager) );
40941
40942   /* In order to be able to rollback, an in-memory database must journal
40943   ** the page we are moving from.
40944   */
40945   if( MEMDB ){
40946     rc = sqlite3PagerWrite(pPg);
40947     if( rc ) return rc;
40948   }
40949
40950   /* If the page being moved is dirty and has not been saved by the latest
40951   ** savepoint, then save the current contents of the page into the 
40952   ** sub-journal now. This is required to handle the following scenario:
40953   **
40954   **   BEGIN;
40955   **     <journal page X, then modify it in memory>
40956   **     SAVEPOINT one;
40957   **       <Move page X to location Y>
40958   **     ROLLBACK TO one;
40959   **
40960   ** If page X were not written to the sub-journal here, it would not
40961   ** be possible to restore its contents when the "ROLLBACK TO one"
40962   ** statement were is processed.
40963   **
40964   ** subjournalPage() may need to allocate space to store pPg->pgno into
40965   ** one or more savepoint bitvecs. This is the reason this function
40966   ** may return SQLITE_NOMEM.
40967   */
40968   if( pPg->flags&PGHDR_DIRTY
40969    && subjRequiresPage(pPg)
40970    && SQLITE_OK!=(rc = subjournalPage(pPg))
40971   ){
40972     return rc;
40973   }
40974
40975   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
40976       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
40977   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
40978
40979   /* If the journal needs to be sync()ed before page pPg->pgno can
40980   ** be written to, store pPg->pgno in local variable needSyncPgno.
40981   **
40982   ** If the isCommit flag is set, there is no need to remember that
40983   ** the journal needs to be sync()ed before database page pPg->pgno 
40984   ** can be written to. The caller has already promised not to write to it.
40985   */
40986   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
40987     needSyncPgno = pPg->pgno;
40988     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
40989     assert( pPg->flags&PGHDR_DIRTY );
40990   }
40991
40992   /* If the cache contains a page with page-number pgno, remove it
40993   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
40994   ** page pgno before the 'move' operation, it needs to be retained 
40995   ** for the page moved there.
40996   */
40997   pPg->flags &= ~PGHDR_NEED_SYNC;
40998   pPgOld = pager_lookup(pPager, pgno);
40999   assert( !pPgOld || pPgOld->nRef==1 );
41000   if( pPgOld ){
41001     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
41002     if( MEMDB ){
41003       /* Do not discard pages from an in-memory database since we might
41004       ** need to rollback later.  Just move the page out of the way. */
41005       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
41006     }else{
41007       sqlite3PcacheDrop(pPgOld);
41008     }
41009   }
41010
41011   origPgno = pPg->pgno;
41012   sqlite3PcacheMove(pPg, pgno);
41013   sqlite3PcacheMakeDirty(pPg);
41014
41015   /* For an in-memory database, make sure the original page continues
41016   ** to exist, in case the transaction needs to roll back.  Use pPgOld
41017   ** as the original page since it has already been allocated.
41018   */
41019   if( MEMDB ){
41020     assert( pPgOld );
41021     sqlite3PcacheMove(pPgOld, origPgno);
41022     sqlite3PagerUnref(pPgOld);
41023   }
41024
41025   if( needSyncPgno ){
41026     /* If needSyncPgno is non-zero, then the journal file needs to be 
41027     ** sync()ed before any data is written to database file page needSyncPgno.
41028     ** Currently, no such page exists in the page-cache and the 
41029     ** "is journaled" bitvec flag has been set. This needs to be remedied by
41030     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
41031     ** flag.
41032     **
41033     ** If the attempt to load the page into the page-cache fails, (due
41034     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
41035     ** array. Otherwise, if the page is loaded and written again in
41036     ** this transaction, it may be written to the database file before
41037     ** it is synced into the journal file. This way, it may end up in
41038     ** the journal file twice, but that is not a problem.
41039     */
41040     PgHdr *pPgHdr;
41041     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
41042     if( rc!=SQLITE_OK ){
41043       if( needSyncPgno<=pPager->dbOrigSize ){
41044         assert( pPager->pTmpSpace!=0 );
41045         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
41046       }
41047       return rc;
41048     }
41049     pPgHdr->flags |= PGHDR_NEED_SYNC;
41050     sqlite3PcacheMakeDirty(pPgHdr);
41051     sqlite3PagerUnref(pPgHdr);
41052   }
41053
41054   return SQLITE_OK;
41055 }
41056 #endif
41057
41058 /*
41059 ** Return a pointer to the data for the specified page.
41060 */
41061 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
41062   assert( pPg->nRef>0 || pPg->pPager->memDb );
41063   return pPg->pData;
41064 }
41065
41066 /*
41067 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
41068 ** allocated along with the specified page.
41069 */
41070 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
41071   return pPg->pExtra;
41072 }
41073
41074 /*
41075 ** Get/set the locking-mode for this pager. Parameter eMode must be one
41076 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
41077 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
41078 ** the locking-mode is set to the value specified.
41079 **
41080 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
41081 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
41082 ** locking-mode.
41083 */
41084 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
41085   assert( eMode==PAGER_LOCKINGMODE_QUERY
41086             || eMode==PAGER_LOCKINGMODE_NORMAL
41087             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
41088   assert( PAGER_LOCKINGMODE_QUERY<0 );
41089   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
41090   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
41091   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
41092     pPager->exclusiveMode = (u8)eMode;
41093   }
41094   return (int)pPager->exclusiveMode;
41095 }
41096
41097 /*
41098 ** Set the journal-mode for this pager. Parameter eMode must be one of:
41099 **
41100 **    PAGER_JOURNALMODE_DELETE
41101 **    PAGER_JOURNALMODE_TRUNCATE
41102 **    PAGER_JOURNALMODE_PERSIST
41103 **    PAGER_JOURNALMODE_OFF
41104 **    PAGER_JOURNALMODE_MEMORY
41105 **    PAGER_JOURNALMODE_WAL
41106 **
41107 ** The journalmode is set to the value specified if the change is allowed.
41108 ** The change may be disallowed for the following reasons:
41109 **
41110 **   *  An in-memory database can only have its journal_mode set to _OFF
41111 **      or _MEMORY.
41112 **
41113 **   *  Temporary databases cannot have _WAL journalmode.
41114 **
41115 ** The returned indicate the current (possibly updated) journal-mode.
41116 */
41117 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
41118   u8 eOld = pPager->journalMode;    /* Prior journalmode */
41119
41120 #ifdef SQLITE_DEBUG
41121   /* The print_pager_state() routine is intended to be used by the debugger
41122   ** only.  We invoke it once here to suppress a compiler warning. */
41123   print_pager_state(pPager);
41124 #endif
41125
41126
41127   /* The eMode parameter is always valid */
41128   assert(      eMode==PAGER_JOURNALMODE_DELETE
41129             || eMode==PAGER_JOURNALMODE_TRUNCATE
41130             || eMode==PAGER_JOURNALMODE_PERSIST
41131             || eMode==PAGER_JOURNALMODE_OFF 
41132             || eMode==PAGER_JOURNALMODE_WAL 
41133             || eMode==PAGER_JOURNALMODE_MEMORY );
41134
41135   /* This routine is only called from the OP_JournalMode opcode, and
41136   ** the logic there will never allow a temporary file to be changed
41137   ** to WAL mode.
41138   */
41139   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
41140
41141   /* Do allow the journalmode of an in-memory database to be set to
41142   ** anything other than MEMORY or OFF
41143   */
41144   if( MEMDB ){
41145     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
41146     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
41147       eMode = eOld;
41148     }
41149   }
41150
41151   if( eMode!=eOld ){
41152
41153     /* Change the journal mode. */
41154     assert( pPager->eState!=PAGER_ERROR );
41155     pPager->journalMode = (u8)eMode;
41156
41157     /* When transistioning from TRUNCATE or PERSIST to any other journal
41158     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
41159     ** delete the journal file.
41160     */
41161     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
41162     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
41163     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
41164     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
41165     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
41166     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
41167
41168     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
41169     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
41170
41171       /* In this case we would like to delete the journal file. If it is
41172       ** not possible, then that is not a problem. Deleting the journal file
41173       ** here is an optimization only.
41174       **
41175       ** Before deleting the journal file, obtain a RESERVED lock on the
41176       ** database file. This ensures that the journal file is not deleted
41177       ** while it is in use by some other client.
41178       */
41179       sqlite3OsClose(pPager->jfd);
41180       if( pPager->eLock>=RESERVED_LOCK ){
41181         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41182       }else{
41183         int rc = SQLITE_OK;
41184         int state = pPager->eState;
41185         assert( state==PAGER_OPEN || state==PAGER_READER );
41186         if( state==PAGER_OPEN ){
41187           rc = sqlite3PagerSharedLock(pPager);
41188         }
41189         if( pPager->eState==PAGER_READER ){
41190           assert( rc==SQLITE_OK );
41191           rc = pagerLockDb(pPager, RESERVED_LOCK);
41192         }
41193         if( rc==SQLITE_OK ){
41194           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41195         }
41196         if( rc==SQLITE_OK && state==PAGER_READER ){
41197           pagerUnlockDb(pPager, SHARED_LOCK);
41198         }else if( state==PAGER_OPEN ){
41199           pager_unlock(pPager);
41200         }
41201         assert( state==pPager->eState );
41202       }
41203     }
41204   }
41205
41206   /* Return the new journal mode */
41207   return (int)pPager->journalMode;
41208 }
41209
41210 /*
41211 ** Return the current journal mode.
41212 */
41213 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
41214   return (int)pPager->journalMode;
41215 }
41216
41217 /*
41218 ** Return TRUE if the pager is in a state where it is OK to change the
41219 ** journalmode.  Journalmode changes can only happen when the database
41220 ** is unmodified.
41221 */
41222 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
41223   assert( assert_pager_state(pPager) );
41224   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
41225   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
41226   return 1;
41227 }
41228
41229 /*
41230 ** Get/set the size-limit used for persistent journal files.
41231 **
41232 ** Setting the size limit to -1 means no limit is enforced.
41233 ** An attempt to set a limit smaller than -1 is a no-op.
41234 */
41235 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
41236   if( iLimit>=-1 ){
41237     pPager->journalSizeLimit = iLimit;
41238   }
41239   return pPager->journalSizeLimit;
41240 }
41241
41242 /*
41243 ** Return a pointer to the pPager->pBackup variable. The backup module
41244 ** in backup.c maintains the content of this variable. This module
41245 ** uses it opaquely as an argument to sqlite3BackupRestart() and
41246 ** sqlite3BackupUpdate() only.
41247 */
41248 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
41249   return &pPager->pBackup;
41250 }
41251
41252 #ifndef SQLITE_OMIT_WAL
41253 /*
41254 ** This function is called when the user invokes "PRAGMA checkpoint".
41255 */
41256 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager){
41257   int rc = SQLITE_OK;
41258   if( pPager->pWal ){
41259     u8 *zBuf = (u8 *)pPager->pTmpSpace;
41260     rc = sqlite3WalCheckpoint(pPager->pWal, pPager->ckptSyncFlags,
41261                               pPager->pageSize, zBuf);
41262   }
41263   return rc;
41264 }
41265
41266 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
41267   return sqlite3WalCallback(pPager->pWal);
41268 }
41269
41270 /*
41271 ** Return true if the underlying VFS for the given pager supports the
41272 ** primitives necessary for write-ahead logging.
41273 */
41274 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
41275   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
41276   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
41277 }
41278
41279 /*
41280 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
41281 ** is obtained instead, immediately release it.
41282 */
41283 static int pagerExclusiveLock(Pager *pPager){
41284   int rc;                         /* Return code */
41285
41286   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
41287   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
41288   if( rc!=SQLITE_OK ){
41289     /* If the attempt to grab the pending lock failed, release the 
41290     ** exclusive lock that may have been obtained instead.  */
41291     pagerUnlockDb(pPager, SHARED_LOCK);
41292   }
41293
41294   return rc;
41295 }
41296
41297 /*
41298 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
41299 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
41300 ** lock on the database file and use heap-memory to store the wal-index
41301 ** in. Otherwise, use the normal shared-memory.
41302 */
41303 static int pagerOpenWal(Pager *pPager){
41304   int rc = SQLITE_OK;
41305
41306   assert( pPager->pWal==0 && pPager->tempFile==0 );
41307   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
41308
41309   /* If the pager is already in exclusive-mode, the WAL module will use 
41310   ** heap-memory for the wal-index instead of the VFS shared-memory 
41311   ** implementation. Take the exclusive lock now, before opening the WAL
41312   ** file, to make sure this is safe.
41313   */
41314   if( pPager->exclusiveMode ){
41315     rc = pagerExclusiveLock(pPager);
41316   }
41317
41318   /* Open the connection to the log file. If this operation fails, 
41319   ** (e.g. due to malloc() failure), return an error code.
41320   */
41321   if( rc==SQLITE_OK ){
41322     rc = sqlite3WalOpen(pPager->pVfs, 
41323         pPager->fd, pPager->zWal, pPager->exclusiveMode, &pPager->pWal
41324     );
41325   }
41326
41327   return rc;
41328 }
41329
41330
41331 /*
41332 ** The caller must be holding a SHARED lock on the database file to call
41333 ** this function.
41334 **
41335 ** If the pager passed as the first argument is open on a real database
41336 ** file (not a temp file or an in-memory database), and the WAL file
41337 ** is not already open, make an attempt to open it now. If successful,
41338 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
41339 ** not support the xShmXXX() methods, return an error code. *pbOpen is
41340 ** not modified in either case.
41341 **
41342 ** If the pager is open on a temp-file (or in-memory database), or if
41343 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
41344 ** without doing anything.
41345 */
41346 SQLITE_PRIVATE int sqlite3PagerOpenWal(
41347   Pager *pPager,                  /* Pager object */
41348   int *pbOpen                     /* OUT: Set to true if call is a no-op */
41349 ){
41350   int rc = SQLITE_OK;             /* Return code */
41351
41352   assert( assert_pager_state(pPager) );
41353   assert( pPager->eState==PAGER_OPEN   || pbOpen );
41354   assert( pPager->eState==PAGER_READER || !pbOpen );
41355   assert( pbOpen==0 || *pbOpen==0 );
41356   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
41357
41358   if( !pPager->tempFile && !pPager->pWal ){
41359     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
41360
41361     /* Close any rollback journal previously open */
41362     sqlite3OsClose(pPager->jfd);
41363
41364     rc = pagerOpenWal(pPager);
41365     if( rc==SQLITE_OK ){
41366       pPager->journalMode = PAGER_JOURNALMODE_WAL;
41367       pPager->eState = PAGER_OPEN;
41368     }
41369   }else{
41370     *pbOpen = 1;
41371   }
41372
41373   return rc;
41374 }
41375
41376 /*
41377 ** This function is called to close the connection to the log file prior
41378 ** to switching from WAL to rollback mode.
41379 **
41380 ** Before closing the log file, this function attempts to take an 
41381 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
41382 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
41383 ** If successful, the EXCLUSIVE lock is not released before returning.
41384 */
41385 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
41386   int rc = SQLITE_OK;
41387
41388   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
41389
41390   /* If the log file is not already open, but does exist in the file-system,
41391   ** it may need to be checkpointed before the connection can switch to
41392   ** rollback mode. Open it now so this can happen.
41393   */
41394   if( !pPager->pWal ){
41395     int logexists = 0;
41396     rc = pagerLockDb(pPager, SHARED_LOCK);
41397     if( rc==SQLITE_OK ){
41398       rc = sqlite3OsAccess(
41399           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
41400       );
41401     }
41402     if( rc==SQLITE_OK && logexists ){
41403       rc = pagerOpenWal(pPager);
41404     }
41405   }
41406     
41407   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
41408   ** the database file, the log and log-summary files will be deleted.
41409   */
41410   if( rc==SQLITE_OK && pPager->pWal ){
41411     rc = pagerExclusiveLock(pPager);
41412     if( rc==SQLITE_OK ){
41413       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
41414                            pPager->pageSize, (u8*)pPager->pTmpSpace);
41415       pPager->pWal = 0;
41416     }
41417   }
41418   return rc;
41419 }
41420
41421 #ifdef SQLITE_HAS_CODEC
41422 /*
41423 ** This function is called by the wal module when writing page content
41424 ** into the log file.
41425 **
41426 ** This function returns a pointer to a buffer containing the encrypted
41427 ** page content. If a malloc fails, this function may return NULL.
41428 */
41429 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
41430   void *aData = 0;
41431   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
41432   return aData;
41433 }
41434 #endif /* SQLITE_HAS_CODEC */
41435
41436 #endif /* !SQLITE_OMIT_WAL */
41437
41438 #endif /* SQLITE_OMIT_DISKIO */
41439
41440 /************** End of pager.c ***********************************************/
41441 /************** Begin file wal.c *********************************************/
41442 /*
41443 ** 2010 February 1
41444 **
41445 ** The author disclaims copyright to this source code.  In place of
41446 ** a legal notice, here is a blessing:
41447 **
41448 **    May you do good and not evil.
41449 **    May you find forgiveness for yourself and forgive others.
41450 **    May you share freely, never taking more than you give.
41451 **
41452 *************************************************************************
41453 **
41454 ** This file contains the implementation of a write-ahead log (WAL) used in 
41455 ** "journal_mode=WAL" mode.
41456 **
41457 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
41458 **
41459 ** A WAL file consists of a header followed by zero or more "frames".
41460 ** Each frame records the revised content of a single page from the
41461 ** database file.  All changes to the database are recorded by writing
41462 ** frames into the WAL.  Transactions commit when a frame is written that
41463 ** contains a commit marker.  A single WAL can and usually does record 
41464 ** multiple transactions.  Periodically, the content of the WAL is
41465 ** transferred back into the database file in an operation called a
41466 ** "checkpoint".
41467 **
41468 ** A single WAL file can be used multiple times.  In other words, the
41469 ** WAL can fill up with frames and then be checkpointed and then new
41470 ** frames can overwrite the old ones.  A WAL always grows from beginning
41471 ** toward the end.  Checksums and counters attached to each frame are
41472 ** used to determine which frames within the WAL are valid and which
41473 ** are leftovers from prior checkpoints.
41474 **
41475 ** The WAL header is 32 bytes in size and consists of the following eight
41476 ** big-endian 32-bit unsigned integer values:
41477 **
41478 **     0: Magic number.  0x377f0682 or 0x377f0683
41479 **     4: File format version.  Currently 3007000
41480 **     8: Database page size.  Example: 1024
41481 **    12: Checkpoint sequence number
41482 **    16: Salt-1, random integer incremented with each checkpoint
41483 **    20: Salt-2, a different random integer changing with each ckpt
41484 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
41485 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
41486 **
41487 ** Immediately following the wal-header are zero or more frames. Each
41488 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
41489 ** of page data. The frame-header is six big-endian 32-bit unsigned 
41490 ** integer values, as follows:
41491 **
41492 **     0: Page number.
41493 **     4: For commit records, the size of the database image in pages 
41494 **        after the commit. For all other records, zero.
41495 **     8: Salt-1 (copied from the header)
41496 **    12: Salt-2 (copied from the header)
41497 **    16: Checksum-1.
41498 **    20: Checksum-2.
41499 **
41500 ** A frame is considered valid if and only if the following conditions are
41501 ** true:
41502 **
41503 **    (1) The salt-1 and salt-2 values in the frame-header match
41504 **        salt values in the wal-header
41505 **
41506 **    (2) The checksum values in the final 8 bytes of the frame-header
41507 **        exactly match the checksum computed consecutively on the
41508 **        WAL header and the first 8 bytes and the content of all frames
41509 **        up to and including the current frame.
41510 **
41511 ** The checksum is computed using 32-bit big-endian integers if the
41512 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
41513 ** is computed using little-endian if the magic number is 0x377f0682.
41514 ** The checksum values are always stored in the frame header in a
41515 ** big-endian format regardless of which byte order is used to compute
41516 ** the checksum.  The checksum is computed by interpreting the input as
41517 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
41518 ** algorithm used for the checksum is as follows:
41519 ** 
41520 **   for i from 0 to n-1 step 2:
41521 **     s0 += x[i] + s1;
41522 **     s1 += x[i+1] + s0;
41523 **   endfor
41524 **
41525 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
41526 ** in reverse order (the largest fibonacci weight occurs on the first element
41527 ** of the sequence being summed.)  The s1 value spans all 32-bit 
41528 ** terms of the sequence whereas s0 omits the final term.
41529 **
41530 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
41531 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
41532 ** The VFS.xSync operations serve as write barriers - all writes launched
41533 ** before the xSync must complete before any write that launches after the
41534 ** xSync begins.
41535 **
41536 ** After each checkpoint, the salt-1 value is incremented and the salt-2
41537 ** value is randomized.  This prevents old and new frames in the WAL from
41538 ** being considered valid at the same time and being checkpointing together
41539 ** following a crash.
41540 **
41541 ** READER ALGORITHM
41542 **
41543 ** To read a page from the database (call it page number P), a reader
41544 ** first checks the WAL to see if it contains page P.  If so, then the
41545 ** last valid instance of page P that is a followed by a commit frame
41546 ** or is a commit frame itself becomes the value read.  If the WAL
41547 ** contains no copies of page P that are valid and which are a commit
41548 ** frame or are followed by a commit frame, then page P is read from
41549 ** the database file.
41550 **
41551 ** To start a read transaction, the reader records the index of the last
41552 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
41553 ** for all subsequent read operations.  New transactions can be appended
41554 ** to the WAL, but as long as the reader uses its original mxFrame value
41555 ** and ignores the newly appended content, it will see a consistent snapshot
41556 ** of the database from a single point in time.  This technique allows
41557 ** multiple concurrent readers to view different versions of the database
41558 ** content simultaneously.
41559 **
41560 ** The reader algorithm in the previous paragraphs works correctly, but 
41561 ** because frames for page P can appear anywhere within the WAL, the
41562 ** reader has to scan the entire WAL looking for page P frames.  If the
41563 ** WAL is large (multiple megabytes is typical) that scan can be slow,
41564 ** and read performance suffers.  To overcome this problem, a separate
41565 ** data structure called the wal-index is maintained to expedite the
41566 ** search for frames of a particular page.
41567 ** 
41568 ** WAL-INDEX FORMAT
41569 **
41570 ** Conceptually, the wal-index is shared memory, though VFS implementations
41571 ** might choose to implement the wal-index using a mmapped file.  Because
41572 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
41573 ** on a network filesystem.  All users of the database must be able to
41574 ** share memory.
41575 **
41576 ** The wal-index is transient.  After a crash, the wal-index can (and should
41577 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
41578 ** to either truncate or zero the header of the wal-index when the last
41579 ** connection to it closes.  Because the wal-index is transient, it can
41580 ** use an architecture-specific format; it does not have to be cross-platform.
41581 ** Hence, unlike the database and WAL file formats which store all values
41582 ** as big endian, the wal-index can store multi-byte values in the native
41583 ** byte order of the host computer.
41584 **
41585 ** The purpose of the wal-index is to answer this question quickly:  Given
41586 ** a page number P, return the index of the last frame for page P in the WAL,
41587 ** or return NULL if there are no frames for page P in the WAL.
41588 **
41589 ** The wal-index consists of a header region, followed by an one or
41590 ** more index blocks.  
41591 **
41592 ** The wal-index header contains the total number of frames within the WAL
41593 ** in the the mxFrame field.  
41594 **
41595 ** Each index block except for the first contains information on 
41596 ** HASHTABLE_NPAGE frames. The first index block contains information on
41597 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
41598 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
41599 ** first index block are the same size as all other index blocks in the
41600 ** wal-index.
41601 **
41602 ** Each index block contains two sections, a page-mapping that contains the
41603 ** database page number associated with each wal frame, and a hash-table 
41604 ** that allows readers to query an index block for a specific page number.
41605 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
41606 ** for the first index block) 32-bit page numbers. The first entry in the 
41607 ** first index-block contains the database page number corresponding to the
41608 ** first frame in the WAL file. The first entry in the second index block
41609 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
41610 ** the log, and so on.
41611 **
41612 ** The last index block in a wal-index usually contains less than the full
41613 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
41614 ** depending on the contents of the WAL file. This does not change the
41615 ** allocated size of the page-mapping array - the page-mapping array merely
41616 ** contains unused entries.
41617 **
41618 ** Even without using the hash table, the last frame for page P
41619 ** can be found by scanning the page-mapping sections of each index block
41620 ** starting with the last index block and moving toward the first, and
41621 ** within each index block, starting at the end and moving toward the
41622 ** beginning.  The first entry that equals P corresponds to the frame
41623 ** holding the content for that page.
41624 **
41625 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
41626 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
41627 ** hash table for each page number in the mapping section, so the hash 
41628 ** table is never more than half full.  The expected number of collisions 
41629 ** prior to finding a match is 1.  Each entry of the hash table is an
41630 ** 1-based index of an entry in the mapping section of the same
41631 ** index block.   Let K be the 1-based index of the largest entry in
41632 ** the mapping section.  (For index blocks other than the last, K will
41633 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
41634 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
41635 ** contain a value of 0.
41636 **
41637 ** To look for page P in the hash table, first compute a hash iKey on
41638 ** P as follows:
41639 **
41640 **      iKey = (P * 383) % HASHTABLE_NSLOT
41641 **
41642 ** Then start scanning entries of the hash table, starting with iKey
41643 ** (wrapping around to the beginning when the end of the hash table is
41644 ** reached) until an unused hash slot is found. Let the first unused slot
41645 ** be at index iUnused.  (iUnused might be less than iKey if there was
41646 ** wrap-around.) Because the hash table is never more than half full,
41647 ** the search is guaranteed to eventually hit an unused entry.  Let 
41648 ** iMax be the value between iKey and iUnused, closest to iUnused,
41649 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
41650 ** no hash slot such that aHash[i]==p) then page P is not in the
41651 ** current index block.  Otherwise the iMax-th mapping entry of the
41652 ** current index block corresponds to the last entry that references 
41653 ** page P.
41654 **
41655 ** A hash search begins with the last index block and moves toward the
41656 ** first index block, looking for entries corresponding to page P.  On
41657 ** average, only two or three slots in each index block need to be
41658 ** examined in order to either find the last entry for page P, or to
41659 ** establish that no such entry exists in the block.  Each index block
41660 ** holds over 4000 entries.  So two or three index blocks are sufficient
41661 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
41662 ** comparisons (on average) suffice to either locate a frame in the
41663 ** WAL or to establish that the frame does not exist in the WAL.  This
41664 ** is much faster than scanning the entire 10MB WAL.
41665 **
41666 ** Note that entries are added in order of increasing K.  Hence, one
41667 ** reader might be using some value K0 and a second reader that started
41668 ** at a later time (after additional transactions were added to the WAL
41669 ** and to the wal-index) might be using a different value K1, where K1>K0.
41670 ** Both readers can use the same hash table and mapping section to get
41671 ** the correct result.  There may be entries in the hash table with
41672 ** K>K0 but to the first reader, those entries will appear to be unused
41673 ** slots in the hash table and so the first reader will get an answer as
41674 ** if no values greater than K0 had ever been inserted into the hash table
41675 ** in the first place - which is what reader one wants.  Meanwhile, the
41676 ** second reader using K1 will see additional values that were inserted
41677 ** later, which is exactly what reader two wants.  
41678 **
41679 ** When a rollback occurs, the value of K is decreased. Hash table entries
41680 ** that correspond to frames greater than the new K value are removed
41681 ** from the hash table at this point.
41682 */
41683 #ifndef SQLITE_OMIT_WAL
41684
41685
41686 /*
41687 ** Trace output macros
41688 */
41689 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
41690 SQLITE_PRIVATE int sqlite3WalTrace = 0;
41691 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
41692 #else
41693 # define WALTRACE(X)
41694 #endif
41695
41696 /*
41697 ** The maximum (and only) versions of the wal and wal-index formats
41698 ** that may be interpreted by this version of SQLite.
41699 **
41700 ** If a client begins recovering a WAL file and finds that (a) the checksum
41701 ** values in the wal-header are correct and (b) the version field is not
41702 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
41703 **
41704 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
41705 ** checksum test is successful) and finds that the version field is not
41706 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
41707 ** returns SQLITE_CANTOPEN.
41708 */
41709 #define WAL_MAX_VERSION      3007000
41710 #define WALINDEX_MAX_VERSION 3007000
41711
41712 /*
41713 ** Indices of various locking bytes.   WAL_NREADER is the number
41714 ** of available reader locks and should be at least 3.
41715 */
41716 #define WAL_WRITE_LOCK         0
41717 #define WAL_ALL_BUT_WRITE      1
41718 #define WAL_CKPT_LOCK          1
41719 #define WAL_RECOVER_LOCK       2
41720 #define WAL_READ_LOCK(I)       (3+(I))
41721 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
41722
41723
41724 /* Object declarations */
41725 typedef struct WalIndexHdr WalIndexHdr;
41726 typedef struct WalIterator WalIterator;
41727 typedef struct WalCkptInfo WalCkptInfo;
41728
41729
41730 /*
41731 ** The following object holds a copy of the wal-index header content.
41732 **
41733 ** The actual header in the wal-index consists of two copies of this
41734 ** object.
41735 **
41736 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
41737 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
41738 ** added in 3.7.1 when support for 64K pages was added.  
41739 */
41740 struct WalIndexHdr {
41741   u32 iVersion;                   /* Wal-index version */
41742   u32 unused;                     /* Unused (padding) field */
41743   u32 iChange;                    /* Counter incremented each transaction */
41744   u8 isInit;                      /* 1 when initialized */
41745   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
41746   u16 szPage;                     /* Database page size in bytes. 1==64K */
41747   u32 mxFrame;                    /* Index of last valid frame in the WAL */
41748   u32 nPage;                      /* Size of database in pages */
41749   u32 aFrameCksum[2];             /* Checksum of last frame in log */
41750   u32 aSalt[2];                   /* Two salt values copied from WAL header */
41751   u32 aCksum[2];                  /* Checksum over all prior fields */
41752 };
41753
41754 /*
41755 ** A copy of the following object occurs in the wal-index immediately
41756 ** following the second copy of the WalIndexHdr.  This object stores
41757 ** information used by checkpoint.
41758 **
41759 ** nBackfill is the number of frames in the WAL that have been written
41760 ** back into the database. (We call the act of moving content from WAL to
41761 ** database "backfilling".)  The nBackfill number is never greater than
41762 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
41763 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
41764 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
41765 ** mxFrame back to zero when the WAL is reset.
41766 **
41767 ** There is one entry in aReadMark[] for each reader lock.  If a reader
41768 ** holds read-lock K, then the value in aReadMark[K] is no greater than
41769 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
41770 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
41771 ** a special case; its value is never used and it exists as a place-holder
41772 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
41773 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
41774 ** directly from the database.
41775 **
41776 ** The value of aReadMark[K] may only be changed by a thread that
41777 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
41778 ** aReadMark[K] cannot changed while there is a reader is using that mark
41779 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
41780 **
41781 ** The checkpointer may only transfer frames from WAL to database where
41782 ** the frame numbers are less than or equal to every aReadMark[] that is
41783 ** in use (that is, every aReadMark[j] for which there is a corresponding
41784 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
41785 ** largest value and will increase an unused aReadMark[] to mxFrame if there
41786 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
41787 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
41788 ** in the WAL has been backfilled into the database) then new readers
41789 ** will choose aReadMark[0] which has value 0 and hence such reader will
41790 ** get all their all content directly from the database file and ignore 
41791 ** the WAL.
41792 **
41793 ** Writers normally append new frames to the end of the WAL.  However,
41794 ** if nBackfill equals mxFrame (meaning that all WAL content has been
41795 ** written back into the database) and if no readers are using the WAL
41796 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
41797 ** the writer will first "reset" the WAL back to the beginning and start
41798 ** writing new content beginning at frame 1.
41799 **
41800 ** We assume that 32-bit loads are atomic and so no locks are needed in
41801 ** order to read from any aReadMark[] entries.
41802 */
41803 struct WalCkptInfo {
41804   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
41805   u32 aReadMark[WAL_NREADER];     /* Reader marks */
41806 };
41807 #define READMARK_NOT_USED  0xffffffff
41808
41809
41810 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
41811 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
41812 ** only support mandatory file-locks, we do not read or write data
41813 ** from the region of the file on which locks are applied.
41814 */
41815 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
41816 #define WALINDEX_LOCK_RESERVED 16
41817 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
41818
41819 /* Size of header before each frame in wal */
41820 #define WAL_FRAME_HDRSIZE 24
41821
41822 /* Size of write ahead log header, including checksum. */
41823 /* #define WAL_HDRSIZE 24 */
41824 #define WAL_HDRSIZE 32
41825
41826 /* WAL magic value. Either this value, or the same value with the least
41827 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
41828 ** big-endian format in the first 4 bytes of a WAL file.
41829 **
41830 ** If the LSB is set, then the checksums for each frame within the WAL
41831 ** file are calculated by treating all data as an array of 32-bit 
41832 ** big-endian words. Otherwise, they are calculated by interpreting 
41833 ** all data as 32-bit little-endian words.
41834 */
41835 #define WAL_MAGIC 0x377f0682
41836
41837 /*
41838 ** Return the offset of frame iFrame in the write-ahead log file, 
41839 ** assuming a database page size of szPage bytes. The offset returned
41840 ** is to the start of the write-ahead log frame-header.
41841 */
41842 #define walFrameOffset(iFrame, szPage) (                               \
41843   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
41844 )
41845
41846 /*
41847 ** An open write-ahead log file is represented by an instance of the
41848 ** following object.
41849 */
41850 struct Wal {
41851   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
41852   sqlite3_file *pDbFd;       /* File handle for the database file */
41853   sqlite3_file *pWalFd;      /* File handle for WAL file */
41854   u32 iCallback;             /* Value to pass to log callback (or 0) */
41855   int nWiData;               /* Size of array apWiData */
41856   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
41857   u32 szPage;                /* Database page size */
41858   i16 readLock;              /* Which read lock is being held.  -1 for none */
41859   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
41860   u8 writeLock;              /* True if in a write transaction */
41861   u8 ckptLock;               /* True if holding a checkpoint lock */
41862   u8 readOnly;               /* True if the WAL file is open read-only */
41863   WalIndexHdr hdr;           /* Wal-index header for current transaction */
41864   const char *zWalName;      /* Name of WAL file */
41865   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
41866 #ifdef SQLITE_DEBUG
41867   u8 lockError;              /* True if a locking error has occurred */
41868 #endif
41869 };
41870
41871 /*
41872 ** Candidate values for Wal.exclusiveMode.
41873 */
41874 #define WAL_NORMAL_MODE     0
41875 #define WAL_EXCLUSIVE_MODE  1     
41876 #define WAL_HEAPMEMORY_MODE 2
41877
41878 /*
41879 ** Each page of the wal-index mapping contains a hash-table made up of
41880 ** an array of HASHTABLE_NSLOT elements of the following type.
41881 */
41882 typedef u16 ht_slot;
41883
41884 /*
41885 ** This structure is used to implement an iterator that loops through
41886 ** all frames in the WAL in database page order. Where two or more frames
41887 ** correspond to the same database page, the iterator visits only the 
41888 ** frame most recently written to the WAL (in other words, the frame with
41889 ** the largest index).
41890 **
41891 ** The internals of this structure are only accessed by:
41892 **
41893 **   walIteratorInit() - Create a new iterator,
41894 **   walIteratorNext() - Step an iterator,
41895 **   walIteratorFree() - Free an iterator.
41896 **
41897 ** This functionality is used by the checkpoint code (see walCheckpoint()).
41898 */
41899 struct WalIterator {
41900   int iPrior;                     /* Last result returned from the iterator */
41901   int nSegment;                   /* Size of the aSegment[] array */
41902   struct WalSegment {
41903     int iNext;                    /* Next slot in aIndex[] not yet returned */
41904     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
41905     u32 *aPgno;                   /* Array of page numbers. */
41906     int nEntry;                   /* Max size of aPgno[] and aIndex[] arrays */
41907     int iZero;                    /* Frame number associated with aPgno[0] */
41908   } aSegment[1];                  /* One for every 32KB page in the WAL */
41909 };
41910
41911 /*
41912 ** Define the parameters of the hash tables in the wal-index file. There
41913 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
41914 ** wal-index.
41915 **
41916 ** Changing any of these constants will alter the wal-index format and
41917 ** create incompatibilities.
41918 */
41919 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
41920 #define HASHTABLE_HASH_1     383                  /* Should be prime */
41921 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
41922
41923 /* 
41924 ** The block of page numbers associated with the first hash-table in a
41925 ** wal-index is smaller than usual. This is so that there is a complete
41926 ** hash-table on each aligned 32KB page of the wal-index.
41927 */
41928 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
41929
41930 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
41931 #define WALINDEX_PGSZ   (                                         \
41932     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
41933 )
41934
41935 /*
41936 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
41937 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
41938 ** numbered from zero.
41939 **
41940 ** If this call is successful, *ppPage is set to point to the wal-index
41941 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
41942 ** then an SQLite error code is returned and *ppPage is set to 0.
41943 */
41944 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
41945   int rc = SQLITE_OK;
41946
41947   /* Enlarge the pWal->apWiData[] array if required */
41948   if( pWal->nWiData<=iPage ){
41949     int nByte = sizeof(u32*)*(iPage+1);
41950     volatile u32 **apNew;
41951     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
41952     if( !apNew ){
41953       *ppPage = 0;
41954       return SQLITE_NOMEM;
41955     }
41956     memset((void*)&apNew[pWal->nWiData], 0,
41957            sizeof(u32*)*(iPage+1-pWal->nWiData));
41958     pWal->apWiData = apNew;
41959     pWal->nWiData = iPage+1;
41960   }
41961
41962   /* Request a pointer to the required page from the VFS */
41963   if( pWal->apWiData[iPage]==0 ){
41964     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
41965       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
41966       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
41967     }else{
41968       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
41969           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
41970       );
41971     }
41972   }
41973
41974   *ppPage = pWal->apWiData[iPage];
41975   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
41976   return rc;
41977 }
41978
41979 /*
41980 ** Return a pointer to the WalCkptInfo structure in the wal-index.
41981 */
41982 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
41983   assert( pWal->nWiData>0 && pWal->apWiData[0] );
41984   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
41985 }
41986
41987 /*
41988 ** Return a pointer to the WalIndexHdr structure in the wal-index.
41989 */
41990 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
41991   assert( pWal->nWiData>0 && pWal->apWiData[0] );
41992   return (volatile WalIndexHdr*)pWal->apWiData[0];
41993 }
41994
41995 /*
41996 ** The argument to this macro must be of type u32. On a little-endian
41997 ** architecture, it returns the u32 value that results from interpreting
41998 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
41999 ** returns the value that would be produced by intepreting the 4 bytes
42000 ** of the input value as a little-endian integer.
42001 */
42002 #define BYTESWAP32(x) ( \
42003     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
42004   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
42005 )
42006
42007 /*
42008 ** Generate or extend an 8 byte checksum based on the data in 
42009 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
42010 ** initial values of 0 and 0 if aIn==NULL).
42011 **
42012 ** The checksum is written back into aOut[] before returning.
42013 **
42014 ** nByte must be a positive multiple of 8.
42015 */
42016 static void walChecksumBytes(
42017   int nativeCksum, /* True for native byte-order, false for non-native */
42018   u8 *a,           /* Content to be checksummed */
42019   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
42020   const u32 *aIn,  /* Initial checksum value input */
42021   u32 *aOut        /* OUT: Final checksum value output */
42022 ){
42023   u32 s1, s2;
42024   u32 *aData = (u32 *)a;
42025   u32 *aEnd = (u32 *)&a[nByte];
42026
42027   if( aIn ){
42028     s1 = aIn[0];
42029     s2 = aIn[1];
42030   }else{
42031     s1 = s2 = 0;
42032   }
42033
42034   assert( nByte>=8 );
42035   assert( (nByte&0x00000007)==0 );
42036
42037   if( nativeCksum ){
42038     do {
42039       s1 += *aData++ + s2;
42040       s2 += *aData++ + s1;
42041     }while( aData<aEnd );
42042   }else{
42043     do {
42044       s1 += BYTESWAP32(aData[0]) + s2;
42045       s2 += BYTESWAP32(aData[1]) + s1;
42046       aData += 2;
42047     }while( aData<aEnd );
42048   }
42049
42050   aOut[0] = s1;
42051   aOut[1] = s2;
42052 }
42053
42054 static void walShmBarrier(Wal *pWal){
42055   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
42056     sqlite3OsShmBarrier(pWal->pDbFd);
42057   }
42058 }
42059
42060 /*
42061 ** Write the header information in pWal->hdr into the wal-index.
42062 **
42063 ** The checksum on pWal->hdr is updated before it is written.
42064 */
42065 static void walIndexWriteHdr(Wal *pWal){
42066   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
42067   const int nCksum = offsetof(WalIndexHdr, aCksum);
42068
42069   assert( pWal->writeLock );
42070   pWal->hdr.isInit = 1;
42071   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
42072   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
42073   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
42074   walShmBarrier(pWal);
42075   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
42076 }
42077
42078 /*
42079 ** This function encodes a single frame header and writes it to a buffer
42080 ** supplied by the caller. A frame-header is made up of a series of 
42081 ** 4-byte big-endian integers, as follows:
42082 **
42083 **     0: Page number.
42084 **     4: For commit records, the size of the database image in pages 
42085 **        after the commit. For all other records, zero.
42086 **     8: Salt-1 (copied from the wal-header)
42087 **    12: Salt-2 (copied from the wal-header)
42088 **    16: Checksum-1.
42089 **    20: Checksum-2.
42090 */
42091 static void walEncodeFrame(
42092   Wal *pWal,                      /* The write-ahead log */
42093   u32 iPage,                      /* Database page number for frame */
42094   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
42095   u8 *aData,                      /* Pointer to page data */
42096   u8 *aFrame                      /* OUT: Write encoded frame here */
42097 ){
42098   int nativeCksum;                /* True for native byte-order checksums */
42099   u32 *aCksum = pWal->hdr.aFrameCksum;
42100   assert( WAL_FRAME_HDRSIZE==24 );
42101   sqlite3Put4byte(&aFrame[0], iPage);
42102   sqlite3Put4byte(&aFrame[4], nTruncate);
42103   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
42104
42105   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
42106   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
42107   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
42108
42109   sqlite3Put4byte(&aFrame[16], aCksum[0]);
42110   sqlite3Put4byte(&aFrame[20], aCksum[1]);
42111 }
42112
42113 /*
42114 ** Check to see if the frame with header in aFrame[] and content
42115 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
42116 ** *pnTruncate and return true.  Return if the frame is not valid.
42117 */
42118 static int walDecodeFrame(
42119   Wal *pWal,                      /* The write-ahead log */
42120   u32 *piPage,                    /* OUT: Database page number for frame */
42121   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
42122   u8 *aData,                      /* Pointer to page data (for checksum) */
42123   u8 *aFrame                      /* Frame data */
42124 ){
42125   int nativeCksum;                /* True for native byte-order checksums */
42126   u32 *aCksum = pWal->hdr.aFrameCksum;
42127   u32 pgno;                       /* Page number of the frame */
42128   assert( WAL_FRAME_HDRSIZE==24 );
42129
42130   /* A frame is only valid if the salt values in the frame-header
42131   ** match the salt values in the wal-header. 
42132   */
42133   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
42134     return 0;
42135   }
42136
42137   /* A frame is only valid if the page number is creater than zero.
42138   */
42139   pgno = sqlite3Get4byte(&aFrame[0]);
42140   if( pgno==0 ){
42141     return 0;
42142   }
42143
42144   /* A frame is only valid if a checksum of the WAL header,
42145   ** all prior frams, the first 16 bytes of this frame-header, 
42146   ** and the frame-data matches the checksum in the last 8 
42147   ** bytes of this frame-header.
42148   */
42149   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
42150   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
42151   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
42152   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
42153    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
42154   ){
42155     /* Checksum failed. */
42156     return 0;
42157   }
42158
42159   /* If we reach this point, the frame is valid.  Return the page number
42160   ** and the new database size.
42161   */
42162   *piPage = pgno;
42163   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
42164   return 1;
42165 }
42166
42167
42168 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
42169 /*
42170 ** Names of locks.  This routine is used to provide debugging output and is not
42171 ** a part of an ordinary build.
42172 */
42173 static const char *walLockName(int lockIdx){
42174   if( lockIdx==WAL_WRITE_LOCK ){
42175     return "WRITE-LOCK";
42176   }else if( lockIdx==WAL_CKPT_LOCK ){
42177     return "CKPT-LOCK";
42178   }else if( lockIdx==WAL_RECOVER_LOCK ){
42179     return "RECOVER-LOCK";
42180   }else{
42181     static char zName[15];
42182     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
42183                      lockIdx-WAL_READ_LOCK(0));
42184     return zName;
42185   }
42186 }
42187 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
42188     
42189
42190 /*
42191 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
42192 ** A lock cannot be moved directly between shared and exclusive - it must go
42193 ** through the unlocked state first.
42194 **
42195 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
42196 */
42197 static int walLockShared(Wal *pWal, int lockIdx){
42198   int rc;
42199   if( pWal->exclusiveMode ) return SQLITE_OK;
42200   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
42201                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
42202   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
42203             walLockName(lockIdx), rc ? "failed" : "ok"));
42204   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
42205   return rc;
42206 }
42207 static void walUnlockShared(Wal *pWal, int lockIdx){
42208   if( pWal->exclusiveMode ) return;
42209   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
42210                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
42211   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
42212 }
42213 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
42214   int rc;
42215   if( pWal->exclusiveMode ) return SQLITE_OK;
42216   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
42217                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
42218   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
42219             walLockName(lockIdx), n, rc ? "failed" : "ok"));
42220   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
42221   return rc;
42222 }
42223 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
42224   if( pWal->exclusiveMode ) return;
42225   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
42226                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
42227   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
42228              walLockName(lockIdx), n));
42229 }
42230
42231 /*
42232 ** Compute a hash on a page number.  The resulting hash value must land
42233 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
42234 ** the hash to the next value in the event of a collision.
42235 */
42236 static int walHash(u32 iPage){
42237   assert( iPage>0 );
42238   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
42239   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
42240 }
42241 static int walNextHash(int iPriorHash){
42242   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
42243 }
42244
42245 /* 
42246 ** Return pointers to the hash table and page number array stored on
42247 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
42248 ** numbered starting from 0.
42249 **
42250 ** Set output variable *paHash to point to the start of the hash table
42251 ** in the wal-index file. Set *piZero to one less than the frame 
42252 ** number of the first frame indexed by this hash table. If a
42253 ** slot in the hash table is set to N, it refers to frame number 
42254 ** (*piZero+N) in the log.
42255 **
42256 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
42257 ** first frame indexed by the hash table, frame (*piZero+1).
42258 */
42259 static int walHashGet(
42260   Wal *pWal,                      /* WAL handle */
42261   int iHash,                      /* Find the iHash'th table */
42262   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
42263   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
42264   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
42265 ){
42266   int rc;                         /* Return code */
42267   volatile u32 *aPgno;
42268
42269   rc = walIndexPage(pWal, iHash, &aPgno);
42270   assert( rc==SQLITE_OK || iHash>0 );
42271
42272   if( rc==SQLITE_OK ){
42273     u32 iZero;
42274     volatile ht_slot *aHash;
42275
42276     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
42277     if( iHash==0 ){
42278       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
42279       iZero = 0;
42280     }else{
42281       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
42282     }
42283   
42284     *paPgno = &aPgno[-1];
42285     *paHash = aHash;
42286     *piZero = iZero;
42287   }
42288   return rc;
42289 }
42290
42291 /*
42292 ** Return the number of the wal-index page that contains the hash-table
42293 ** and page-number array that contain entries corresponding to WAL frame
42294 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
42295 ** are numbered starting from 0.
42296 */
42297 static int walFramePage(u32 iFrame){
42298   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
42299   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
42300        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
42301        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
42302        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
42303        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
42304   );
42305   return iHash;
42306 }
42307
42308 /*
42309 ** Return the page number associated with frame iFrame in this WAL.
42310 */
42311 static u32 walFramePgno(Wal *pWal, u32 iFrame){
42312   int iHash = walFramePage(iFrame);
42313   if( iHash==0 ){
42314     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
42315   }
42316   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
42317 }
42318
42319 /*
42320 ** Remove entries from the hash table that point to WAL slots greater
42321 ** than pWal->hdr.mxFrame.
42322 **
42323 ** This function is called whenever pWal->hdr.mxFrame is decreased due
42324 ** to a rollback or savepoint.
42325 **
42326 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
42327 ** updated.  Any later hash tables will be automatically cleared when
42328 ** pWal->hdr.mxFrame advances to the point where those hash tables are
42329 ** actually needed.
42330 */
42331 static void walCleanupHash(Wal *pWal){
42332   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
42333   volatile u32 *aPgno = 0;        /* Page number array for hash table */
42334   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
42335   int iLimit = 0;                 /* Zero values greater than this */
42336   int nByte;                      /* Number of bytes to zero in aPgno[] */
42337   int i;                          /* Used to iterate through aHash[] */
42338
42339   assert( pWal->writeLock );
42340   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
42341   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
42342   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
42343
42344   if( pWal->hdr.mxFrame==0 ) return;
42345
42346   /* Obtain pointers to the hash-table and page-number array containing 
42347   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
42348   ** that the page said hash-table and array reside on is already mapped.
42349   */
42350   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
42351   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
42352   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
42353
42354   /* Zero all hash-table entries that correspond to frame numbers greater
42355   ** than pWal->hdr.mxFrame.
42356   */
42357   iLimit = pWal->hdr.mxFrame - iZero;
42358   assert( iLimit>0 );
42359   for(i=0; i<HASHTABLE_NSLOT; i++){
42360     if( aHash[i]>iLimit ){
42361       aHash[i] = 0;
42362     }
42363   }
42364   
42365   /* Zero the entries in the aPgno array that correspond to frames with
42366   ** frame numbers greater than pWal->hdr.mxFrame. 
42367   */
42368   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
42369   memset((void *)&aPgno[iLimit+1], 0, nByte);
42370
42371 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
42372   /* Verify that the every entry in the mapping region is still reachable
42373   ** via the hash table even after the cleanup.
42374   */
42375   if( iLimit ){
42376     int i;           /* Loop counter */
42377     int iKey;        /* Hash key */
42378     for(i=1; i<=iLimit; i++){
42379       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
42380         if( aHash[iKey]==i ) break;
42381       }
42382       assert( aHash[iKey]==i );
42383     }
42384   }
42385 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
42386 }
42387
42388
42389 /*
42390 ** Set an entry in the wal-index that will map database page number
42391 ** pPage into WAL frame iFrame.
42392 */
42393 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
42394   int rc;                         /* Return code */
42395   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
42396   volatile u32 *aPgno = 0;        /* Page number array */
42397   volatile ht_slot *aHash = 0;    /* Hash table */
42398
42399   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
42400
42401   /* Assuming the wal-index file was successfully mapped, populate the
42402   ** page number array and hash table entry.
42403   */
42404   if( rc==SQLITE_OK ){
42405     int iKey;                     /* Hash table key */
42406     int idx;                      /* Value to write to hash-table slot */
42407     int nCollide;                 /* Number of hash collisions */
42408
42409     idx = iFrame - iZero;
42410     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
42411     
42412     /* If this is the first entry to be added to this hash-table, zero the
42413     ** entire hash table and aPgno[] array before proceding. 
42414     */
42415     if( idx==1 ){
42416       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
42417       memset((void*)&aPgno[1], 0, nByte);
42418     }
42419
42420     /* If the entry in aPgno[] is already set, then the previous writer
42421     ** must have exited unexpectedly in the middle of a transaction (after
42422     ** writing one or more dirty pages to the WAL to free up memory). 
42423     ** Remove the remnants of that writers uncommitted transaction from 
42424     ** the hash-table before writing any new entries.
42425     */
42426     if( aPgno[idx] ){
42427       walCleanupHash(pWal);
42428       assert( !aPgno[idx] );
42429     }
42430
42431     /* Write the aPgno[] array entry and the hash-table slot. */
42432     nCollide = idx;
42433     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
42434       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
42435     }
42436     aPgno[idx] = iPage;
42437     aHash[iKey] = (ht_slot)idx;
42438
42439 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
42440     /* Verify that the number of entries in the hash table exactly equals
42441     ** the number of entries in the mapping region.
42442     */
42443     {
42444       int i;           /* Loop counter */
42445       int nEntry = 0;  /* Number of entries in the hash table */
42446       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
42447       assert( nEntry==idx );
42448     }
42449
42450     /* Verify that the every entry in the mapping region is reachable
42451     ** via the hash table.  This turns out to be a really, really expensive
42452     ** thing to check, so only do this occasionally - not on every
42453     ** iteration.
42454     */
42455     if( (idx&0x3ff)==0 ){
42456       int i;           /* Loop counter */
42457       for(i=1; i<=idx; i++){
42458         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
42459           if( aHash[iKey]==i ) break;
42460         }
42461         assert( aHash[iKey]==i );
42462       }
42463     }
42464 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
42465   }
42466
42467
42468   return rc;
42469 }
42470
42471
42472 /*
42473 ** Recover the wal-index by reading the write-ahead log file. 
42474 **
42475 ** This routine first tries to establish an exclusive lock on the
42476 ** wal-index to prevent other threads/processes from doing anything
42477 ** with the WAL or wal-index while recovery is running.  The
42478 ** WAL_RECOVER_LOCK is also held so that other threads will know
42479 ** that this thread is running recovery.  If unable to establish
42480 ** the necessary locks, this routine returns SQLITE_BUSY.
42481 */
42482 static int walIndexRecover(Wal *pWal){
42483   int rc;                         /* Return Code */
42484   i64 nSize;                      /* Size of log file */
42485   u32 aFrameCksum[2] = {0, 0};
42486   int iLock;                      /* Lock offset to lock for checkpoint */
42487   int nLock;                      /* Number of locks to hold */
42488
42489   /* Obtain an exclusive lock on all byte in the locking range not already
42490   ** locked by the caller. The caller is guaranteed to have locked the
42491   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
42492   ** If successful, the same bytes that are locked here are unlocked before
42493   ** this function returns.
42494   */
42495   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
42496   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
42497   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
42498   assert( pWal->writeLock );
42499   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
42500   nLock = SQLITE_SHM_NLOCK - iLock;
42501   rc = walLockExclusive(pWal, iLock, nLock);
42502   if( rc ){
42503     return rc;
42504   }
42505   WALTRACE(("WAL%p: recovery begin...\n", pWal));
42506
42507   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
42508
42509   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
42510   if( rc!=SQLITE_OK ){
42511     goto recovery_error;
42512   }
42513
42514   if( nSize>WAL_HDRSIZE ){
42515     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
42516     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
42517     int szFrame;                  /* Number of bytes in buffer aFrame[] */
42518     u8 *aData;                    /* Pointer to data part of aFrame buffer */
42519     int iFrame;                   /* Index of last frame read */
42520     i64 iOffset;                  /* Next offset to read from log file */
42521     int szPage;                   /* Page size according to the log */
42522     u32 magic;                    /* Magic value read from WAL header */
42523     u32 version;                  /* Magic value read from WAL header */
42524
42525     /* Read in the WAL header. */
42526     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
42527     if( rc!=SQLITE_OK ){
42528       goto recovery_error;
42529     }
42530
42531     /* If the database page size is not a power of two, or is greater than
42532     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
42533     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
42534     ** WAL file.
42535     */
42536     magic = sqlite3Get4byte(&aBuf[0]);
42537     szPage = sqlite3Get4byte(&aBuf[8]);
42538     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
42539      || szPage&(szPage-1) 
42540      || szPage>SQLITE_MAX_PAGE_SIZE 
42541      || szPage<512 
42542     ){
42543       goto finished;
42544     }
42545     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
42546     pWal->szPage = szPage;
42547     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
42548     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
42549
42550     /* Verify that the WAL header checksum is correct */
42551     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
42552         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
42553     );
42554     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
42555      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
42556     ){
42557       goto finished;
42558     }
42559
42560     /* Verify that the version number on the WAL format is one that
42561     ** are able to understand */
42562     version = sqlite3Get4byte(&aBuf[4]);
42563     if( version!=WAL_MAX_VERSION ){
42564       rc = SQLITE_CANTOPEN_BKPT;
42565       goto finished;
42566     }
42567
42568     /* Malloc a buffer to read frames into. */
42569     szFrame = szPage + WAL_FRAME_HDRSIZE;
42570     aFrame = (u8 *)sqlite3_malloc(szFrame);
42571     if( !aFrame ){
42572       rc = SQLITE_NOMEM;
42573       goto recovery_error;
42574     }
42575     aData = &aFrame[WAL_FRAME_HDRSIZE];
42576
42577     /* Read all frames from the log file. */
42578     iFrame = 0;
42579     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
42580       u32 pgno;                   /* Database page number for frame */
42581       u32 nTruncate;              /* dbsize field from frame header */
42582       int isValid;                /* True if this frame is valid */
42583
42584       /* Read and decode the next log frame. */
42585       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
42586       if( rc!=SQLITE_OK ) break;
42587       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
42588       if( !isValid ) break;
42589       rc = walIndexAppend(pWal, ++iFrame, pgno);
42590       if( rc!=SQLITE_OK ) break;
42591
42592       /* If nTruncate is non-zero, this is a commit record. */
42593       if( nTruncate ){
42594         pWal->hdr.mxFrame = iFrame;
42595         pWal->hdr.nPage = nTruncate;
42596         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
42597         testcase( szPage<=32768 );
42598         testcase( szPage>=65536 );
42599         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
42600         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
42601       }
42602     }
42603
42604     sqlite3_free(aFrame);
42605   }
42606
42607 finished:
42608   if( rc==SQLITE_OK ){
42609     volatile WalCkptInfo *pInfo;
42610     int i;
42611     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
42612     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
42613     walIndexWriteHdr(pWal);
42614
42615     /* Reset the checkpoint-header. This is safe because this thread is 
42616     ** currently holding locks that exclude all other readers, writers and
42617     ** checkpointers.
42618     */
42619     pInfo = walCkptInfo(pWal);
42620     pInfo->nBackfill = 0;
42621     pInfo->aReadMark[0] = 0;
42622     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
42623
42624     /* If more than one frame was recovered from the log file, report an
42625     ** event via sqlite3_log(). This is to help with identifying performance
42626     ** problems caused by applications routinely shutting down without
42627     ** checkpointing the log file.
42628     */
42629     if( pWal->hdr.nPage ){
42630       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
42631           pWal->hdr.nPage, pWal->zWalName
42632       );
42633     }
42634   }
42635
42636 recovery_error:
42637   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
42638   walUnlockExclusive(pWal, iLock, nLock);
42639   return rc;
42640 }
42641
42642 /*
42643 ** Close an open wal-index.
42644 */
42645 static void walIndexClose(Wal *pWal, int isDelete){
42646   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
42647     int i;
42648     for(i=0; i<pWal->nWiData; i++){
42649       sqlite3_free((void *)pWal->apWiData[i]);
42650       pWal->apWiData[i] = 0;
42651     }
42652   }else{
42653     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
42654   }
42655 }
42656
42657 /* 
42658 ** Open a connection to the WAL file zWalName. The database file must 
42659 ** already be opened on connection pDbFd. The buffer that zWalName points
42660 ** to must remain valid for the lifetime of the returned Wal* handle.
42661 **
42662 ** A SHARED lock should be held on the database file when this function
42663 ** is called. The purpose of this SHARED lock is to prevent any other
42664 ** client from unlinking the WAL or wal-index file. If another process
42665 ** were to do this just after this client opened one of these files, the
42666 ** system would be badly broken.
42667 **
42668 ** If the log file is successfully opened, SQLITE_OK is returned and 
42669 ** *ppWal is set to point to a new WAL handle. If an error occurs,
42670 ** an SQLite error code is returned and *ppWal is left unmodified.
42671 */
42672 SQLITE_PRIVATE int sqlite3WalOpen(
42673   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
42674   sqlite3_file *pDbFd,            /* The open database file */
42675   const char *zWalName,           /* Name of the WAL file */
42676   int bNoShm,                     /* True to run in heap-memory mode */
42677   Wal **ppWal                     /* OUT: Allocated Wal handle */
42678 ){
42679   int rc;                         /* Return Code */
42680   Wal *pRet;                      /* Object to allocate and return */
42681   int flags;                      /* Flags passed to OsOpen() */
42682
42683   assert( zWalName && zWalName[0] );
42684   assert( pDbFd );
42685
42686   /* In the amalgamation, the os_unix.c and os_win.c source files come before
42687   ** this source file.  Verify that the #defines of the locking byte offsets
42688   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
42689   */
42690 #ifdef WIN_SHM_BASE
42691   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
42692 #endif
42693 #ifdef UNIX_SHM_BASE
42694   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
42695 #endif
42696
42697
42698   /* Allocate an instance of struct Wal to return. */
42699   *ppWal = 0;
42700   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
42701   if( !pRet ){
42702     return SQLITE_NOMEM;
42703   }
42704
42705   pRet->pVfs = pVfs;
42706   pRet->pWalFd = (sqlite3_file *)&pRet[1];
42707   pRet->pDbFd = pDbFd;
42708   pRet->readLock = -1;
42709   pRet->zWalName = zWalName;
42710   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
42711
42712   /* Open file handle on the write-ahead log file. */
42713   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
42714   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
42715   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
42716     pRet->readOnly = 1;
42717   }
42718
42719   if( rc!=SQLITE_OK ){
42720     walIndexClose(pRet, 0);
42721     sqlite3OsClose(pRet->pWalFd);
42722     sqlite3_free(pRet);
42723   }else{
42724     *ppWal = pRet;
42725     WALTRACE(("WAL%d: opened\n", pRet));
42726   }
42727   return rc;
42728 }
42729
42730 /*
42731 ** Find the smallest page number out of all pages held in the WAL that
42732 ** has not been returned by any prior invocation of this method on the
42733 ** same WalIterator object.   Write into *piFrame the frame index where
42734 ** that page was last written into the WAL.  Write into *piPage the page
42735 ** number.
42736 **
42737 ** Return 0 on success.  If there are no pages in the WAL with a page
42738 ** number larger than *piPage, then return 1.
42739 */
42740 static int walIteratorNext(
42741   WalIterator *p,               /* Iterator */
42742   u32 *piPage,                  /* OUT: The page number of the next page */
42743   u32 *piFrame                  /* OUT: Wal frame index of next page */
42744 ){
42745   u32 iMin;                     /* Result pgno must be greater than iMin */
42746   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
42747   int i;                        /* For looping through segments */
42748
42749   iMin = p->iPrior;
42750   assert( iMin<0xffffffff );
42751   for(i=p->nSegment-1; i>=0; i--){
42752     struct WalSegment *pSegment = &p->aSegment[i];
42753     while( pSegment->iNext<pSegment->nEntry ){
42754       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
42755       if( iPg>iMin ){
42756         if( iPg<iRet ){
42757           iRet = iPg;
42758           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
42759         }
42760         break;
42761       }
42762       pSegment->iNext++;
42763     }
42764   }
42765
42766   *piPage = p->iPrior = iRet;
42767   return (iRet==0xFFFFFFFF);
42768 }
42769
42770 /*
42771 ** This function merges two sorted lists into a single sorted list.
42772 */
42773 static void walMerge(
42774   u32 *aContent,                  /* Pages in wal */
42775   ht_slot *aLeft,                 /* IN: Left hand input list */
42776   int nLeft,                      /* IN: Elements in array *paLeft */
42777   ht_slot **paRight,              /* IN/OUT: Right hand input list */
42778   int *pnRight,                   /* IN/OUT: Elements in *paRight */
42779   ht_slot *aTmp                   /* Temporary buffer */
42780 ){
42781   int iLeft = 0;                  /* Current index in aLeft */
42782   int iRight = 0;                 /* Current index in aRight */
42783   int iOut = 0;                   /* Current index in output buffer */
42784   int nRight = *pnRight;
42785   ht_slot *aRight = *paRight;
42786
42787   assert( nLeft>0 && nRight>0 );
42788   while( iRight<nRight || iLeft<nLeft ){
42789     ht_slot logpage;
42790     Pgno dbpage;
42791
42792     if( (iLeft<nLeft) 
42793      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
42794     ){
42795       logpage = aLeft[iLeft++];
42796     }else{
42797       logpage = aRight[iRight++];
42798     }
42799     dbpage = aContent[logpage];
42800
42801     aTmp[iOut++] = logpage;
42802     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
42803
42804     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
42805     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
42806   }
42807
42808   *paRight = aLeft;
42809   *pnRight = iOut;
42810   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
42811 }
42812
42813 /*
42814 ** Sort the elements in list aList, removing any duplicates.
42815 */
42816 static void walMergesort(
42817   u32 *aContent,                  /* Pages in wal */
42818   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
42819   ht_slot *aList,                 /* IN/OUT: List to sort */
42820   int *pnList                     /* IN/OUT: Number of elements in aList[] */
42821 ){
42822   struct Sublist {
42823     int nList;                    /* Number of elements in aList */
42824     ht_slot *aList;               /* Pointer to sub-list content */
42825   };
42826
42827   const int nList = *pnList;      /* Size of input list */
42828   int nMerge = 0;                 /* Number of elements in list aMerge */
42829   ht_slot *aMerge = 0;            /* List to be merged */
42830   int iList;                      /* Index into input list */
42831   int iSub = 0;                   /* Index into aSub array */
42832   struct Sublist aSub[13];        /* Array of sub-lists */
42833
42834   memset(aSub, 0, sizeof(aSub));
42835   assert( nList<=HASHTABLE_NPAGE && nList>0 );
42836   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
42837
42838   for(iList=0; iList<nList; iList++){
42839     nMerge = 1;
42840     aMerge = &aList[iList];
42841     for(iSub=0; iList & (1<<iSub); iSub++){
42842       struct Sublist *p = &aSub[iSub];
42843       assert( p->aList && p->nList<=(1<<iSub) );
42844       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
42845       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
42846     }
42847     aSub[iSub].aList = aMerge;
42848     aSub[iSub].nList = nMerge;
42849   }
42850
42851   for(iSub++; iSub<ArraySize(aSub); iSub++){
42852     if( nList & (1<<iSub) ){
42853       struct Sublist *p = &aSub[iSub];
42854       assert( p->nList<=(1<<iSub) );
42855       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
42856       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
42857     }
42858   }
42859   assert( aMerge==aList );
42860   *pnList = nMerge;
42861
42862 #ifdef SQLITE_DEBUG
42863   {
42864     int i;
42865     for(i=1; i<*pnList; i++){
42866       assert( aContent[aList[i]] > aContent[aList[i-1]] );
42867     }
42868   }
42869 #endif
42870 }
42871
42872 /* 
42873 ** Free an iterator allocated by walIteratorInit().
42874 */
42875 static void walIteratorFree(WalIterator *p){
42876   sqlite3ScratchFree(p);
42877 }
42878
42879 /*
42880 ** Construct a WalInterator object that can be used to loop over all 
42881 ** pages in the WAL in ascending order. The caller must hold the checkpoint
42882 **
42883 ** On success, make *pp point to the newly allocated WalInterator object
42884 ** return SQLITE_OK. Otherwise, return an error code. If this routine
42885 ** returns an error, the value of *pp is undefined.
42886 **
42887 ** The calling routine should invoke walIteratorFree() to destroy the
42888 ** WalIterator object when it has finished with it.
42889 */
42890 static int walIteratorInit(Wal *pWal, WalIterator **pp){
42891   WalIterator *p;                 /* Return value */
42892   int nSegment;                   /* Number of segments to merge */
42893   u32 iLast;                      /* Last frame in log */
42894   int nByte;                      /* Number of bytes to allocate */
42895   int i;                          /* Iterator variable */
42896   ht_slot *aTmp;                  /* Temp space used by merge-sort */
42897   int rc = SQLITE_OK;             /* Return Code */
42898
42899   /* This routine only runs while holding the checkpoint lock. And
42900   ** it only runs if there is actually content in the log (mxFrame>0).
42901   */
42902   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
42903   iLast = pWal->hdr.mxFrame;
42904
42905   /* Allocate space for the WalIterator object. */
42906   nSegment = walFramePage(iLast) + 1;
42907   nByte = sizeof(WalIterator) 
42908         + (nSegment-1)*sizeof(struct WalSegment)
42909         + iLast*sizeof(ht_slot);
42910   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
42911   if( !p ){
42912     return SQLITE_NOMEM;
42913   }
42914   memset(p, 0, nByte);
42915   p->nSegment = nSegment;
42916
42917   /* Allocate temporary space used by the merge-sort routine. This block
42918   ** of memory will be freed before this function returns.
42919   */
42920   aTmp = (ht_slot *)sqlite3ScratchMalloc(
42921       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
42922   );
42923   if( !aTmp ){
42924     rc = SQLITE_NOMEM;
42925   }
42926
42927   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
42928     volatile ht_slot *aHash;
42929     u32 iZero;
42930     volatile u32 *aPgno;
42931
42932     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
42933     if( rc==SQLITE_OK ){
42934       int j;                      /* Counter variable */
42935       int nEntry;                 /* Number of entries in this segment */
42936       ht_slot *aIndex;            /* Sorted index for this segment */
42937
42938       aPgno++;
42939       if( (i+1)==nSegment ){
42940         nEntry = (int)(iLast - iZero);
42941       }else{
42942         nEntry = (int)((u32*)aHash - (u32*)aPgno);
42943       }
42944       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
42945       iZero++;
42946   
42947       for(j=0; j<nEntry; j++){
42948         aIndex[j] = (ht_slot)j;
42949       }
42950       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
42951       p->aSegment[i].iZero = iZero;
42952       p->aSegment[i].nEntry = nEntry;
42953       p->aSegment[i].aIndex = aIndex;
42954       p->aSegment[i].aPgno = (u32 *)aPgno;
42955     }
42956   }
42957   sqlite3ScratchFree(aTmp);
42958
42959   if( rc!=SQLITE_OK ){
42960     walIteratorFree(p);
42961   }
42962   *pp = p;
42963   return rc;
42964 }
42965
42966 /*
42967 ** Copy as much content as we can from the WAL back into the database file
42968 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
42969 **
42970 ** The amount of information copies from WAL to database might be limited
42971 ** by active readers.  This routine will never overwrite a database page
42972 ** that a concurrent reader might be using.
42973 **
42974 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
42975 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
42976 ** checkpoints are always run by a background thread or background 
42977 ** process, foreground threads will never block on a lengthy fsync call.
42978 **
42979 ** Fsync is called on the WAL before writing content out of the WAL and
42980 ** into the database.  This ensures that if the new content is persistent
42981 ** in the WAL and can be recovered following a power-loss or hard reset.
42982 **
42983 ** Fsync is also called on the database file if (and only if) the entire
42984 ** WAL content is copied into the database file.  This second fsync makes
42985 ** it safe to delete the WAL since the new content will persist in the
42986 ** database file.
42987 **
42988 ** This routine uses and updates the nBackfill field of the wal-index header.
42989 ** This is the only routine tha will increase the value of nBackfill.  
42990 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
42991 ** its value.)
42992 **
42993 ** The caller must be holding sufficient locks to ensure that no other
42994 ** checkpoint is running (in any other thread or process) at the same
42995 ** time.
42996 */
42997 static int walCheckpoint(
42998   Wal *pWal,                      /* Wal connection */
42999   int sync_flags,                 /* Flags for OsSync() (or 0) */
43000   int nBuf,                       /* Size of zBuf in bytes */
43001   u8 *zBuf                        /* Temporary buffer to use */
43002 ){
43003   int rc;                         /* Return code */
43004   int szPage;                     /* Database page-size */
43005   WalIterator *pIter = 0;         /* Wal iterator context */
43006   u32 iDbpage = 0;                /* Next database page to write */
43007   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
43008   u32 mxSafeFrame;                /* Max frame that can be backfilled */
43009   u32 mxPage;                     /* Max database page to write */
43010   int i;                          /* Loop counter */
43011   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
43012
43013   szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
43014   testcase( szPage<=32768 );
43015   testcase( szPage>=65536 );
43016   if( pWal->hdr.mxFrame==0 ) return SQLITE_OK;
43017
43018   /* Allocate the iterator */
43019   rc = walIteratorInit(pWal, &pIter);
43020   if( rc!=SQLITE_OK ){
43021     return rc;
43022   }
43023   assert( pIter );
43024
43025   /*** TODO:  Move this test out to the caller.  Make it an assert() here ***/
43026   if( szPage!=nBuf ){
43027     rc = SQLITE_CORRUPT_BKPT;
43028     goto walcheckpoint_out;
43029   }
43030
43031   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
43032   ** safe to write into the database.  Frames beyond mxSafeFrame might
43033   ** overwrite database pages that are in use by active readers and thus
43034   ** cannot be backfilled from the WAL.
43035   */
43036   mxSafeFrame = pWal->hdr.mxFrame;
43037   mxPage = pWal->hdr.nPage;
43038   pInfo = walCkptInfo(pWal);
43039   for(i=1; i<WAL_NREADER; i++){
43040     u32 y = pInfo->aReadMark[i];
43041     if( mxSafeFrame>=y ){
43042       assert( y<=pWal->hdr.mxFrame );
43043       rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
43044       if( rc==SQLITE_OK ){
43045         pInfo->aReadMark[i] = READMARK_NOT_USED;
43046         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
43047       }else if( rc==SQLITE_BUSY ){
43048         mxSafeFrame = y;
43049       }else{
43050         goto walcheckpoint_out;
43051       }
43052     }
43053   }
43054
43055   if( pInfo->nBackfill<mxSafeFrame
43056    && (rc = walLockExclusive(pWal, WAL_READ_LOCK(0), 1))==SQLITE_OK
43057   ){
43058     i64 nSize;                    /* Current size of database file */
43059     u32 nBackfill = pInfo->nBackfill;
43060
43061     /* Sync the WAL to disk */
43062     if( sync_flags ){
43063       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
43064     }
43065
43066     /* If the database file may grow as a result of this checkpoint, hint
43067     ** about the eventual size of the db file to the VFS layer. 
43068     */
43069     if( rc==SQLITE_OK ){
43070       i64 nReq = ((i64)mxPage * szPage);
43071       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
43072       if( rc==SQLITE_OK && nSize<nReq ){
43073         sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
43074       }
43075     }
43076
43077     /* Iterate through the contents of the WAL, copying data to the db file. */
43078     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
43079       i64 iOffset;
43080       assert( walFramePgno(pWal, iFrame)==iDbpage );
43081       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
43082       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
43083       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
43084       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
43085       if( rc!=SQLITE_OK ) break;
43086       iOffset = (iDbpage-1)*(i64)szPage;
43087       testcase( IS_BIG_INT(iOffset) );
43088       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
43089       if( rc!=SQLITE_OK ) break;
43090     }
43091
43092     /* If work was actually accomplished... */
43093     if( rc==SQLITE_OK ){
43094       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
43095         i64 szDb = pWal->hdr.nPage*(i64)szPage;
43096         testcase( IS_BIG_INT(szDb) );
43097         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
43098         if( rc==SQLITE_OK && sync_flags ){
43099           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
43100         }
43101       }
43102       if( rc==SQLITE_OK ){
43103         pInfo->nBackfill = mxSafeFrame;
43104       }
43105     }
43106
43107     /* Release the reader lock held while backfilling */
43108     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
43109   }else if( rc==SQLITE_BUSY ){
43110     /* Reset the return code so as not to report a checkpoint failure
43111     ** just because active readers prevent any backfill.
43112     */
43113     rc = SQLITE_OK;
43114   }
43115
43116  walcheckpoint_out:
43117   walIteratorFree(pIter);
43118   return rc;
43119 }
43120
43121 /*
43122 ** Close a connection to a log file.
43123 */
43124 SQLITE_PRIVATE int sqlite3WalClose(
43125   Wal *pWal,                      /* Wal to close */
43126   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
43127   int nBuf,
43128   u8 *zBuf                        /* Buffer of at least nBuf bytes */
43129 ){
43130   int rc = SQLITE_OK;
43131   if( pWal ){
43132     int isDelete = 0;             /* True to unlink wal and wal-index files */
43133
43134     /* If an EXCLUSIVE lock can be obtained on the database file (using the
43135     ** ordinary, rollback-mode locking methods, this guarantees that the
43136     ** connection associated with this log file is the only connection to
43137     ** the database. In this case checkpoint the database and unlink both
43138     ** the wal and wal-index files.
43139     **
43140     ** The EXCLUSIVE lock is not released before returning.
43141     */
43142     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
43143     if( rc==SQLITE_OK ){
43144       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
43145         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
43146       }
43147       rc = sqlite3WalCheckpoint(pWal, sync_flags, nBuf, zBuf);
43148       if( rc==SQLITE_OK ){
43149         isDelete = 1;
43150       }
43151     }
43152
43153     walIndexClose(pWal, isDelete);
43154     sqlite3OsClose(pWal->pWalFd);
43155     if( isDelete ){
43156       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
43157     }
43158     WALTRACE(("WAL%p: closed\n", pWal));
43159     sqlite3_free((void *)pWal->apWiData);
43160     sqlite3_free(pWal);
43161   }
43162   return rc;
43163 }
43164
43165 /*
43166 ** Try to read the wal-index header.  Return 0 on success and 1 if
43167 ** there is a problem.
43168 **
43169 ** The wal-index is in shared memory.  Another thread or process might
43170 ** be writing the header at the same time this procedure is trying to
43171 ** read it, which might result in inconsistency.  A dirty read is detected
43172 ** by verifying that both copies of the header are the same and also by
43173 ** a checksum on the header.
43174 **
43175 ** If and only if the read is consistent and the header is different from
43176 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
43177 ** and *pChanged is set to 1.
43178 **
43179 ** If the checksum cannot be verified return non-zero. If the header
43180 ** is read successfully and the checksum verified, return zero.
43181 */
43182 static int walIndexTryHdr(Wal *pWal, int *pChanged){
43183   u32 aCksum[2];                  /* Checksum on the header content */
43184   WalIndexHdr h1, h2;             /* Two copies of the header content */
43185   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
43186
43187   /* The first page of the wal-index must be mapped at this point. */
43188   assert( pWal->nWiData>0 && pWal->apWiData[0] );
43189
43190   /* Read the header. This might happen concurrently with a write to the
43191   ** same area of shared memory on a different CPU in a SMP,
43192   ** meaning it is possible that an inconsistent snapshot is read
43193   ** from the file. If this happens, return non-zero.
43194   **
43195   ** There are two copies of the header at the beginning of the wal-index.
43196   ** When reading, read [0] first then [1].  Writes are in the reverse order.
43197   ** Memory barriers are used to prevent the compiler or the hardware from
43198   ** reordering the reads and writes.
43199   */
43200   aHdr = walIndexHdr(pWal);
43201   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
43202   walShmBarrier(pWal);
43203   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
43204
43205   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
43206     return 1;   /* Dirty read */
43207   }  
43208   if( h1.isInit==0 ){
43209     return 1;   /* Malformed header - probably all zeros */
43210   }
43211   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
43212   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
43213     return 1;   /* Checksum does not match */
43214   }
43215
43216   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
43217     *pChanged = 1;
43218     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
43219     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
43220     testcase( pWal->szPage<=32768 );
43221     testcase( pWal->szPage>=65536 );
43222   }
43223
43224   /* The header was successfully read. Return zero. */
43225   return 0;
43226 }
43227
43228 /*
43229 ** Read the wal-index header from the wal-index and into pWal->hdr.
43230 ** If the wal-header appears to be corrupt, try to reconstruct the
43231 ** wal-index from the WAL before returning.
43232 **
43233 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
43234 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
43235 ** to 0.
43236 **
43237 ** If the wal-index header is successfully read, return SQLITE_OK. 
43238 ** Otherwise an SQLite error code.
43239 */
43240 static int walIndexReadHdr(Wal *pWal, int *pChanged){
43241   int rc;                         /* Return code */
43242   int badHdr;                     /* True if a header read failed */
43243   volatile u32 *page0;            /* Chunk of wal-index containing header */
43244
43245   /* Ensure that page 0 of the wal-index (the page that contains the 
43246   ** wal-index header) is mapped. Return early if an error occurs here.
43247   */
43248   assert( pChanged );
43249   rc = walIndexPage(pWal, 0, &page0);
43250   if( rc!=SQLITE_OK ){
43251     return rc;
43252   };
43253   assert( page0 || pWal->writeLock==0 );
43254
43255   /* If the first page of the wal-index has been mapped, try to read the
43256   ** wal-index header immediately, without holding any lock. This usually
43257   ** works, but may fail if the wal-index header is corrupt or currently 
43258   ** being modified by another thread or process.
43259   */
43260   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
43261
43262   /* If the first attempt failed, it might have been due to a race
43263   ** with a writer.  So get a WRITE lock and try again.
43264   */
43265   assert( badHdr==0 || pWal->writeLock==0 );
43266   if( badHdr && SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
43267     pWal->writeLock = 1;
43268     if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
43269       badHdr = walIndexTryHdr(pWal, pChanged);
43270       if( badHdr ){
43271         /* If the wal-index header is still malformed even while holding
43272         ** a WRITE lock, it can only mean that the header is corrupted and
43273         ** needs to be reconstructed.  So run recovery to do exactly that.
43274         */
43275         rc = walIndexRecover(pWal);
43276         *pChanged = 1;
43277       }
43278     }
43279     pWal->writeLock = 0;
43280     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43281   }
43282
43283   /* If the header is read successfully, check the version number to make
43284   ** sure the wal-index was not constructed with some future format that
43285   ** this version of SQLite cannot understand.
43286   */
43287   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
43288     rc = SQLITE_CANTOPEN_BKPT;
43289   }
43290
43291   return rc;
43292 }
43293
43294 /*
43295 ** This is the value that walTryBeginRead returns when it needs to
43296 ** be retried.
43297 */
43298 #define WAL_RETRY  (-1)
43299
43300 /*
43301 ** Attempt to start a read transaction.  This might fail due to a race or
43302 ** other transient condition.  When that happens, it returns WAL_RETRY to
43303 ** indicate to the caller that it is safe to retry immediately.
43304 **
43305 ** On success return SQLITE_OK.  On a permanent failure (such an
43306 ** I/O error or an SQLITE_BUSY because another process is running
43307 ** recovery) return a positive error code.
43308 **
43309 ** The useWal parameter is true to force the use of the WAL and disable
43310 ** the case where the WAL is bypassed because it has been completely
43311 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
43312 ** to make a copy of the wal-index header into pWal->hdr.  If the 
43313 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
43314 ** to the caller that the local paget cache is obsolete and needs to be 
43315 ** flushed.)  When useWal==1, the wal-index header is assumed to already
43316 ** be loaded and the pChanged parameter is unused.
43317 **
43318 ** The caller must set the cnt parameter to the number of prior calls to
43319 ** this routine during the current read attempt that returned WAL_RETRY.
43320 ** This routine will start taking more aggressive measures to clear the
43321 ** race conditions after multiple WAL_RETRY returns, and after an excessive
43322 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
43323 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
43324 ** and is not honoring the locking protocol.  There is a vanishingly small
43325 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
43326 ** bad luck when there is lots of contention for the wal-index, but that
43327 ** possibility is so small that it can be safely neglected, we believe.
43328 **
43329 ** On success, this routine obtains a read lock on 
43330 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
43331 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
43332 ** that means the Wal does not hold any read lock.  The reader must not
43333 ** access any database page that is modified by a WAL frame up to and
43334 ** including frame number aReadMark[pWal->readLock].  The reader will
43335 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
43336 ** Or if pWal->readLock==0, then the reader will ignore the WAL
43337 ** completely and get all content directly from the database file.
43338 ** If the useWal parameter is 1 then the WAL will never be ignored and
43339 ** this routine will always set pWal->readLock>0 on success.
43340 ** When the read transaction is completed, the caller must release the
43341 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
43342 **
43343 ** This routine uses the nBackfill and aReadMark[] fields of the header
43344 ** to select a particular WAL_READ_LOCK() that strives to let the
43345 ** checkpoint process do as much work as possible.  This routine might
43346 ** update values of the aReadMark[] array in the header, but if it does
43347 ** so it takes care to hold an exclusive lock on the corresponding
43348 ** WAL_READ_LOCK() while changing values.
43349 */
43350 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
43351   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
43352   u32 mxReadMark;                 /* Largest aReadMark[] value */
43353   int mxI;                        /* Index of largest aReadMark[] value */
43354   int i;                          /* Loop counter */
43355   int rc = SQLITE_OK;             /* Return code  */
43356
43357   assert( pWal->readLock<0 );     /* Not currently locked */
43358
43359   /* Take steps to avoid spinning forever if there is a protocol error. */
43360   if( cnt>5 ){
43361     if( cnt>100 ) return SQLITE_PROTOCOL;
43362     sqlite3OsSleep(pWal->pVfs, 1);
43363   }
43364
43365   if( !useWal ){
43366     rc = walIndexReadHdr(pWal, pChanged);
43367     if( rc==SQLITE_BUSY ){
43368       /* If there is not a recovery running in another thread or process
43369       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
43370       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
43371       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
43372       ** would be technically correct.  But the race is benign since with
43373       ** WAL_RETRY this routine will be called again and will probably be
43374       ** right on the second iteration.
43375       */
43376       if( pWal->apWiData[0]==0 ){
43377         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
43378         ** We assume this is a transient condition, so return WAL_RETRY. The
43379         ** xShmMap() implementation used by the default unix and win32 VFS 
43380         ** modules may return SQLITE_BUSY due to a race condition in the 
43381         ** code that determines whether or not the shared-memory region 
43382         ** must be zeroed before the requested page is returned.
43383         */
43384         rc = WAL_RETRY;
43385       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
43386         walUnlockShared(pWal, WAL_RECOVER_LOCK);
43387         rc = WAL_RETRY;
43388       }else if( rc==SQLITE_BUSY ){
43389         rc = SQLITE_BUSY_RECOVERY;
43390       }
43391     }
43392     if( rc!=SQLITE_OK ){
43393       return rc;
43394     }
43395   }
43396
43397   pInfo = walCkptInfo(pWal);
43398   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
43399     /* The WAL has been completely backfilled (or it is empty).
43400     ** and can be safely ignored.
43401     */
43402     rc = walLockShared(pWal, WAL_READ_LOCK(0));
43403     walShmBarrier(pWal);
43404     if( rc==SQLITE_OK ){
43405       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
43406         /* It is not safe to allow the reader to continue here if frames
43407         ** may have been appended to the log before READ_LOCK(0) was obtained.
43408         ** When holding READ_LOCK(0), the reader ignores the entire log file,
43409         ** which implies that the database file contains a trustworthy
43410         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
43411         ** happening, this is usually correct.
43412         **
43413         ** However, if frames have been appended to the log (or if the log 
43414         ** is wrapped and written for that matter) before the READ_LOCK(0)
43415         ** is obtained, that is not necessarily true. A checkpointer may
43416         ** have started to backfill the appended frames but crashed before
43417         ** it finished. Leaving a corrupt image in the database file.
43418         */
43419         walUnlockShared(pWal, WAL_READ_LOCK(0));
43420         return WAL_RETRY;
43421       }
43422       pWal->readLock = 0;
43423       return SQLITE_OK;
43424     }else if( rc!=SQLITE_BUSY ){
43425       return rc;
43426     }
43427   }
43428
43429   /* If we get this far, it means that the reader will want to use
43430   ** the WAL to get at content from recent commits.  The job now is
43431   ** to select one of the aReadMark[] entries that is closest to
43432   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
43433   */
43434   mxReadMark = 0;
43435   mxI = 0;
43436   for(i=1; i<WAL_NREADER; i++){
43437     u32 thisMark = pInfo->aReadMark[i];
43438     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
43439       assert( thisMark!=READMARK_NOT_USED );
43440       mxReadMark = thisMark;
43441       mxI = i;
43442     }
43443   }
43444   if( mxI==0 ){
43445     /* If we get here, it means that all of the aReadMark[] entries between
43446     ** 1 and WAL_NREADER-1 are zero.  Try to initialize aReadMark[1] to
43447     ** be mxFrame, then retry.
43448     */
43449     rc = walLockExclusive(pWal, WAL_READ_LOCK(1), 1);
43450     if( rc==SQLITE_OK ){
43451       pInfo->aReadMark[1] = pWal->hdr.mxFrame;
43452       walUnlockExclusive(pWal, WAL_READ_LOCK(1), 1);
43453       rc = WAL_RETRY;
43454     }else if( rc==SQLITE_BUSY ){
43455       rc = WAL_RETRY;
43456     }
43457     return rc;
43458   }else{
43459     if( mxReadMark < pWal->hdr.mxFrame ){
43460       for(i=1; i<WAL_NREADER; i++){
43461         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
43462         if( rc==SQLITE_OK ){
43463           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
43464           mxI = i;
43465           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
43466           break;
43467         }else if( rc!=SQLITE_BUSY ){
43468           return rc;
43469         }
43470       }
43471     }
43472
43473     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
43474     if( rc ){
43475       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
43476     }
43477     /* Now that the read-lock has been obtained, check that neither the
43478     ** value in the aReadMark[] array or the contents of the wal-index
43479     ** header have changed.
43480     **
43481     ** It is necessary to check that the wal-index header did not change
43482     ** between the time it was read and when the shared-lock was obtained
43483     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
43484     ** that the log file may have been wrapped by a writer, or that frames
43485     ** that occur later in the log than pWal->hdr.mxFrame may have been
43486     ** copied into the database by a checkpointer. If either of these things
43487     ** happened, then reading the database with the current value of
43488     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
43489     ** instead.
43490     **
43491     ** This does not guarantee that the copy of the wal-index header is up to
43492     ** date before proceeding. That would not be possible without somehow
43493     ** blocking writers. It only guarantees that a dangerous checkpoint or 
43494     ** log-wrap (either of which would require an exclusive lock on
43495     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
43496     */
43497     walShmBarrier(pWal);
43498     if( pInfo->aReadMark[mxI]!=mxReadMark
43499      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
43500     ){
43501       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
43502       return WAL_RETRY;
43503     }else{
43504       assert( mxReadMark<=pWal->hdr.mxFrame );
43505       pWal->readLock = (i16)mxI;
43506     }
43507   }
43508   return rc;
43509 }
43510
43511 /*
43512 ** Begin a read transaction on the database.
43513 **
43514 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
43515 ** it takes a snapshot of the state of the WAL and wal-index for the current
43516 ** instant in time.  The current thread will continue to use this snapshot.
43517 ** Other threads might append new content to the WAL and wal-index but
43518 ** that extra content is ignored by the current thread.
43519 **
43520 ** If the database contents have changes since the previous read
43521 ** transaction, then *pChanged is set to 1 before returning.  The
43522 ** Pager layer will use this to know that is cache is stale and
43523 ** needs to be flushed.
43524 */
43525 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
43526   int rc;                         /* Return code */
43527   int cnt = 0;                    /* Number of TryBeginRead attempts */
43528
43529   do{
43530     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
43531   }while( rc==WAL_RETRY );
43532   return rc;
43533 }
43534
43535 /*
43536 ** Finish with a read transaction.  All this does is release the
43537 ** read-lock.
43538 */
43539 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
43540   sqlite3WalEndWriteTransaction(pWal);
43541   if( pWal->readLock>=0 ){
43542     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
43543     pWal->readLock = -1;
43544   }
43545 }
43546
43547 /*
43548 ** Read a page from the WAL, if it is present in the WAL and if the 
43549 ** current read transaction is configured to use the WAL.  
43550 **
43551 ** The *pInWal is set to 1 if the requested page is in the WAL and
43552 ** has been loaded.  Or *pInWal is set to 0 if the page was not in 
43553 ** the WAL and needs to be read out of the database.
43554 */
43555 SQLITE_PRIVATE int sqlite3WalRead(
43556   Wal *pWal,                      /* WAL handle */
43557   Pgno pgno,                      /* Database page number to read data for */
43558   int *pInWal,                    /* OUT: True if data is read from WAL */
43559   int nOut,                       /* Size of buffer pOut in bytes */
43560   u8 *pOut                        /* Buffer to write page data to */
43561 ){
43562   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
43563   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
43564   int iHash;                      /* Used to loop through N hash tables */
43565
43566   /* This routine is only be called from within a read transaction. */
43567   assert( pWal->readLock>=0 || pWal->lockError );
43568
43569   /* If the "last page" field of the wal-index header snapshot is 0, then
43570   ** no data will be read from the wal under any circumstances. Return early
43571   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
43572   ** then the WAL is ignored by the reader so return early, as if the 
43573   ** WAL were empty.
43574   */
43575   if( iLast==0 || pWal->readLock==0 ){
43576     *pInWal = 0;
43577     return SQLITE_OK;
43578   }
43579
43580   /* Search the hash table or tables for an entry matching page number
43581   ** pgno. Each iteration of the following for() loop searches one
43582   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
43583   **
43584   ** This code might run concurrently to the code in walIndexAppend()
43585   ** that adds entries to the wal-index (and possibly to this hash 
43586   ** table). This means the value just read from the hash 
43587   ** slot (aHash[iKey]) may have been added before or after the 
43588   ** current read transaction was opened. Values added after the
43589   ** read transaction was opened may have been written incorrectly -
43590   ** i.e. these slots may contain garbage data. However, we assume
43591   ** that any slots written before the current read transaction was
43592   ** opened remain unmodified.
43593   **
43594   ** For the reasons above, the if(...) condition featured in the inner
43595   ** loop of the following block is more stringent that would be required 
43596   ** if we had exclusive access to the hash-table:
43597   **
43598   **   (aPgno[iFrame]==pgno): 
43599   **     This condition filters out normal hash-table collisions.
43600   **
43601   **   (iFrame<=iLast): 
43602   **     This condition filters out entries that were added to the hash
43603   **     table after the current read-transaction had started.
43604   */
43605   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
43606     volatile ht_slot *aHash;      /* Pointer to hash table */
43607     volatile u32 *aPgno;          /* Pointer to array of page numbers */
43608     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
43609     int iKey;                     /* Hash slot index */
43610     int nCollide;                 /* Number of hash collisions remaining */
43611     int rc;                       /* Error code */
43612
43613     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
43614     if( rc!=SQLITE_OK ){
43615       return rc;
43616     }
43617     nCollide = HASHTABLE_NSLOT;
43618     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
43619       u32 iFrame = aHash[iKey] + iZero;
43620       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
43621         assert( iFrame>iRead );
43622         iRead = iFrame;
43623       }
43624       if( (nCollide--)==0 ){
43625         return SQLITE_CORRUPT_BKPT;
43626       }
43627     }
43628   }
43629
43630 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
43631   /* If expensive assert() statements are available, do a linear search
43632   ** of the wal-index file content. Make sure the results agree with the
43633   ** result obtained using the hash indexes above.  */
43634   {
43635     u32 iRead2 = 0;
43636     u32 iTest;
43637     for(iTest=iLast; iTest>0; iTest--){
43638       if( walFramePgno(pWal, iTest)==pgno ){
43639         iRead2 = iTest;
43640         break;
43641       }
43642     }
43643     assert( iRead==iRead2 );
43644   }
43645 #endif
43646
43647   /* If iRead is non-zero, then it is the log frame number that contains the
43648   ** required page. Read and return data from the log file.
43649   */
43650   if( iRead ){
43651     int sz;
43652     i64 iOffset;
43653     sz = pWal->hdr.szPage;
43654     sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
43655     testcase( sz<=32768 );
43656     testcase( sz>=65536 );
43657     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
43658     *pInWal = 1;
43659     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43660     return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
43661   }
43662
43663   *pInWal = 0;
43664   return SQLITE_OK;
43665 }
43666
43667
43668 /* 
43669 ** Return the size of the database in pages (or zero, if unknown).
43670 */
43671 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
43672   if( pWal && ALWAYS(pWal->readLock>=0) ){
43673     return pWal->hdr.nPage;
43674   }
43675   return 0;
43676 }
43677
43678
43679 /* 
43680 ** This function starts a write transaction on the WAL.
43681 **
43682 ** A read transaction must have already been started by a prior call
43683 ** to sqlite3WalBeginReadTransaction().
43684 **
43685 ** If another thread or process has written into the database since
43686 ** the read transaction was started, then it is not possible for this
43687 ** thread to write as doing so would cause a fork.  So this routine
43688 ** returns SQLITE_BUSY in that case and no write transaction is started.
43689 **
43690 ** There can only be a single writer active at a time.
43691 */
43692 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
43693   int rc;
43694
43695   /* Cannot start a write transaction without first holding a read
43696   ** transaction. */
43697   assert( pWal->readLock>=0 );
43698
43699   if( pWal->readOnly ){
43700     return SQLITE_READONLY;
43701   }
43702
43703   /* Only one writer allowed at a time.  Get the write lock.  Return
43704   ** SQLITE_BUSY if unable.
43705   */
43706   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
43707   if( rc ){
43708     return rc;
43709   }
43710   pWal->writeLock = 1;
43711
43712   /* If another connection has written to the database file since the
43713   ** time the read transaction on this connection was started, then
43714   ** the write is disallowed.
43715   */
43716   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
43717     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43718     pWal->writeLock = 0;
43719     rc = SQLITE_BUSY;
43720   }
43721
43722   return rc;
43723 }
43724
43725 /*
43726 ** End a write transaction.  The commit has already been done.  This
43727 ** routine merely releases the lock.
43728 */
43729 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
43730   if( pWal->writeLock ){
43731     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
43732     pWal->writeLock = 0;
43733   }
43734   return SQLITE_OK;
43735 }
43736
43737 /*
43738 ** If any data has been written (but not committed) to the log file, this
43739 ** function moves the write-pointer back to the start of the transaction.
43740 **
43741 ** Additionally, the callback function is invoked for each frame written
43742 ** to the WAL since the start of the transaction. If the callback returns
43743 ** other than SQLITE_OK, it is not invoked again and the error code is
43744 ** returned to the caller.
43745 **
43746 ** Otherwise, if the callback function does not return an error, this
43747 ** function returns SQLITE_OK.
43748 */
43749 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
43750   int rc = SQLITE_OK;
43751   if( ALWAYS(pWal->writeLock) ){
43752     Pgno iMax = pWal->hdr.mxFrame;
43753     Pgno iFrame;
43754   
43755     /* Restore the clients cache of the wal-index header to the state it
43756     ** was in before the client began writing to the database. 
43757     */
43758     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
43759
43760     for(iFrame=pWal->hdr.mxFrame+1; 
43761         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
43762         iFrame++
43763     ){
43764       /* This call cannot fail. Unless the page for which the page number
43765       ** is passed as the second argument is (a) in the cache and 
43766       ** (b) has an outstanding reference, then xUndo is either a no-op
43767       ** (if (a) is false) or simply expels the page from the cache (if (b)
43768       ** is false).
43769       **
43770       ** If the upper layer is doing a rollback, it is guaranteed that there
43771       ** are no outstanding references to any page other than page 1. And
43772       ** page 1 is never written to the log until the transaction is
43773       ** committed. As a result, the call to xUndo may not fail.
43774       */
43775       assert( walFramePgno(pWal, iFrame)!=1 );
43776       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
43777     }
43778     walCleanupHash(pWal);
43779   }
43780   assert( rc==SQLITE_OK );
43781   return rc;
43782 }
43783
43784 /* 
43785 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
43786 ** values. This function populates the array with values required to 
43787 ** "rollback" the write position of the WAL handle back to the current 
43788 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
43789 */
43790 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
43791   assert( pWal->writeLock );
43792   aWalData[0] = pWal->hdr.mxFrame;
43793   aWalData[1] = pWal->hdr.aFrameCksum[0];
43794   aWalData[2] = pWal->hdr.aFrameCksum[1];
43795   aWalData[3] = pWal->nCkpt;
43796 }
43797
43798 /* 
43799 ** Move the write position of the WAL back to the point identified by
43800 ** the values in the aWalData[] array. aWalData must point to an array
43801 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
43802 ** by a call to WalSavepoint().
43803 */
43804 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
43805   int rc = SQLITE_OK;
43806
43807   assert( pWal->writeLock );
43808   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
43809
43810   if( aWalData[3]!=pWal->nCkpt ){
43811     /* This savepoint was opened immediately after the write-transaction
43812     ** was started. Right after that, the writer decided to wrap around
43813     ** to the start of the log. Update the savepoint values to match.
43814     */
43815     aWalData[0] = 0;
43816     aWalData[3] = pWal->nCkpt;
43817   }
43818
43819   if( aWalData[0]<pWal->hdr.mxFrame ){
43820     pWal->hdr.mxFrame = aWalData[0];
43821     pWal->hdr.aFrameCksum[0] = aWalData[1];
43822     pWal->hdr.aFrameCksum[1] = aWalData[2];
43823     walCleanupHash(pWal);
43824   }
43825
43826   return rc;
43827 }
43828
43829 /*
43830 ** This function is called just before writing a set of frames to the log
43831 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
43832 ** to the current log file, it is possible to overwrite the start of the
43833 ** existing log file with the new frames (i.e. "reset" the log). If so,
43834 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
43835 ** unchanged.
43836 **
43837 ** SQLITE_OK is returned if no error is encountered (regardless of whether
43838 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
43839 ** if an error occurs.
43840 */
43841 static int walRestartLog(Wal *pWal){
43842   int rc = SQLITE_OK;
43843   int cnt;
43844
43845   if( pWal->readLock==0 ){
43846     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
43847     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
43848     if( pInfo->nBackfill>0 ){
43849       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
43850       if( rc==SQLITE_OK ){
43851         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
43852         ** readers are currently using the WAL), then the transactions
43853         ** frames will overwrite the start of the existing log. Update the
43854         ** wal-index header to reflect this.
43855         **
43856         ** In theory it would be Ok to update the cache of the header only
43857         ** at this point. But updating the actual wal-index header is also
43858         ** safe and means there is no special case for sqlite3WalUndo()
43859         ** to handle if this transaction is rolled back.
43860         */
43861         int i;                    /* Loop counter */
43862         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
43863         pWal->nCkpt++;
43864         pWal->hdr.mxFrame = 0;
43865         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
43866         sqlite3_randomness(4, &aSalt[1]);
43867         walIndexWriteHdr(pWal);
43868         pInfo->nBackfill = 0;
43869         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
43870         assert( pInfo->aReadMark[0]==0 );
43871         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
43872       }else if( rc!=SQLITE_BUSY ){
43873         return rc;
43874       }
43875     }
43876     walUnlockShared(pWal, WAL_READ_LOCK(0));
43877     pWal->readLock = -1;
43878     cnt = 0;
43879     do{
43880       int notUsed;
43881       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
43882     }while( rc==WAL_RETRY );
43883   }
43884   return rc;
43885 }
43886
43887 /* 
43888 ** Write a set of frames to the log. The caller must hold the write-lock
43889 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
43890 */
43891 SQLITE_PRIVATE int sqlite3WalFrames(
43892   Wal *pWal,                      /* Wal handle to write to */
43893   int szPage,                     /* Database page-size in bytes */
43894   PgHdr *pList,                   /* List of dirty pages to write */
43895   Pgno nTruncate,                 /* Database size after this commit */
43896   int isCommit,                   /* True if this is a commit */
43897   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
43898 ){
43899   int rc;                         /* Used to catch return codes */
43900   u32 iFrame;                     /* Next frame address */
43901   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
43902   PgHdr *p;                       /* Iterator to run through pList with. */
43903   PgHdr *pLast = 0;               /* Last frame in list */
43904   int nLast = 0;                  /* Number of extra copies of last page */
43905
43906   assert( pList );
43907   assert( pWal->writeLock );
43908
43909 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
43910   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
43911     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
43912               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
43913   }
43914 #endif
43915
43916   /* See if it is possible to write these frames into the start of the
43917   ** log file, instead of appending to it at pWal->hdr.mxFrame.
43918   */
43919   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
43920     return rc;
43921   }
43922
43923   /* If this is the first frame written into the log, write the WAL
43924   ** header to the start of the WAL file. See comments at the top of
43925   ** this source file for a description of the WAL header format.
43926   */
43927   iFrame = pWal->hdr.mxFrame;
43928   if( iFrame==0 ){
43929     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
43930     u32 aCksum[2];                /* Checksum for wal-header */
43931
43932     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
43933     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
43934     sqlite3Put4byte(&aWalHdr[8], szPage);
43935     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
43936     sqlite3_randomness(8, pWal->hdr.aSalt);
43937     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
43938     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
43939     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
43940     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
43941     
43942     pWal->szPage = szPage;
43943     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
43944     pWal->hdr.aFrameCksum[0] = aCksum[0];
43945     pWal->hdr.aFrameCksum[1] = aCksum[1];
43946
43947     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
43948     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
43949     if( rc!=SQLITE_OK ){
43950       return rc;
43951     }
43952   }
43953   assert( (int)pWal->szPage==szPage );
43954
43955   /* Write the log file. */
43956   for(p=pList; p; p=p->pDirty){
43957     u32 nDbsize;                  /* Db-size field for frame header */
43958     i64 iOffset;                  /* Write offset in log file */
43959     void *pData;
43960    
43961     iOffset = walFrameOffset(++iFrame, szPage);
43962     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
43963     
43964     /* Populate and write the frame header */
43965     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
43966 #if defined(SQLITE_HAS_CODEC)
43967     if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
43968 #else
43969     pData = p->pData;
43970 #endif
43971     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
43972     rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
43973     if( rc!=SQLITE_OK ){
43974       return rc;
43975     }
43976
43977     /* Write the page data */
43978     rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
43979     if( rc!=SQLITE_OK ){
43980       return rc;
43981     }
43982     pLast = p;
43983   }
43984
43985   /* Sync the log file if the 'isSync' flag was specified. */
43986   if( sync_flags ){
43987     i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
43988     i64 iOffset = walFrameOffset(iFrame+1, szPage);
43989
43990     assert( isCommit );
43991     assert( iSegment>0 );
43992
43993     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
43994     while( iOffset<iSegment ){
43995       void *pData;
43996 #if defined(SQLITE_HAS_CODEC)
43997       if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
43998 #else
43999       pData = pLast->pData;
44000 #endif
44001       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
44002       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
44003       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
44004       if( rc!=SQLITE_OK ){
44005         return rc;
44006       }
44007       iOffset += WAL_FRAME_HDRSIZE;
44008       rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset); 
44009       if( rc!=SQLITE_OK ){
44010         return rc;
44011       }
44012       nLast++;
44013       iOffset += szPage;
44014     }
44015
44016     rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
44017   }
44018
44019   /* Append data to the wal-index. It is not necessary to lock the 
44020   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
44021   ** guarantees that there are no other writers, and no data that may
44022   ** be in use by existing readers is being overwritten.
44023   */
44024   iFrame = pWal->hdr.mxFrame;
44025   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
44026     iFrame++;
44027     rc = walIndexAppend(pWal, iFrame, p->pgno);
44028   }
44029   while( nLast>0 && rc==SQLITE_OK ){
44030     iFrame++;
44031     nLast--;
44032     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
44033   }
44034
44035   if( rc==SQLITE_OK ){
44036     /* Update the private copy of the header. */
44037     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
44038     testcase( szPage<=32768 );
44039     testcase( szPage>=65536 );
44040     pWal->hdr.mxFrame = iFrame;
44041     if( isCommit ){
44042       pWal->hdr.iChange++;
44043       pWal->hdr.nPage = nTruncate;
44044     }
44045     /* If this is a commit, update the wal-index header too. */
44046     if( isCommit ){
44047       walIndexWriteHdr(pWal);
44048       pWal->iCallback = iFrame;
44049     }
44050   }
44051
44052   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
44053   return rc;
44054 }
44055
44056 /* 
44057 ** This routine is called to implement sqlite3_wal_checkpoint() and
44058 ** related interfaces.
44059 **
44060 ** Obtain a CHECKPOINT lock and then backfill as much information as
44061 ** we can from WAL into the database.
44062 */
44063 SQLITE_PRIVATE int sqlite3WalCheckpoint(
44064   Wal *pWal,                      /* Wal connection */
44065   int sync_flags,                 /* Flags to sync db file with (or 0) */
44066   int nBuf,                       /* Size of temporary buffer */
44067   u8 *zBuf                        /* Temporary buffer to use */
44068 ){
44069   int rc;                         /* Return code */
44070   int isChanged = 0;              /* True if a new wal-index header is loaded */
44071
44072   assert( pWal->ckptLock==0 );
44073
44074   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
44075   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
44076   if( rc ){
44077     /* Usually this is SQLITE_BUSY meaning that another thread or process
44078     ** is already running a checkpoint, or maybe a recovery.  But it might
44079     ** also be SQLITE_IOERR. */
44080     return rc;
44081   }
44082   pWal->ckptLock = 1;
44083
44084   /* Copy data from the log to the database file. */
44085   rc = walIndexReadHdr(pWal, &isChanged);
44086   if( rc==SQLITE_OK ){
44087     rc = walCheckpoint(pWal, sync_flags, nBuf, zBuf);
44088   }
44089   if( isChanged ){
44090     /* If a new wal-index header was loaded before the checkpoint was 
44091     ** performed, then the pager-cache associated with pWal is now
44092     ** out of date. So zero the cached wal-index header to ensure that
44093     ** next time the pager opens a snapshot on this database it knows that
44094     ** the cache needs to be reset.
44095     */
44096     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
44097   }
44098
44099   /* Release the locks. */
44100   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
44101   pWal->ckptLock = 0;
44102   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
44103   return rc;
44104 }
44105
44106 /* Return the value to pass to a sqlite3_wal_hook callback, the
44107 ** number of frames in the WAL at the point of the last commit since
44108 ** sqlite3WalCallback() was called.  If no commits have occurred since
44109 ** the last call, then return 0.
44110 */
44111 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
44112   u32 ret = 0;
44113   if( pWal ){
44114     ret = pWal->iCallback;
44115     pWal->iCallback = 0;
44116   }
44117   return (int)ret;
44118 }
44119
44120 /*
44121 ** This function is called to change the WAL subsystem into or out
44122 ** of locking_mode=EXCLUSIVE.
44123 **
44124 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
44125 ** into locking_mode=NORMAL.  This means that we must acquire a lock
44126 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
44127 ** or if the acquisition of the lock fails, then return 0.  If the
44128 ** transition out of exclusive-mode is successful, return 1.  This
44129 ** operation must occur while the pager is still holding the exclusive
44130 ** lock on the main database file.
44131 **
44132 ** If op is one, then change from locking_mode=NORMAL into 
44133 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
44134 ** be released.  Return 1 if the transition is made and 0 if the
44135 ** WAL is already in exclusive-locking mode - meaning that this
44136 ** routine is a no-op.  The pager must already hold the exclusive lock
44137 ** on the main database file before invoking this operation.
44138 **
44139 ** If op is negative, then do a dry-run of the op==1 case but do
44140 ** not actually change anything. The pager uses this to see if it
44141 ** should acquire the database exclusive lock prior to invoking
44142 ** the op==1 case.
44143 */
44144 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
44145   int rc;
44146   assert( pWal->writeLock==0 );
44147   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
44148
44149   /* pWal->readLock is usually set, but might be -1 if there was a 
44150   ** prior error while attempting to acquire are read-lock. This cannot 
44151   ** happen if the connection is actually in exclusive mode (as no xShmLock
44152   ** locks are taken in this case). Nor should the pager attempt to
44153   ** upgrade to exclusive-mode following such an error.
44154   */
44155   assert( pWal->readLock>=0 || pWal->lockError );
44156   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
44157
44158   if( op==0 ){
44159     if( pWal->exclusiveMode ){
44160       pWal->exclusiveMode = 0;
44161       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
44162         pWal->exclusiveMode = 1;
44163       }
44164       rc = pWal->exclusiveMode==0;
44165     }else{
44166       /* Already in locking_mode=NORMAL */
44167       rc = 0;
44168     }
44169   }else if( op>0 ){
44170     assert( pWal->exclusiveMode==0 );
44171     assert( pWal->readLock>=0 );
44172     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
44173     pWal->exclusiveMode = 1;
44174     rc = 1;
44175   }else{
44176     rc = pWal->exclusiveMode==0;
44177   }
44178   return rc;
44179 }
44180
44181 /* 
44182 ** Return true if the argument is non-NULL and the WAL module is using
44183 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
44184 ** WAL module is using shared-memory, return false. 
44185 */
44186 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
44187   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
44188 }
44189
44190 #endif /* #ifndef SQLITE_OMIT_WAL */
44191
44192 /************** End of wal.c *************************************************/
44193 /************** Begin file btmutex.c *****************************************/
44194 /*
44195 ** 2007 August 27
44196 **
44197 ** The author disclaims copyright to this source code.  In place of
44198 ** a legal notice, here is a blessing:
44199 **
44200 **    May you do good and not evil.
44201 **    May you find forgiveness for yourself and forgive others.
44202 **    May you share freely, never taking more than you give.
44203 **
44204 *************************************************************************
44205 **
44206 ** This file contains code used to implement mutexes on Btree objects.
44207 ** This code really belongs in btree.c.  But btree.c is getting too
44208 ** big and we want to break it down some.  This packaged seemed like
44209 ** a good breakout.
44210 */
44211 /************** Include btreeInt.h in the middle of btmutex.c ****************/
44212 /************** Begin file btreeInt.h ****************************************/
44213 /*
44214 ** 2004 April 6
44215 **
44216 ** The author disclaims copyright to this source code.  In place of
44217 ** a legal notice, here is a blessing:
44218 **
44219 **    May you do good and not evil.
44220 **    May you find forgiveness for yourself and forgive others.
44221 **    May you share freely, never taking more than you give.
44222 **
44223 *************************************************************************
44224 ** This file implements a external (disk-based) database using BTrees.
44225 ** For a detailed discussion of BTrees, refer to
44226 **
44227 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
44228 **     "Sorting And Searching", pages 473-480. Addison-Wesley
44229 **     Publishing Company, Reading, Massachusetts.
44230 **
44231 ** The basic idea is that each page of the file contains N database
44232 ** entries and N+1 pointers to subpages.
44233 **
44234 **   ----------------------------------------------------------------
44235 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
44236 **   ----------------------------------------------------------------
44237 **
44238 ** All of the keys on the page that Ptr(0) points to have values less
44239 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
44240 ** values greater than Key(0) and less than Key(1).  All of the keys
44241 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
44242 ** so forth.
44243 **
44244 ** Finding a particular key requires reading O(log(M)) pages from the 
44245 ** disk where M is the number of entries in the tree.
44246 **
44247 ** In this implementation, a single file can hold one or more separate 
44248 ** BTrees.  Each BTree is identified by the index of its root page.  The
44249 ** key and data for any entry are combined to form the "payload".  A
44250 ** fixed amount of payload can be carried directly on the database
44251 ** page.  If the payload is larger than the preset amount then surplus
44252 ** bytes are stored on overflow pages.  The payload for an entry
44253 ** and the preceding pointer are combined to form a "Cell".  Each 
44254 ** page has a small header which contains the Ptr(N) pointer and other
44255 ** information such as the size of key and data.
44256 **
44257 ** FORMAT DETAILS
44258 **
44259 ** The file is divided into pages.  The first page is called page 1,
44260 ** the second is page 2, and so forth.  A page number of zero indicates
44261 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
44262 ** Each page can be either a btree page, a freelist page, an overflow
44263 ** page, or a pointer-map page.
44264 **
44265 ** The first page is always a btree page.  The first 100 bytes of the first
44266 ** page contain a special header (the "file header") that describes the file.
44267 ** The format of the file header is as follows:
44268 **
44269 **   OFFSET   SIZE    DESCRIPTION
44270 **      0      16     Header string: "SQLite format 3\000"
44271 **     16       2     Page size in bytes.  
44272 **     18       1     File format write version
44273 **     19       1     File format read version
44274 **     20       1     Bytes of unused space at the end of each page
44275 **     21       1     Max embedded payload fraction
44276 **     22       1     Min embedded payload fraction
44277 **     23       1     Min leaf payload fraction
44278 **     24       4     File change counter
44279 **     28       4     Reserved for future use
44280 **     32       4     First freelist page
44281 **     36       4     Number of freelist pages in the file
44282 **     40      60     15 4-byte meta values passed to higher layers
44283 **
44284 **     40       4     Schema cookie
44285 **     44       4     File format of schema layer
44286 **     48       4     Size of page cache
44287 **     52       4     Largest root-page (auto/incr_vacuum)
44288 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
44289 **     60       4     User version
44290 **     64       4     Incremental vacuum mode
44291 **     68       4     unused
44292 **     72       4     unused
44293 **     76       4     unused
44294 **
44295 ** All of the integer values are big-endian (most significant byte first).
44296 **
44297 ** The file change counter is incremented when the database is changed
44298 ** This counter allows other processes to know when the file has changed
44299 ** and thus when they need to flush their cache.
44300 **
44301 ** The max embedded payload fraction is the amount of the total usable
44302 ** space in a page that can be consumed by a single cell for standard
44303 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
44304 ** is to limit the maximum cell size so that at least 4 cells will fit
44305 ** on one page.  Thus the default max embedded payload fraction is 64.
44306 **
44307 ** If the payload for a cell is larger than the max payload, then extra
44308 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
44309 ** as many bytes as possible are moved into the overflow pages without letting
44310 ** the cell size drop below the min embedded payload fraction.
44311 **
44312 ** The min leaf payload fraction is like the min embedded payload fraction
44313 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
44314 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
44315 ** not specified in the header.
44316 **
44317 ** Each btree pages is divided into three sections:  The header, the
44318 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
44319 ** file header that occurs before the page header.
44320 **
44321 **      |----------------|
44322 **      | file header    |   100 bytes.  Page 1 only.
44323 **      |----------------|
44324 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
44325 **      |----------------|
44326 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
44327 **      | array          |   |  Grows downward
44328 **      |                |   v
44329 **      |----------------|
44330 **      | unallocated    |
44331 **      | space          |
44332 **      |----------------|   ^  Grows upwards
44333 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
44334 **      | area           |   |  and free space fragments.
44335 **      |----------------|
44336 **
44337 ** The page headers looks like this:
44338 **
44339 **   OFFSET   SIZE     DESCRIPTION
44340 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
44341 **      1       2      byte offset to the first freeblock
44342 **      3       2      number of cells on this page
44343 **      5       2      first byte of the cell content area
44344 **      7       1      number of fragmented free bytes
44345 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
44346 **
44347 ** The flags define the format of this btree page.  The leaf flag means that
44348 ** this page has no children.  The zerodata flag means that this page carries
44349 ** only keys and no data.  The intkey flag means that the key is a integer
44350 ** which is stored in the key size entry of the cell header rather than in
44351 ** the payload area.
44352 **
44353 ** The cell pointer array begins on the first byte after the page header.
44354 ** The cell pointer array contains zero or more 2-byte numbers which are
44355 ** offsets from the beginning of the page to the cell content in the cell
44356 ** content area.  The cell pointers occur in sorted order.  The system strives
44357 ** to keep free space after the last cell pointer so that new cells can
44358 ** be easily added without having to defragment the page.
44359 **
44360 ** Cell content is stored at the very end of the page and grows toward the
44361 ** beginning of the page.
44362 **
44363 ** Unused space within the cell content area is collected into a linked list of
44364 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
44365 ** to the first freeblock is given in the header.  Freeblocks occur in
44366 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
44367 ** any group of 3 or fewer unused bytes in the cell content area cannot
44368 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
44369 ** a fragment.  The total number of bytes in all fragments is recorded.
44370 ** in the page header at offset 7.
44371 **
44372 **    SIZE    DESCRIPTION
44373 **      2     Byte offset of the next freeblock
44374 **      2     Bytes in this freeblock
44375 **
44376 ** Cells are of variable length.  Cells are stored in the cell content area at
44377 ** the end of the page.  Pointers to the cells are in the cell pointer array
44378 ** that immediately follows the page header.  Cells is not necessarily
44379 ** contiguous or in order, but cell pointers are contiguous and in order.
44380 **
44381 ** Cell content makes use of variable length integers.  A variable
44382 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
44383 ** byte are used.  The integer consists of all bytes that have bit 8 set and
44384 ** the first byte with bit 8 clear.  The most significant byte of the integer
44385 ** appears first.  A variable-length integer may not be more than 9 bytes long.
44386 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
44387 ** allows a 64-bit integer to be encoded in 9 bytes.
44388 **
44389 **    0x00                      becomes  0x00000000
44390 **    0x7f                      becomes  0x0000007f
44391 **    0x81 0x00                 becomes  0x00000080
44392 **    0x82 0x00                 becomes  0x00000100
44393 **    0x80 0x7f                 becomes  0x0000007f
44394 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
44395 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
44396 **
44397 ** Variable length integers are used for rowids and to hold the number of
44398 ** bytes of key and data in a btree cell.
44399 **
44400 ** The content of a cell looks like this:
44401 **
44402 **    SIZE    DESCRIPTION
44403 **      4     Page number of the left child. Omitted if leaf flag is set.
44404 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
44405 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
44406 **      *     Payload
44407 **      4     First page of the overflow chain.  Omitted if no overflow
44408 **
44409 ** Overflow pages form a linked list.  Each page except the last is completely
44410 ** filled with data (pagesize - 4 bytes).  The last page can have as little
44411 ** as 1 byte of data.
44412 **
44413 **    SIZE    DESCRIPTION
44414 **      4     Page number of next overflow page
44415 **      *     Data
44416 **
44417 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
44418 ** file header points to the first in a linked list of trunk page.  Each trunk
44419 ** page points to multiple leaf pages.  The content of a leaf page is
44420 ** unspecified.  A trunk page looks like this:
44421 **
44422 **    SIZE    DESCRIPTION
44423 **      4     Page number of next trunk page
44424 **      4     Number of leaf pointers on this page
44425 **      *     zero or more pages numbers of leaves
44426 */
44427
44428
44429 /* The following value is the maximum cell size assuming a maximum page
44430 ** size give above.
44431 */
44432 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
44433
44434 /* The maximum number of cells on a single page of the database.  This
44435 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
44436 ** plus 2 bytes for the index to the cell in the page header).  Such
44437 ** small cells will be rare, but they are possible.
44438 */
44439 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
44440
44441 /* Forward declarations */
44442 typedef struct MemPage MemPage;
44443 typedef struct BtLock BtLock;
44444
44445 /*
44446 ** This is a magic string that appears at the beginning of every
44447 ** SQLite database in order to identify the file as a real database.
44448 **
44449 ** You can change this value at compile-time by specifying a
44450 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
44451 ** header must be exactly 16 bytes including the zero-terminator so
44452 ** the string itself should be 15 characters long.  If you change
44453 ** the header, then your custom library will not be able to read 
44454 ** databases generated by the standard tools and the standard tools
44455 ** will not be able to read databases created by your custom library.
44456 */
44457 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
44458 #  define SQLITE_FILE_HEADER "SQLite format 3"
44459 #endif
44460
44461 /*
44462 ** Page type flags.  An ORed combination of these flags appear as the
44463 ** first byte of on-disk image of every BTree page.
44464 */
44465 #define PTF_INTKEY    0x01
44466 #define PTF_ZERODATA  0x02
44467 #define PTF_LEAFDATA  0x04
44468 #define PTF_LEAF      0x08
44469
44470 /*
44471 ** As each page of the file is loaded into memory, an instance of the following
44472 ** structure is appended and initialized to zero.  This structure stores
44473 ** information about the page that is decoded from the raw file page.
44474 **
44475 ** The pParent field points back to the parent page.  This allows us to
44476 ** walk up the BTree from any leaf to the root.  Care must be taken to
44477 ** unref() the parent page pointer when this page is no longer referenced.
44478 ** The pageDestructor() routine handles that chore.
44479 **
44480 ** Access to all fields of this structure is controlled by the mutex
44481 ** stored in MemPage.pBt->mutex.
44482 */
44483 struct MemPage {
44484   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
44485   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
44486   u8 intKey;           /* True if intkey flag is set */
44487   u8 leaf;             /* True if leaf flag is set */
44488   u8 hasData;          /* True if this page stores data */
44489   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
44490   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
44491   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
44492   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
44493   u16 cellOffset;      /* Index in aData of first cell pointer */
44494   u16 nFree;           /* Number of free bytes on the page */
44495   u16 nCell;           /* Number of cells on this page, local and ovfl */
44496   u16 maskPage;        /* Mask for page offset */
44497   struct _OvflCell {   /* Cells that will not fit on aData[] */
44498     u8 *pCell;          /* Pointers to the body of the overflow cell */
44499     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
44500   } aOvfl[5];
44501   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
44502   u8 *aData;           /* Pointer to disk image of the page data */
44503   DbPage *pDbPage;     /* Pager page handle */
44504   Pgno pgno;           /* Page number for this page */
44505 };
44506
44507 /*
44508 ** The in-memory image of a disk page has the auxiliary information appended
44509 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
44510 ** that extra information.
44511 */
44512 #define EXTRA_SIZE sizeof(MemPage)
44513
44514 /*
44515 ** A linked list of the following structures is stored at BtShared.pLock.
44516 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
44517 ** is opened on the table with root page BtShared.iTable. Locks are removed
44518 ** from this list when a transaction is committed or rolled back, or when
44519 ** a btree handle is closed.
44520 */
44521 struct BtLock {
44522   Btree *pBtree;        /* Btree handle holding this lock */
44523   Pgno iTable;          /* Root page of table */
44524   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
44525   BtLock *pNext;        /* Next in BtShared.pLock list */
44526 };
44527
44528 /* Candidate values for BtLock.eLock */
44529 #define READ_LOCK     1
44530 #define WRITE_LOCK    2
44531
44532 /* A Btree handle
44533 **
44534 ** A database connection contains a pointer to an instance of
44535 ** this object for every database file that it has open.  This structure
44536 ** is opaque to the database connection.  The database connection cannot
44537 ** see the internals of this structure and only deals with pointers to
44538 ** this structure.
44539 **
44540 ** For some database files, the same underlying database cache might be 
44541 ** shared between multiple connections.  In that case, each connection
44542 ** has it own instance of this object.  But each instance of this object
44543 ** points to the same BtShared object.  The database cache and the
44544 ** schema associated with the database file are all contained within
44545 ** the BtShared object.
44546 **
44547 ** All fields in this structure are accessed under sqlite3.mutex.
44548 ** The pBt pointer itself may not be changed while there exists cursors 
44549 ** in the referenced BtShared that point back to this Btree since those
44550 ** cursors have to do go through this Btree to find their BtShared and
44551 ** they often do so without holding sqlite3.mutex.
44552 */
44553 struct Btree {
44554   sqlite3 *db;       /* The database connection holding this btree */
44555   BtShared *pBt;     /* Sharable content of this btree */
44556   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
44557   u8 sharable;       /* True if we can share pBt with another db */
44558   u8 locked;         /* True if db currently has pBt locked */
44559   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
44560   int nBackup;       /* Number of backup operations reading this btree */
44561   Btree *pNext;      /* List of other sharable Btrees from the same db */
44562   Btree *pPrev;      /* Back pointer of the same list */
44563 #ifndef SQLITE_OMIT_SHARED_CACHE
44564   BtLock lock;       /* Object used to lock page 1 */
44565 #endif
44566 };
44567
44568 /*
44569 ** Btree.inTrans may take one of the following values.
44570 **
44571 ** If the shared-data extension is enabled, there may be multiple users
44572 ** of the Btree structure. At most one of these may open a write transaction,
44573 ** but any number may have active read transactions.
44574 */
44575 #define TRANS_NONE  0
44576 #define TRANS_READ  1
44577 #define TRANS_WRITE 2
44578
44579 /*
44580 ** An instance of this object represents a single database file.
44581 ** 
44582 ** A single database file can be in use as the same time by two
44583 ** or more database connections.  When two or more connections are
44584 ** sharing the same database file, each connection has it own
44585 ** private Btree object for the file and each of those Btrees points
44586 ** to this one BtShared object.  BtShared.nRef is the number of
44587 ** connections currently sharing this database file.
44588 **
44589 ** Fields in this structure are accessed under the BtShared.mutex
44590 ** mutex, except for nRef and pNext which are accessed under the
44591 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
44592 ** may not be modified once it is initially set as long as nRef>0.
44593 ** The pSchema field may be set once under BtShared.mutex and
44594 ** thereafter is unchanged as long as nRef>0.
44595 **
44596 ** isPending:
44597 **
44598 **   If a BtShared client fails to obtain a write-lock on a database
44599 **   table (because there exists one or more read-locks on the table),
44600 **   the shared-cache enters 'pending-lock' state and isPending is
44601 **   set to true.
44602 **
44603 **   The shared-cache leaves the 'pending lock' state when either of
44604 **   the following occur:
44605 **
44606 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
44607 **     2) The number of locks held by other connections drops to zero.
44608 **
44609 **   while in the 'pending-lock' state, no connection may start a new
44610 **   transaction.
44611 **
44612 **   This feature is included to help prevent writer-starvation.
44613 */
44614 struct BtShared {
44615   Pager *pPager;        /* The page cache */
44616   sqlite3 *db;          /* Database connection currently using this Btree */
44617   BtCursor *pCursor;    /* A list of all open cursors */
44618   MemPage *pPage1;      /* First page of the database */
44619   u8 readOnly;          /* True if the underlying file is readonly */
44620   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
44621   u8 secureDelete;      /* True if secure_delete is enabled */
44622   u8 initiallyEmpty;    /* Database is empty at start of transaction */
44623   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
44624 #ifndef SQLITE_OMIT_AUTOVACUUM
44625   u8 autoVacuum;        /* True if auto-vacuum is enabled */
44626   u8 incrVacuum;        /* True if incr-vacuum is enabled */
44627 #endif
44628   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
44629   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
44630   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
44631   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
44632   u8 inTransaction;     /* Transaction state */
44633   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
44634   u32 pageSize;         /* Total number of bytes on a page */
44635   u32 usableSize;       /* Number of usable bytes on each page */
44636   int nTransaction;     /* Number of open transactions (read + write) */
44637   u32 nPage;            /* Number of pages in the database */
44638   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
44639   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
44640   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
44641   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
44642 #ifndef SQLITE_OMIT_SHARED_CACHE
44643   int nRef;             /* Number of references to this structure */
44644   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
44645   BtLock *pLock;        /* List of locks held on this shared-btree struct */
44646   Btree *pWriter;       /* Btree with currently open write transaction */
44647   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
44648   u8 isPending;         /* If waiting for read-locks to clear */
44649 #endif
44650   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
44651 };
44652
44653 /*
44654 ** An instance of the following structure is used to hold information
44655 ** about a cell.  The parseCellPtr() function fills in this structure
44656 ** based on information extract from the raw disk page.
44657 */
44658 typedef struct CellInfo CellInfo;
44659 struct CellInfo {
44660   u8 *pCell;     /* Pointer to the start of cell content */
44661   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
44662   u32 nData;     /* Number of bytes of data */
44663   u32 nPayload;  /* Total amount of payload */
44664   u16 nHeader;   /* Size of the cell content header in bytes */
44665   u16 nLocal;    /* Amount of payload held locally */
44666   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
44667   u16 nSize;     /* Size of the cell content on the main b-tree page */
44668 };
44669
44670 /*
44671 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
44672 ** this will be declared corrupt. This value is calculated based on a
44673 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
44674 ** root-node and 3 for all other internal nodes.
44675 **
44676 ** If a tree that appears to be taller than this is encountered, it is
44677 ** assumed that the database is corrupt.
44678 */
44679 #define BTCURSOR_MAX_DEPTH 20
44680
44681 /*
44682 ** A cursor is a pointer to a particular entry within a particular
44683 ** b-tree within a database file.
44684 **
44685 ** The entry is identified by its MemPage and the index in
44686 ** MemPage.aCell[] of the entry.
44687 **
44688 ** A single database file can shared by two more database connections,
44689 ** but cursors cannot be shared.  Each cursor is associated with a
44690 ** particular database connection identified BtCursor.pBtree.db.
44691 **
44692 ** Fields in this structure are accessed under the BtShared.mutex
44693 ** found at self->pBt->mutex. 
44694 */
44695 struct BtCursor {
44696   Btree *pBtree;            /* The Btree to which this cursor belongs */
44697   BtShared *pBt;            /* The BtShared this cursor points to */
44698   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
44699   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
44700   Pgno pgnoRoot;            /* The root page of this tree */
44701   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
44702   CellInfo info;            /* A parse of the cell we are pointing at */
44703   u8 wrFlag;                /* True if writable */
44704   u8 atLast;                /* Cursor pointing to the last entry */
44705   u8 validNKey;             /* True if info.nKey is valid */
44706   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
44707   void *pKey;      /* Saved key that was cursor's last known position */
44708   i64 nKey;        /* Size of pKey, or last integer key */
44709   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
44710 #ifndef SQLITE_OMIT_INCRBLOB
44711   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
44712   Pgno *aOverflow;          /* Cache of overflow page locations */
44713 #endif
44714   i16 iPage;                            /* Index of current page in apPage */
44715   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
44716   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
44717 };
44718
44719 /*
44720 ** Potential values for BtCursor.eState.
44721 **
44722 ** CURSOR_VALID:
44723 **   Cursor points to a valid entry. getPayload() etc. may be called.
44724 **
44725 ** CURSOR_INVALID:
44726 **   Cursor does not point to a valid entry. This can happen (for example) 
44727 **   because the table is empty or because BtreeCursorFirst() has not been
44728 **   called.
44729 **
44730 ** CURSOR_REQUIRESEEK:
44731 **   The table that this cursor was opened on still exists, but has been 
44732 **   modified since the cursor was last used. The cursor position is saved
44733 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
44734 **   this state, restoreCursorPosition() can be called to attempt to
44735 **   seek the cursor to the saved position.
44736 **
44737 ** CURSOR_FAULT:
44738 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
44739 **   on a different connection that shares the BtShared cache with this
44740 **   cursor.  The error has left the cache in an inconsistent state.
44741 **   Do nothing else with this cursor.  Any attempt to use the cursor
44742 **   should return the error code stored in BtCursor.skip
44743 */
44744 #define CURSOR_INVALID           0
44745 #define CURSOR_VALID             1
44746 #define CURSOR_REQUIRESEEK       2
44747 #define CURSOR_FAULT             3
44748
44749 /* 
44750 ** The database page the PENDING_BYTE occupies. This page is never used.
44751 */
44752 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
44753
44754 /*
44755 ** These macros define the location of the pointer-map entry for a 
44756 ** database page. The first argument to each is the number of usable
44757 ** bytes on each page of the database (often 1024). The second is the
44758 ** page number to look up in the pointer map.
44759 **
44760 ** PTRMAP_PAGENO returns the database page number of the pointer-map
44761 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
44762 ** the offset of the requested map entry.
44763 **
44764 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
44765 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
44766 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
44767 ** this test.
44768 */
44769 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
44770 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
44771 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
44772
44773 /*
44774 ** The pointer map is a lookup table that identifies the parent page for
44775 ** each child page in the database file.  The parent page is the page that
44776 ** contains a pointer to the child.  Every page in the database contains
44777 ** 0 or 1 parent pages.  (In this context 'database page' refers
44778 ** to any page that is not part of the pointer map itself.)  Each pointer map
44779 ** entry consists of a single byte 'type' and a 4 byte parent page number.
44780 ** The PTRMAP_XXX identifiers below are the valid types.
44781 **
44782 ** The purpose of the pointer map is to facility moving pages from one
44783 ** position in the file to another as part of autovacuum.  When a page
44784 ** is moved, the pointer in its parent must be updated to point to the
44785 ** new location.  The pointer map is used to locate the parent page quickly.
44786 **
44787 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
44788 **                  used in this case.
44789 **
44790 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
44791 **                  is not used in this case.
44792 **
44793 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
44794 **                   overflow pages. The page number identifies the page that
44795 **                   contains the cell with a pointer to this overflow page.
44796 **
44797 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
44798 **                   overflow pages. The page-number identifies the previous
44799 **                   page in the overflow page list.
44800 **
44801 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
44802 **               identifies the parent page in the btree.
44803 */
44804 #define PTRMAP_ROOTPAGE 1
44805 #define PTRMAP_FREEPAGE 2
44806 #define PTRMAP_OVERFLOW1 3
44807 #define PTRMAP_OVERFLOW2 4
44808 #define PTRMAP_BTREE 5
44809
44810 /* A bunch of assert() statements to check the transaction state variables
44811 ** of handle p (type Btree*) are internally consistent.
44812 */
44813 #define btreeIntegrity(p) \
44814   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
44815   assert( p->pBt->inTransaction>=p->inTrans ); 
44816
44817
44818 /*
44819 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
44820 ** if the database supports auto-vacuum or not. Because it is used
44821 ** within an expression that is an argument to another macro 
44822 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
44823 ** So, this macro is defined instead.
44824 */
44825 #ifndef SQLITE_OMIT_AUTOVACUUM
44826 #define ISAUTOVACUUM (pBt->autoVacuum)
44827 #else
44828 #define ISAUTOVACUUM 0
44829 #endif
44830
44831
44832 /*
44833 ** This structure is passed around through all the sanity checking routines
44834 ** in order to keep track of some global state information.
44835 */
44836 typedef struct IntegrityCk IntegrityCk;
44837 struct IntegrityCk {
44838   BtShared *pBt;    /* The tree being checked out */
44839   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
44840   Pgno nPage;       /* Number of pages in the database */
44841   int *anRef;       /* Number of times each page is referenced */
44842   int mxErr;        /* Stop accumulating errors when this reaches zero */
44843   int nErr;         /* Number of messages written to zErrMsg so far */
44844   int mallocFailed; /* A memory allocation error has occurred */
44845   StrAccum errMsg;  /* Accumulate the error message text here */
44846 };
44847
44848 /*
44849 ** Read or write a two- and four-byte big-endian integer values.
44850 */
44851 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
44852 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
44853 #define get4byte sqlite3Get4byte
44854 #define put4byte sqlite3Put4byte
44855
44856 /************** End of btreeInt.h ********************************************/
44857 /************** Continuing where we left off in btmutex.c ********************/
44858 #ifndef SQLITE_OMIT_SHARED_CACHE
44859 #if SQLITE_THREADSAFE
44860
44861 /*
44862 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
44863 ** set BtShared.db to the database handle associated with p and the
44864 ** p->locked boolean to true.
44865 */
44866 static void lockBtreeMutex(Btree *p){
44867   assert( p->locked==0 );
44868   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
44869   assert( sqlite3_mutex_held(p->db->mutex) );
44870
44871   sqlite3_mutex_enter(p->pBt->mutex);
44872   p->pBt->db = p->db;
44873   p->locked = 1;
44874 }
44875
44876 /*
44877 ** Release the BtShared mutex associated with B-Tree handle p and
44878 ** clear the p->locked boolean.
44879 */
44880 static void unlockBtreeMutex(Btree *p){
44881   assert( p->locked==1 );
44882   assert( sqlite3_mutex_held(p->pBt->mutex) );
44883   assert( sqlite3_mutex_held(p->db->mutex) );
44884   assert( p->db==p->pBt->db );
44885
44886   sqlite3_mutex_leave(p->pBt->mutex);
44887   p->locked = 0;
44888 }
44889
44890 /*
44891 ** Enter a mutex on the given BTree object.
44892 **
44893 ** If the object is not sharable, then no mutex is ever required
44894 ** and this routine is a no-op.  The underlying mutex is non-recursive.
44895 ** But we keep a reference count in Btree.wantToLock so the behavior
44896 ** of this interface is recursive.
44897 **
44898 ** To avoid deadlocks, multiple Btrees are locked in the same order
44899 ** by all database connections.  The p->pNext is a list of other
44900 ** Btrees belonging to the same database connection as the p Btree
44901 ** which need to be locked after p.  If we cannot get a lock on
44902 ** p, then first unlock all of the others on p->pNext, then wait
44903 ** for the lock to become available on p, then relock all of the
44904 ** subsequent Btrees that desire a lock.
44905 */
44906 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
44907   Btree *pLater;
44908
44909   /* Some basic sanity checking on the Btree.  The list of Btrees
44910   ** connected by pNext and pPrev should be in sorted order by
44911   ** Btree.pBt value. All elements of the list should belong to
44912   ** the same connection. Only shared Btrees are on the list. */
44913   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
44914   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
44915   assert( p->pNext==0 || p->pNext->db==p->db );
44916   assert( p->pPrev==0 || p->pPrev->db==p->db );
44917   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
44918
44919   /* Check for locking consistency */
44920   assert( !p->locked || p->wantToLock>0 );
44921   assert( p->sharable || p->wantToLock==0 );
44922
44923   /* We should already hold a lock on the database connection */
44924   assert( sqlite3_mutex_held(p->db->mutex) );
44925
44926   /* Unless the database is sharable and unlocked, then BtShared.db
44927   ** should already be set correctly. */
44928   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
44929
44930   if( !p->sharable ) return;
44931   p->wantToLock++;
44932   if( p->locked ) return;
44933
44934   /* In most cases, we should be able to acquire the lock we
44935   ** want without having to go throught the ascending lock
44936   ** procedure that follows.  Just be sure not to block.
44937   */
44938   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
44939     p->pBt->db = p->db;
44940     p->locked = 1;
44941     return;
44942   }
44943
44944   /* To avoid deadlock, first release all locks with a larger
44945   ** BtShared address.  Then acquire our lock.  Then reacquire
44946   ** the other BtShared locks that we used to hold in ascending
44947   ** order.
44948   */
44949   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
44950     assert( pLater->sharable );
44951     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
44952     assert( !pLater->locked || pLater->wantToLock>0 );
44953     if( pLater->locked ){
44954       unlockBtreeMutex(pLater);
44955     }
44956   }
44957   lockBtreeMutex(p);
44958   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
44959     if( pLater->wantToLock ){
44960       lockBtreeMutex(pLater);
44961     }
44962   }
44963 }
44964
44965 /*
44966 ** Exit the recursive mutex on a Btree.
44967 */
44968 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
44969   if( p->sharable ){
44970     assert( p->wantToLock>0 );
44971     p->wantToLock--;
44972     if( p->wantToLock==0 ){
44973       unlockBtreeMutex(p);
44974     }
44975   }
44976 }
44977
44978 #ifndef NDEBUG
44979 /*
44980 ** Return true if the BtShared mutex is held on the btree, or if the
44981 ** B-Tree is not marked as sharable.
44982 **
44983 ** This routine is used only from within assert() statements.
44984 */
44985 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
44986   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
44987   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
44988   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
44989   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
44990
44991   return (p->sharable==0 || p->locked);
44992 }
44993 #endif
44994
44995
44996 #ifndef SQLITE_OMIT_INCRBLOB
44997 /*
44998 ** Enter and leave a mutex on a Btree given a cursor owned by that
44999 ** Btree.  These entry points are used by incremental I/O and can be
45000 ** omitted if that module is not used.
45001 */
45002 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
45003   sqlite3BtreeEnter(pCur->pBtree);
45004 }
45005 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
45006   sqlite3BtreeLeave(pCur->pBtree);
45007 }
45008 #endif /* SQLITE_OMIT_INCRBLOB */
45009
45010
45011 /*
45012 ** Enter the mutex on every Btree associated with a database
45013 ** connection.  This is needed (for example) prior to parsing
45014 ** a statement since we will be comparing table and column names
45015 ** against all schemas and we do not want those schemas being
45016 ** reset out from under us.
45017 **
45018 ** There is a corresponding leave-all procedures.
45019 **
45020 ** Enter the mutexes in accending order by BtShared pointer address
45021 ** to avoid the possibility of deadlock when two threads with
45022 ** two or more btrees in common both try to lock all their btrees
45023 ** at the same instant.
45024 */
45025 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
45026   int i;
45027   Btree *p, *pLater;
45028   assert( sqlite3_mutex_held(db->mutex) );
45029   for(i=0; i<db->nDb; i++){
45030     p = db->aDb[i].pBt;
45031     assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
45032     if( p && p->sharable ){
45033       p->wantToLock++;
45034       if( !p->locked ){
45035         assert( p->wantToLock==1 );
45036         while( p->pPrev ) p = p->pPrev;
45037         /* Reason for ALWAYS:  There must be at least on unlocked Btree in
45038         ** the chain.  Otherwise the !p->locked test above would have failed */
45039         while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
45040         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
45041           if( pLater->locked ){
45042             unlockBtreeMutex(pLater);
45043           }
45044         }
45045         while( p ){
45046           lockBtreeMutex(p);
45047           p = p->pNext;
45048         }
45049       }
45050     }
45051   }
45052 }
45053 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
45054   int i;
45055   Btree *p;
45056   assert( sqlite3_mutex_held(db->mutex) );
45057   for(i=0; i<db->nDb; i++){
45058     p = db->aDb[i].pBt;
45059     if( p && p->sharable ){
45060       assert( p->wantToLock>0 );
45061       p->wantToLock--;
45062       if( p->wantToLock==0 ){
45063         unlockBtreeMutex(p);
45064       }
45065     }
45066   }
45067 }
45068
45069 #ifndef NDEBUG
45070 /*
45071 ** Return true if the current thread holds the database connection
45072 ** mutex and all required BtShared mutexes.
45073 **
45074 ** This routine is used inside assert() statements only.
45075 */
45076 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
45077   int i;
45078   if( !sqlite3_mutex_held(db->mutex) ){
45079     return 0;
45080   }
45081   for(i=0; i<db->nDb; i++){
45082     Btree *p;
45083     p = db->aDb[i].pBt;
45084     if( p && p->sharable &&
45085          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
45086       return 0;
45087     }
45088   }
45089   return 1;
45090 }
45091 #endif /* NDEBUG */
45092
45093 /*
45094 ** Add a new Btree pointer to a BtreeMutexArray. 
45095 ** if the pointer can possibly be shared with
45096 ** another database connection.
45097 **
45098 ** The pointers are kept in sorted order by pBtree->pBt.  That
45099 ** way when we go to enter all the mutexes, we can enter them
45100 ** in order without every having to backup and retry and without
45101 ** worrying about deadlock.
45102 **
45103 ** The number of shared btrees will always be small (usually 0 or 1)
45104 ** so an insertion sort is an adequate algorithm here.
45105 */
45106 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
45107   int i, j;
45108   BtShared *pBt;
45109   if( pBtree==0 || pBtree->sharable==0 ) return;
45110 #ifndef NDEBUG
45111   {
45112     for(i=0; i<pArray->nMutex; i++){
45113       assert( pArray->aBtree[i]!=pBtree );
45114     }
45115   }
45116 #endif
45117   assert( pArray->nMutex>=0 );
45118   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
45119   pBt = pBtree->pBt;
45120   for(i=0; i<pArray->nMutex; i++){
45121     assert( pArray->aBtree[i]!=pBtree );
45122     if( pArray->aBtree[i]->pBt>pBt ){
45123       for(j=pArray->nMutex; j>i; j--){
45124         pArray->aBtree[j] = pArray->aBtree[j-1];
45125       }
45126       pArray->aBtree[i] = pBtree;
45127       pArray->nMutex++;
45128       return;
45129     }
45130   }
45131   pArray->aBtree[pArray->nMutex++] = pBtree;
45132 }
45133
45134 /*
45135 ** Enter the mutex of every btree in the array.  This routine is
45136 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
45137 ** exited at the end of the same function.
45138 */
45139 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
45140   int i;
45141   for(i=0; i<pArray->nMutex; i++){
45142     Btree *p = pArray->aBtree[i];
45143     /* Some basic sanity checking */
45144     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
45145     assert( !p->locked || p->wantToLock>0 );
45146
45147     /* We should already hold a lock on the database connection */
45148     assert( sqlite3_mutex_held(p->db->mutex) );
45149
45150     /* The Btree is sharable because only sharable Btrees are entered
45151     ** into the array in the first place. */
45152     assert( p->sharable );
45153
45154     p->wantToLock++;
45155     if( !p->locked ){
45156       lockBtreeMutex(p);
45157     }
45158   }
45159 }
45160
45161 /*
45162 ** Leave the mutex of every btree in the group.
45163 */
45164 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
45165   int i;
45166   for(i=0; i<pArray->nMutex; i++){
45167     Btree *p = pArray->aBtree[i];
45168     /* Some basic sanity checking */
45169     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
45170     assert( p->locked );
45171     assert( p->wantToLock>0 );
45172
45173     /* We should already hold a lock on the database connection */
45174     assert( sqlite3_mutex_held(p->db->mutex) );
45175
45176     p->wantToLock--;
45177     if( p->wantToLock==0 ){
45178       unlockBtreeMutex(p);
45179     }
45180   }
45181 }
45182
45183 #else
45184 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
45185   p->pBt->db = p->db;
45186 }
45187 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
45188   int i;
45189   for(i=0; i<db->nDb; i++){
45190     Btree *p = db->aDb[i].pBt;
45191     if( p ){
45192       p->pBt->db = p->db;
45193     }
45194   }
45195 }
45196 #endif /* if SQLITE_THREADSAFE */
45197 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
45198
45199 /************** End of btmutex.c *********************************************/
45200 /************** Begin file btree.c *******************************************/
45201 /*
45202 ** 2004 April 6
45203 **
45204 ** The author disclaims copyright to this source code.  In place of
45205 ** a legal notice, here is a blessing:
45206 **
45207 **    May you do good and not evil.
45208 **    May you find forgiveness for yourself and forgive others.
45209 **    May you share freely, never taking more than you give.
45210 **
45211 *************************************************************************
45212 ** This file implements a external (disk-based) database using BTrees.
45213 ** See the header comment on "btreeInt.h" for additional information.
45214 ** Including a description of file format and an overview of operation.
45215 */
45216
45217 /*
45218 ** The header string that appears at the beginning of every
45219 ** SQLite database.
45220 */
45221 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
45222
45223 /*
45224 ** Set this global variable to 1 to enable tracing using the TRACE
45225 ** macro.
45226 */
45227 #if 0
45228 int sqlite3BtreeTrace=1;  /* True to enable tracing */
45229 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
45230 #else
45231 # define TRACE(X)
45232 #endif
45233
45234 /*
45235 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
45236 ** But if the value is zero, make it 65536.
45237 **
45238 ** This routine is used to extract the "offset to cell content area" value
45239 ** from the header of a btree page.  If the page size is 65536 and the page
45240 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
45241 ** This routine makes the necessary adjustment to 65536.
45242 */
45243 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
45244
45245 #ifndef SQLITE_OMIT_SHARED_CACHE
45246 /*
45247 ** A list of BtShared objects that are eligible for participation
45248 ** in shared cache.  This variable has file scope during normal builds,
45249 ** but the test harness needs to access it so we make it global for 
45250 ** test builds.
45251 **
45252 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
45253 */
45254 #ifdef SQLITE_TEST
45255 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
45256 #else
45257 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
45258 #endif
45259 #endif /* SQLITE_OMIT_SHARED_CACHE */
45260
45261 #ifndef SQLITE_OMIT_SHARED_CACHE
45262 /*
45263 ** Enable or disable the shared pager and schema features.
45264 **
45265 ** This routine has no effect on existing database connections.
45266 ** The shared cache setting effects only future calls to
45267 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
45268 */
45269 SQLITE_API int sqlite3_enable_shared_cache(int enable){
45270   sqlite3GlobalConfig.sharedCacheEnabled = enable;
45271   return SQLITE_OK;
45272 }
45273 #endif
45274
45275
45276
45277 #ifdef SQLITE_OMIT_SHARED_CACHE
45278   /*
45279   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
45280   ** and clearAllSharedCacheTableLocks()
45281   ** manipulate entries in the BtShared.pLock linked list used to store
45282   ** shared-cache table level locks. If the library is compiled with the
45283   ** shared-cache feature disabled, then there is only ever one user
45284   ** of each BtShared structure and so this locking is not necessary. 
45285   ** So define the lock related functions as no-ops.
45286   */
45287   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
45288   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
45289   #define clearAllSharedCacheTableLocks(a)
45290   #define downgradeAllSharedCacheTableLocks(a)
45291   #define hasSharedCacheTableLock(a,b,c,d) 1
45292   #define hasReadConflicts(a, b) 0
45293 #endif
45294
45295 #ifndef SQLITE_OMIT_SHARED_CACHE
45296
45297 #ifdef SQLITE_DEBUG
45298 /*
45299 **** This function is only used as part of an assert() statement. ***
45300 **
45301 ** Check to see if pBtree holds the required locks to read or write to the 
45302 ** table with root page iRoot.   Return 1 if it does and 0 if not.
45303 **
45304 ** For example, when writing to a table with root-page iRoot via 
45305 ** Btree connection pBtree:
45306 **
45307 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
45308 **
45309 ** When writing to an index that resides in a sharable database, the 
45310 ** caller should have first obtained a lock specifying the root page of
45311 ** the corresponding table. This makes things a bit more complicated,
45312 ** as this module treats each table as a separate structure. To determine
45313 ** the table corresponding to the index being written, this
45314 ** function has to search through the database schema.
45315 **
45316 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
45317 ** hold a write-lock on the schema table (root page 1). This is also
45318 ** acceptable.
45319 */
45320 static int hasSharedCacheTableLock(
45321   Btree *pBtree,         /* Handle that must hold lock */
45322   Pgno iRoot,            /* Root page of b-tree */
45323   int isIndex,           /* True if iRoot is the root of an index b-tree */
45324   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
45325 ){
45326   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
45327   Pgno iTab = 0;
45328   BtLock *pLock;
45329
45330   /* If this database is not shareable, or if the client is reading
45331   ** and has the read-uncommitted flag set, then no lock is required. 
45332   ** Return true immediately.
45333   */
45334   if( (pBtree->sharable==0)
45335    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
45336   ){
45337     return 1;
45338   }
45339
45340   /* If the client is reading  or writing an index and the schema is
45341   ** not loaded, then it is too difficult to actually check to see if
45342   ** the correct locks are held.  So do not bother - just return true.
45343   ** This case does not come up very often anyhow.
45344   */
45345   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
45346     return 1;
45347   }
45348
45349   /* Figure out the root-page that the lock should be held on. For table
45350   ** b-trees, this is just the root page of the b-tree being read or
45351   ** written. For index b-trees, it is the root page of the associated
45352   ** table.  */
45353   if( isIndex ){
45354     HashElem *p;
45355     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
45356       Index *pIdx = (Index *)sqliteHashData(p);
45357       if( pIdx->tnum==(int)iRoot ){
45358         iTab = pIdx->pTable->tnum;
45359       }
45360     }
45361   }else{
45362     iTab = iRoot;
45363   }
45364
45365   /* Search for the required lock. Either a write-lock on root-page iTab, a 
45366   ** write-lock on the schema table, or (if the client is reading) a
45367   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
45368   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
45369     if( pLock->pBtree==pBtree 
45370      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
45371      && pLock->eLock>=eLockType 
45372     ){
45373       return 1;
45374     }
45375   }
45376
45377   /* Failed to find the required lock. */
45378   return 0;
45379 }
45380 #endif /* SQLITE_DEBUG */
45381
45382 #ifdef SQLITE_DEBUG
45383 /*
45384 **** This function may be used as part of assert() statements only. ****
45385 **
45386 ** Return true if it would be illegal for pBtree to write into the
45387 ** table or index rooted at iRoot because other shared connections are
45388 ** simultaneously reading that same table or index.
45389 **
45390 ** It is illegal for pBtree to write if some other Btree object that
45391 ** shares the same BtShared object is currently reading or writing
45392 ** the iRoot table.  Except, if the other Btree object has the
45393 ** read-uncommitted flag set, then it is OK for the other object to
45394 ** have a read cursor.
45395 **
45396 ** For example, before writing to any part of the table or index
45397 ** rooted at page iRoot, one should call:
45398 **
45399 **    assert( !hasReadConflicts(pBtree, iRoot) );
45400 */
45401 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
45402   BtCursor *p;
45403   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
45404     if( p->pgnoRoot==iRoot 
45405      && p->pBtree!=pBtree
45406      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
45407     ){
45408       return 1;
45409     }
45410   }
45411   return 0;
45412 }
45413 #endif    /* #ifdef SQLITE_DEBUG */
45414
45415 /*
45416 ** Query to see if Btree handle p may obtain a lock of type eLock 
45417 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
45418 ** SQLITE_OK if the lock may be obtained (by calling
45419 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
45420 */
45421 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
45422   BtShared *pBt = p->pBt;
45423   BtLock *pIter;
45424
45425   assert( sqlite3BtreeHoldsMutex(p) );
45426   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
45427   assert( p->db!=0 );
45428   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
45429   
45430   /* If requesting a write-lock, then the Btree must have an open write
45431   ** transaction on this file. And, obviously, for this to be so there 
45432   ** must be an open write transaction on the file itself.
45433   */
45434   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
45435   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
45436   
45437   /* This routine is a no-op if the shared-cache is not enabled */
45438   if( !p->sharable ){
45439     return SQLITE_OK;
45440   }
45441
45442   /* If some other connection is holding an exclusive lock, the
45443   ** requested lock may not be obtained.
45444   */
45445   if( pBt->pWriter!=p && pBt->isExclusive ){
45446     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
45447     return SQLITE_LOCKED_SHAREDCACHE;
45448   }
45449
45450   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
45451     /* The condition (pIter->eLock!=eLock) in the following if(...) 
45452     ** statement is a simplification of:
45453     **
45454     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
45455     **
45456     ** since we know that if eLock==WRITE_LOCK, then no other connection
45457     ** may hold a WRITE_LOCK on any table in this file (since there can
45458     ** only be a single writer).
45459     */
45460     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
45461     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
45462     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
45463       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
45464       if( eLock==WRITE_LOCK ){
45465         assert( p==pBt->pWriter );
45466         pBt->isPending = 1;
45467       }
45468       return SQLITE_LOCKED_SHAREDCACHE;
45469     }
45470   }
45471   return SQLITE_OK;
45472 }
45473 #endif /* !SQLITE_OMIT_SHARED_CACHE */
45474
45475 #ifndef SQLITE_OMIT_SHARED_CACHE
45476 /*
45477 ** Add a lock on the table with root-page iTable to the shared-btree used
45478 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
45479 ** WRITE_LOCK.
45480 **
45481 ** This function assumes the following:
45482 **
45483 **   (a) The specified Btree object p is connected to a sharable
45484 **       database (one with the BtShared.sharable flag set), and
45485 **
45486 **   (b) No other Btree objects hold a lock that conflicts
45487 **       with the requested lock (i.e. querySharedCacheTableLock() has
45488 **       already been called and returned SQLITE_OK).
45489 **
45490 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
45491 ** is returned if a malloc attempt fails.
45492 */
45493 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
45494   BtShared *pBt = p->pBt;
45495   BtLock *pLock = 0;
45496   BtLock *pIter;
45497
45498   assert( sqlite3BtreeHoldsMutex(p) );
45499   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
45500   assert( p->db!=0 );
45501
45502   /* A connection with the read-uncommitted flag set will never try to
45503   ** obtain a read-lock using this function. The only read-lock obtained
45504   ** by a connection in read-uncommitted mode is on the sqlite_master 
45505   ** table, and that lock is obtained in BtreeBeginTrans().  */
45506   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
45507
45508   /* This function should only be called on a sharable b-tree after it 
45509   ** has been determined that no other b-tree holds a conflicting lock.  */
45510   assert( p->sharable );
45511   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
45512
45513   /* First search the list for an existing lock on this table. */
45514   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
45515     if( pIter->iTable==iTable && pIter->pBtree==p ){
45516       pLock = pIter;
45517       break;
45518     }
45519   }
45520
45521   /* If the above search did not find a BtLock struct associating Btree p
45522   ** with table iTable, allocate one and link it into the list.
45523   */
45524   if( !pLock ){
45525     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
45526     if( !pLock ){
45527       return SQLITE_NOMEM;
45528     }
45529     pLock->iTable = iTable;
45530     pLock->pBtree = p;
45531     pLock->pNext = pBt->pLock;
45532     pBt->pLock = pLock;
45533   }
45534
45535   /* Set the BtLock.eLock variable to the maximum of the current lock
45536   ** and the requested lock. This means if a write-lock was already held
45537   ** and a read-lock requested, we don't incorrectly downgrade the lock.
45538   */
45539   assert( WRITE_LOCK>READ_LOCK );
45540   if( eLock>pLock->eLock ){
45541     pLock->eLock = eLock;
45542   }
45543
45544   return SQLITE_OK;
45545 }
45546 #endif /* !SQLITE_OMIT_SHARED_CACHE */
45547
45548 #ifndef SQLITE_OMIT_SHARED_CACHE
45549 /*
45550 ** Release all the table locks (locks obtained via calls to
45551 ** the setSharedCacheTableLock() procedure) held by Btree object p.
45552 **
45553 ** This function assumes that Btree p has an open read or write 
45554 ** transaction. If it does not, then the BtShared.isPending variable
45555 ** may be incorrectly cleared.
45556 */
45557 static void clearAllSharedCacheTableLocks(Btree *p){
45558   BtShared *pBt = p->pBt;
45559   BtLock **ppIter = &pBt->pLock;
45560
45561   assert( sqlite3BtreeHoldsMutex(p) );
45562   assert( p->sharable || 0==*ppIter );
45563   assert( p->inTrans>0 );
45564
45565   while( *ppIter ){
45566     BtLock *pLock = *ppIter;
45567     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
45568     assert( pLock->pBtree->inTrans>=pLock->eLock );
45569     if( pLock->pBtree==p ){
45570       *ppIter = pLock->pNext;
45571       assert( pLock->iTable!=1 || pLock==&p->lock );
45572       if( pLock->iTable!=1 ){
45573         sqlite3_free(pLock);
45574       }
45575     }else{
45576       ppIter = &pLock->pNext;
45577     }
45578   }
45579
45580   assert( pBt->isPending==0 || pBt->pWriter );
45581   if( pBt->pWriter==p ){
45582     pBt->pWriter = 0;
45583     pBt->isExclusive = 0;
45584     pBt->isPending = 0;
45585   }else if( pBt->nTransaction==2 ){
45586     /* This function is called when Btree p is concluding its 
45587     ** transaction. If there currently exists a writer, and p is not
45588     ** that writer, then the number of locks held by connections other
45589     ** than the writer must be about to drop to zero. In this case
45590     ** set the isPending flag to 0.
45591     **
45592     ** If there is not currently a writer, then BtShared.isPending must
45593     ** be zero already. So this next line is harmless in that case.
45594     */
45595     pBt->isPending = 0;
45596   }
45597 }
45598
45599 /*
45600 ** This function changes all write-locks held by Btree p into read-locks.
45601 */
45602 static void downgradeAllSharedCacheTableLocks(Btree *p){
45603   BtShared *pBt = p->pBt;
45604   if( pBt->pWriter==p ){
45605     BtLock *pLock;
45606     pBt->pWriter = 0;
45607     pBt->isExclusive = 0;
45608     pBt->isPending = 0;
45609     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
45610       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
45611       pLock->eLock = READ_LOCK;
45612     }
45613   }
45614 }
45615
45616 #endif /* SQLITE_OMIT_SHARED_CACHE */
45617
45618 static void releasePage(MemPage *pPage);  /* Forward reference */
45619
45620 /*
45621 ***** This routine is used inside of assert() only ****
45622 **
45623 ** Verify that the cursor holds the mutex on its BtShared
45624 */
45625 #ifdef SQLITE_DEBUG
45626 static int cursorHoldsMutex(BtCursor *p){
45627   return sqlite3_mutex_held(p->pBt->mutex);
45628 }
45629 #endif
45630
45631
45632 #ifndef SQLITE_OMIT_INCRBLOB
45633 /*
45634 ** Invalidate the overflow page-list cache for cursor pCur, if any.
45635 */
45636 static void invalidateOverflowCache(BtCursor *pCur){
45637   assert( cursorHoldsMutex(pCur) );
45638   sqlite3_free(pCur->aOverflow);
45639   pCur->aOverflow = 0;
45640 }
45641
45642 /*
45643 ** Invalidate the overflow page-list cache for all cursors opened
45644 ** on the shared btree structure pBt.
45645 */
45646 static void invalidateAllOverflowCache(BtShared *pBt){
45647   BtCursor *p;
45648   assert( sqlite3_mutex_held(pBt->mutex) );
45649   for(p=pBt->pCursor; p; p=p->pNext){
45650     invalidateOverflowCache(p);
45651   }
45652 }
45653
45654 /*
45655 ** This function is called before modifying the contents of a table
45656 ** to invalidate any incrblob cursors that are open on the
45657 ** row or one of the rows being modified.
45658 **
45659 ** If argument isClearTable is true, then the entire contents of the
45660 ** table is about to be deleted. In this case invalidate all incrblob
45661 ** cursors open on any row within the table with root-page pgnoRoot.
45662 **
45663 ** Otherwise, if argument isClearTable is false, then the row with
45664 ** rowid iRow is being replaced or deleted. In this case invalidate
45665 ** only those incrblob cursors open on that specific row.
45666 */
45667 static void invalidateIncrblobCursors(
45668   Btree *pBtree,          /* The database file to check */
45669   i64 iRow,               /* The rowid that might be changing */
45670   int isClearTable        /* True if all rows are being deleted */
45671 ){
45672   BtCursor *p;
45673   BtShared *pBt = pBtree->pBt;
45674   assert( sqlite3BtreeHoldsMutex(pBtree) );
45675   for(p=pBt->pCursor; p; p=p->pNext){
45676     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
45677       p->eState = CURSOR_INVALID;
45678     }
45679   }
45680 }
45681
45682 #else
45683   /* Stub functions when INCRBLOB is omitted */
45684   #define invalidateOverflowCache(x)
45685   #define invalidateAllOverflowCache(x)
45686   #define invalidateIncrblobCursors(x,y,z)
45687 #endif /* SQLITE_OMIT_INCRBLOB */
45688
45689 /*
45690 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
45691 ** when a page that previously contained data becomes a free-list leaf 
45692 ** page.
45693 **
45694 ** The BtShared.pHasContent bitvec exists to work around an obscure
45695 ** bug caused by the interaction of two useful IO optimizations surrounding
45696 ** free-list leaf pages:
45697 **
45698 **   1) When all data is deleted from a page and the page becomes
45699 **      a free-list leaf page, the page is not written to the database
45700 **      (as free-list leaf pages contain no meaningful data). Sometimes
45701 **      such a page is not even journalled (as it will not be modified,
45702 **      why bother journalling it?).
45703 **
45704 **   2) When a free-list leaf page is reused, its content is not read
45705 **      from the database or written to the journal file (why should it
45706 **      be, if it is not at all meaningful?).
45707 **
45708 ** By themselves, these optimizations work fine and provide a handy
45709 ** performance boost to bulk delete or insert operations. However, if
45710 ** a page is moved to the free-list and then reused within the same
45711 ** transaction, a problem comes up. If the page is not journalled when
45712 ** it is moved to the free-list and it is also not journalled when it
45713 ** is extracted from the free-list and reused, then the original data
45714 ** may be lost. In the event of a rollback, it may not be possible
45715 ** to restore the database to its original configuration.
45716 **
45717 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
45718 ** moved to become a free-list leaf page, the corresponding bit is
45719 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
45720 ** optimization 2 above is omitted if the corresponding bit is already
45721 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
45722 ** at the end of every transaction.
45723 */
45724 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
45725   int rc = SQLITE_OK;
45726   if( !pBt->pHasContent ){
45727     assert( pgno<=pBt->nPage );
45728     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
45729     if( !pBt->pHasContent ){
45730       rc = SQLITE_NOMEM;
45731     }
45732   }
45733   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
45734     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
45735   }
45736   return rc;
45737 }
45738
45739 /*
45740 ** Query the BtShared.pHasContent vector.
45741 **
45742 ** This function is called when a free-list leaf page is removed from the
45743 ** free-list for reuse. It returns false if it is safe to retrieve the
45744 ** page from the pager layer with the 'no-content' flag set. True otherwise.
45745 */
45746 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
45747   Bitvec *p = pBt->pHasContent;
45748   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
45749 }
45750
45751 /*
45752 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
45753 ** invoked at the conclusion of each write-transaction.
45754 */
45755 static void btreeClearHasContent(BtShared *pBt){
45756   sqlite3BitvecDestroy(pBt->pHasContent);
45757   pBt->pHasContent = 0;
45758 }
45759
45760 /*
45761 ** Save the current cursor position in the variables BtCursor.nKey 
45762 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
45763 **
45764 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
45765 ** prior to calling this routine.  
45766 */
45767 static int saveCursorPosition(BtCursor *pCur){
45768   int rc;
45769
45770   assert( CURSOR_VALID==pCur->eState );
45771   assert( 0==pCur->pKey );
45772   assert( cursorHoldsMutex(pCur) );
45773
45774   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
45775   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
45776
45777   /* If this is an intKey table, then the above call to BtreeKeySize()
45778   ** stores the integer key in pCur->nKey. In this case this value is
45779   ** all that is required. Otherwise, if pCur is not open on an intKey
45780   ** table, then malloc space for and store the pCur->nKey bytes of key 
45781   ** data.
45782   */
45783   if( 0==pCur->apPage[0]->intKey ){
45784     void *pKey = sqlite3Malloc( (int)pCur->nKey );
45785     if( pKey ){
45786       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
45787       if( rc==SQLITE_OK ){
45788         pCur->pKey = pKey;
45789       }else{
45790         sqlite3_free(pKey);
45791       }
45792     }else{
45793       rc = SQLITE_NOMEM;
45794     }
45795   }
45796   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
45797
45798   if( rc==SQLITE_OK ){
45799     int i;
45800     for(i=0; i<=pCur->iPage; i++){
45801       releasePage(pCur->apPage[i]);
45802       pCur->apPage[i] = 0;
45803     }
45804     pCur->iPage = -1;
45805     pCur->eState = CURSOR_REQUIRESEEK;
45806   }
45807
45808   invalidateOverflowCache(pCur);
45809   return rc;
45810 }
45811
45812 /*
45813 ** Save the positions of all cursors (except pExcept) that are open on
45814 ** the table  with root-page iRoot. Usually, this is called just before cursor
45815 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
45816 */
45817 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
45818   BtCursor *p;
45819   assert( sqlite3_mutex_held(pBt->mutex) );
45820   assert( pExcept==0 || pExcept->pBt==pBt );
45821   for(p=pBt->pCursor; p; p=p->pNext){
45822     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
45823         p->eState==CURSOR_VALID ){
45824       int rc = saveCursorPosition(p);
45825       if( SQLITE_OK!=rc ){
45826         return rc;
45827       }
45828     }
45829   }
45830   return SQLITE_OK;
45831 }
45832
45833 /*
45834 ** Clear the current cursor position.
45835 */
45836 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
45837   assert( cursorHoldsMutex(pCur) );
45838   sqlite3_free(pCur->pKey);
45839   pCur->pKey = 0;
45840   pCur->eState = CURSOR_INVALID;
45841 }
45842
45843 /*
45844 ** In this version of BtreeMoveto, pKey is a packed index record
45845 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
45846 ** record and then call BtreeMovetoUnpacked() to do the work.
45847 */
45848 static int btreeMoveto(
45849   BtCursor *pCur,     /* Cursor open on the btree to be searched */
45850   const void *pKey,   /* Packed key if the btree is an index */
45851   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
45852   int bias,           /* Bias search to the high end */
45853   int *pRes           /* Write search results here */
45854 ){
45855   int rc;                    /* Status code */
45856   UnpackedRecord *pIdxKey;   /* Unpacked index key */
45857   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
45858
45859   if( pKey ){
45860     assert( nKey==(i64)(int)nKey );
45861     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
45862                                       aSpace, sizeof(aSpace));
45863     if( pIdxKey==0 ) return SQLITE_NOMEM;
45864   }else{
45865     pIdxKey = 0;
45866   }
45867   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
45868   if( pKey ){
45869     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
45870   }
45871   return rc;
45872 }
45873
45874 /*
45875 ** Restore the cursor to the position it was in (or as close to as possible)
45876 ** when saveCursorPosition() was called. Note that this call deletes the 
45877 ** saved position info stored by saveCursorPosition(), so there can be
45878 ** at most one effective restoreCursorPosition() call after each 
45879 ** saveCursorPosition().
45880 */
45881 static int btreeRestoreCursorPosition(BtCursor *pCur){
45882   int rc;
45883   assert( cursorHoldsMutex(pCur) );
45884   assert( pCur->eState>=CURSOR_REQUIRESEEK );
45885   if( pCur->eState==CURSOR_FAULT ){
45886     return pCur->skipNext;
45887   }
45888   pCur->eState = CURSOR_INVALID;
45889   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
45890   if( rc==SQLITE_OK ){
45891     sqlite3_free(pCur->pKey);
45892     pCur->pKey = 0;
45893     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
45894   }
45895   return rc;
45896 }
45897
45898 #define restoreCursorPosition(p) \
45899   (p->eState>=CURSOR_REQUIRESEEK ? \
45900          btreeRestoreCursorPosition(p) : \
45901          SQLITE_OK)
45902
45903 /*
45904 ** Determine whether or not a cursor has moved from the position it
45905 ** was last placed at.  Cursors can move when the row they are pointing
45906 ** at is deleted out from under them.
45907 **
45908 ** This routine returns an error code if something goes wrong.  The
45909 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
45910 */
45911 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
45912   int rc;
45913
45914   rc = restoreCursorPosition(pCur);
45915   if( rc ){
45916     *pHasMoved = 1;
45917     return rc;
45918   }
45919   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
45920     *pHasMoved = 1;
45921   }else{
45922     *pHasMoved = 0;
45923   }
45924   return SQLITE_OK;
45925 }
45926
45927 #ifndef SQLITE_OMIT_AUTOVACUUM
45928 /*
45929 ** Given a page number of a regular database page, return the page
45930 ** number for the pointer-map page that contains the entry for the
45931 ** input page number.
45932 **
45933 ** Return 0 (not a valid page) for pgno==1 since there is
45934 ** no pointer map associated with page 1.  The integrity_check logic
45935 ** requires that ptrmapPageno(*,1)!=1.
45936 */
45937 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
45938   int nPagesPerMapPage;
45939   Pgno iPtrMap, ret;
45940   assert( sqlite3_mutex_held(pBt->mutex) );
45941   if( pgno<2 ) return 0;
45942   nPagesPerMapPage = (pBt->usableSize/5)+1;
45943   iPtrMap = (pgno-2)/nPagesPerMapPage;
45944   ret = (iPtrMap*nPagesPerMapPage) + 2; 
45945   if( ret==PENDING_BYTE_PAGE(pBt) ){
45946     ret++;
45947   }
45948   return ret;
45949 }
45950
45951 /*
45952 ** Write an entry into the pointer map.
45953 **
45954 ** This routine updates the pointer map entry for page number 'key'
45955 ** so that it maps to type 'eType' and parent page number 'pgno'.
45956 **
45957 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
45958 ** a no-op.  If an error occurs, the appropriate error code is written
45959 ** into *pRC.
45960 */
45961 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
45962   DbPage *pDbPage;  /* The pointer map page */
45963   u8 *pPtrmap;      /* The pointer map data */
45964   Pgno iPtrmap;     /* The pointer map page number */
45965   int offset;       /* Offset in pointer map page */
45966   int rc;           /* Return code from subfunctions */
45967
45968   if( *pRC ) return;
45969
45970   assert( sqlite3_mutex_held(pBt->mutex) );
45971   /* The master-journal page number must never be used as a pointer map page */
45972   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
45973
45974   assert( pBt->autoVacuum );
45975   if( key==0 ){
45976     *pRC = SQLITE_CORRUPT_BKPT;
45977     return;
45978   }
45979   iPtrmap = PTRMAP_PAGENO(pBt, key);
45980   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
45981   if( rc!=SQLITE_OK ){
45982     *pRC = rc;
45983     return;
45984   }
45985   offset = PTRMAP_PTROFFSET(iPtrmap, key);
45986   if( offset<0 ){
45987     *pRC = SQLITE_CORRUPT_BKPT;
45988     goto ptrmap_exit;
45989   }
45990   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
45991
45992   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
45993     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
45994     *pRC= rc = sqlite3PagerWrite(pDbPage);
45995     if( rc==SQLITE_OK ){
45996       pPtrmap[offset] = eType;
45997       put4byte(&pPtrmap[offset+1], parent);
45998     }
45999   }
46000
46001 ptrmap_exit:
46002   sqlite3PagerUnref(pDbPage);
46003 }
46004
46005 /*
46006 ** Read an entry from the pointer map.
46007 **
46008 ** This routine retrieves the pointer map entry for page 'key', writing
46009 ** the type and parent page number to *pEType and *pPgno respectively.
46010 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
46011 */
46012 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
46013   DbPage *pDbPage;   /* The pointer map page */
46014   int iPtrmap;       /* Pointer map page index */
46015   u8 *pPtrmap;       /* Pointer map page data */
46016   int offset;        /* Offset of entry in pointer map */
46017   int rc;
46018
46019   assert( sqlite3_mutex_held(pBt->mutex) );
46020
46021   iPtrmap = PTRMAP_PAGENO(pBt, key);
46022   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
46023   if( rc!=0 ){
46024     return rc;
46025   }
46026   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
46027
46028   offset = PTRMAP_PTROFFSET(iPtrmap, key);
46029   assert( pEType!=0 );
46030   *pEType = pPtrmap[offset];
46031   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
46032
46033   sqlite3PagerUnref(pDbPage);
46034   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
46035   return SQLITE_OK;
46036 }
46037
46038 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
46039   #define ptrmapPut(w,x,y,z,rc)
46040   #define ptrmapGet(w,x,y,z) SQLITE_OK
46041   #define ptrmapPutOvflPtr(x, y, rc)
46042 #endif
46043
46044 /*
46045 ** Given a btree page and a cell index (0 means the first cell on
46046 ** the page, 1 means the second cell, and so forth) return a pointer
46047 ** to the cell content.
46048 **
46049 ** This routine works only for pages that do not contain overflow cells.
46050 */
46051 #define findCell(P,I) \
46052   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
46053
46054 /*
46055 ** This a more complex version of findCell() that works for
46056 ** pages that do contain overflow cells.
46057 */
46058 static u8 *findOverflowCell(MemPage *pPage, int iCell){
46059   int i;
46060   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46061   for(i=pPage->nOverflow-1; i>=0; i--){
46062     int k;
46063     struct _OvflCell *pOvfl;
46064     pOvfl = &pPage->aOvfl[i];
46065     k = pOvfl->idx;
46066     if( k<=iCell ){
46067       if( k==iCell ){
46068         return pOvfl->pCell;
46069       }
46070       iCell--;
46071     }
46072   }
46073   return findCell(pPage, iCell);
46074 }
46075
46076 /*
46077 ** Parse a cell content block and fill in the CellInfo structure.  There
46078 ** are two versions of this function.  btreeParseCell() takes a 
46079 ** cell index as the second argument and btreeParseCellPtr() 
46080 ** takes a pointer to the body of the cell as its second argument.
46081 **
46082 ** Within this file, the parseCell() macro can be called instead of
46083 ** btreeParseCellPtr(). Using some compilers, this will be faster.
46084 */
46085 static void btreeParseCellPtr(
46086   MemPage *pPage,         /* Page containing the cell */
46087   u8 *pCell,              /* Pointer to the cell text. */
46088   CellInfo *pInfo         /* Fill in this structure */
46089 ){
46090   u16 n;                  /* Number bytes in cell content header */
46091   u32 nPayload;           /* Number of bytes of cell payload */
46092
46093   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46094
46095   pInfo->pCell = pCell;
46096   assert( pPage->leaf==0 || pPage->leaf==1 );
46097   n = pPage->childPtrSize;
46098   assert( n==4-4*pPage->leaf );
46099   if( pPage->intKey ){
46100     if( pPage->hasData ){
46101       n += getVarint32(&pCell[n], nPayload);
46102     }else{
46103       nPayload = 0;
46104     }
46105     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
46106     pInfo->nData = nPayload;
46107   }else{
46108     pInfo->nData = 0;
46109     n += getVarint32(&pCell[n], nPayload);
46110     pInfo->nKey = nPayload;
46111   }
46112   pInfo->nPayload = nPayload;
46113   pInfo->nHeader = n;
46114   testcase( nPayload==pPage->maxLocal );
46115   testcase( nPayload==pPage->maxLocal+1 );
46116   if( likely(nPayload<=pPage->maxLocal) ){
46117     /* This is the (easy) common case where the entire payload fits
46118     ** on the local page.  No overflow is required.
46119     */
46120     int nSize;          /* Total size of cell content in bytes */
46121     nSize = nPayload + n;
46122     pInfo->nLocal = (u16)nPayload;
46123     pInfo->iOverflow = 0;
46124     if( (nSize & ~3)==0 ){
46125       nSize = 4;        /* Minimum cell size is 4 */
46126     }
46127     pInfo->nSize = (u16)nSize;
46128   }else{
46129     /* If the payload will not fit completely on the local page, we have
46130     ** to decide how much to store locally and how much to spill onto
46131     ** overflow pages.  The strategy is to minimize the amount of unused
46132     ** space on overflow pages while keeping the amount of local storage
46133     ** in between minLocal and maxLocal.
46134     **
46135     ** Warning:  changing the way overflow payload is distributed in any
46136     ** way will result in an incompatible file format.
46137     */
46138     int minLocal;  /* Minimum amount of payload held locally */
46139     int maxLocal;  /* Maximum amount of payload held locally */
46140     int surplus;   /* Overflow payload available for local storage */
46141
46142     minLocal = pPage->minLocal;
46143     maxLocal = pPage->maxLocal;
46144     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
46145     testcase( surplus==maxLocal );
46146     testcase( surplus==maxLocal+1 );
46147     if( surplus <= maxLocal ){
46148       pInfo->nLocal = (u16)surplus;
46149     }else{
46150       pInfo->nLocal = (u16)minLocal;
46151     }
46152     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
46153     pInfo->nSize = pInfo->iOverflow + 4;
46154   }
46155 }
46156 #define parseCell(pPage, iCell, pInfo) \
46157   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
46158 static void btreeParseCell(
46159   MemPage *pPage,         /* Page containing the cell */
46160   int iCell,              /* The cell index.  First cell is 0 */
46161   CellInfo *pInfo         /* Fill in this structure */
46162 ){
46163   parseCell(pPage, iCell, pInfo);
46164 }
46165
46166 /*
46167 ** Compute the total number of bytes that a Cell needs in the cell
46168 ** data area of the btree-page.  The return number includes the cell
46169 ** data header and the local payload, but not any overflow page or
46170 ** the space used by the cell pointer.
46171 */
46172 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
46173   u8 *pIter = &pCell[pPage->childPtrSize];
46174   u32 nSize;
46175
46176 #ifdef SQLITE_DEBUG
46177   /* The value returned by this function should always be the same as
46178   ** the (CellInfo.nSize) value found by doing a full parse of the
46179   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
46180   ** this function verifies that this invariant is not violated. */
46181   CellInfo debuginfo;
46182   btreeParseCellPtr(pPage, pCell, &debuginfo);
46183 #endif
46184
46185   if( pPage->intKey ){
46186     u8 *pEnd;
46187     if( pPage->hasData ){
46188       pIter += getVarint32(pIter, nSize);
46189     }else{
46190       nSize = 0;
46191     }
46192
46193     /* pIter now points at the 64-bit integer key value, a variable length 
46194     ** integer. The following block moves pIter to point at the first byte
46195     ** past the end of the key value. */
46196     pEnd = &pIter[9];
46197     while( (*pIter++)&0x80 && pIter<pEnd );
46198   }else{
46199     pIter += getVarint32(pIter, nSize);
46200   }
46201
46202   testcase( nSize==pPage->maxLocal );
46203   testcase( nSize==pPage->maxLocal+1 );
46204   if( nSize>pPage->maxLocal ){
46205     int minLocal = pPage->minLocal;
46206     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
46207     testcase( nSize==pPage->maxLocal );
46208     testcase( nSize==pPage->maxLocal+1 );
46209     if( nSize>pPage->maxLocal ){
46210       nSize = minLocal;
46211     }
46212     nSize += 4;
46213   }
46214   nSize += (u32)(pIter - pCell);
46215
46216   /* The minimum size of any cell is 4 bytes. */
46217   if( nSize<4 ){
46218     nSize = 4;
46219   }
46220
46221   assert( nSize==debuginfo.nSize );
46222   return (u16)nSize;
46223 }
46224
46225 #ifdef SQLITE_DEBUG
46226 /* This variation on cellSizePtr() is used inside of assert() statements
46227 ** only. */
46228 static u16 cellSize(MemPage *pPage, int iCell){
46229   return cellSizePtr(pPage, findCell(pPage, iCell));
46230 }
46231 #endif
46232
46233 #ifndef SQLITE_OMIT_AUTOVACUUM
46234 /*
46235 ** If the cell pCell, part of page pPage contains a pointer
46236 ** to an overflow page, insert an entry into the pointer-map
46237 ** for the overflow page.
46238 */
46239 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
46240   CellInfo info;
46241   if( *pRC ) return;
46242   assert( pCell!=0 );
46243   btreeParseCellPtr(pPage, pCell, &info);
46244   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
46245   if( info.iOverflow ){
46246     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
46247     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
46248   }
46249 }
46250 #endif
46251
46252
46253 /*
46254 ** Defragment the page given.  All Cells are moved to the
46255 ** end of the page and all free space is collected into one
46256 ** big FreeBlk that occurs in between the header and cell
46257 ** pointer array and the cell content area.
46258 */
46259 static int defragmentPage(MemPage *pPage){
46260   int i;                     /* Loop counter */
46261   int pc;                    /* Address of a i-th cell */
46262   int hdr;                   /* Offset to the page header */
46263   int size;                  /* Size of a cell */
46264   int usableSize;            /* Number of usable bytes on a page */
46265   int cellOffset;            /* Offset to the cell pointer array */
46266   int cbrk;                  /* Offset to the cell content area */
46267   int nCell;                 /* Number of cells on the page */
46268   unsigned char *data;       /* The page data */
46269   unsigned char *temp;       /* Temp area for cell content */
46270   int iCellFirst;            /* First allowable cell index */
46271   int iCellLast;             /* Last possible cell index */
46272
46273
46274   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46275   assert( pPage->pBt!=0 );
46276   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
46277   assert( pPage->nOverflow==0 );
46278   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46279   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
46280   data = pPage->aData;
46281   hdr = pPage->hdrOffset;
46282   cellOffset = pPage->cellOffset;
46283   nCell = pPage->nCell;
46284   assert( nCell==get2byte(&data[hdr+3]) );
46285   usableSize = pPage->pBt->usableSize;
46286   cbrk = get2byte(&data[hdr+5]);
46287   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
46288   cbrk = usableSize;
46289   iCellFirst = cellOffset + 2*nCell;
46290   iCellLast = usableSize - 4;
46291   for(i=0; i<nCell; i++){
46292     u8 *pAddr;     /* The i-th cell pointer */
46293     pAddr = &data[cellOffset + i*2];
46294     pc = get2byte(pAddr);
46295     testcase( pc==iCellFirst );
46296     testcase( pc==iCellLast );
46297 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
46298     /* These conditions have already been verified in btreeInitPage()
46299     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
46300     */
46301     if( pc<iCellFirst || pc>iCellLast ){
46302       return SQLITE_CORRUPT_BKPT;
46303     }
46304 #endif
46305     assert( pc>=iCellFirst && pc<=iCellLast );
46306     size = cellSizePtr(pPage, &temp[pc]);
46307     cbrk -= size;
46308 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
46309     if( cbrk<iCellFirst ){
46310       return SQLITE_CORRUPT_BKPT;
46311     }
46312 #else
46313     if( cbrk<iCellFirst || pc+size>usableSize ){
46314       return SQLITE_CORRUPT_BKPT;
46315     }
46316 #endif
46317     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
46318     testcase( cbrk+size==usableSize );
46319     testcase( pc+size==usableSize );
46320     memcpy(&data[cbrk], &temp[pc], size);
46321     put2byte(pAddr, cbrk);
46322   }
46323   assert( cbrk>=iCellFirst );
46324   put2byte(&data[hdr+5], cbrk);
46325   data[hdr+1] = 0;
46326   data[hdr+2] = 0;
46327   data[hdr+7] = 0;
46328   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
46329   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46330   if( cbrk-iCellFirst!=pPage->nFree ){
46331     return SQLITE_CORRUPT_BKPT;
46332   }
46333   return SQLITE_OK;
46334 }
46335
46336 /*
46337 ** Allocate nByte bytes of space from within the B-Tree page passed
46338 ** as the first argument. Write into *pIdx the index into pPage->aData[]
46339 ** of the first byte of allocated space. Return either SQLITE_OK or
46340 ** an error code (usually SQLITE_CORRUPT).
46341 **
46342 ** The caller guarantees that there is sufficient space to make the
46343 ** allocation.  This routine might need to defragment in order to bring
46344 ** all the space together, however.  This routine will avoid using
46345 ** the first two bytes past the cell pointer area since presumably this
46346 ** allocation is being made in order to insert a new cell, so we will
46347 ** also end up needing a new cell pointer.
46348 */
46349 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
46350   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
46351   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
46352   int nFrag;                           /* Number of fragmented bytes on pPage */
46353   int top;                             /* First byte of cell content area */
46354   int gap;        /* First byte of gap between cell pointers and cell content */
46355   int rc;         /* Integer return code */
46356   int usableSize; /* Usable size of the page */
46357   
46358   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46359   assert( pPage->pBt );
46360   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46361   assert( nByte>=0 );  /* Minimum cell size is 4 */
46362   assert( pPage->nFree>=nByte );
46363   assert( pPage->nOverflow==0 );
46364   usableSize = pPage->pBt->usableSize;
46365   assert( nByte < usableSize-8 );
46366
46367   nFrag = data[hdr+7];
46368   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
46369   gap = pPage->cellOffset + 2*pPage->nCell;
46370   top = get2byteNotZero(&data[hdr+5]);
46371   if( gap>top ) return SQLITE_CORRUPT_BKPT;
46372   testcase( gap+2==top );
46373   testcase( gap+1==top );
46374   testcase( gap==top );
46375
46376   if( nFrag>=60 ){
46377     /* Always defragment highly fragmented pages */
46378     rc = defragmentPage(pPage);
46379     if( rc ) return rc;
46380     top = get2byteNotZero(&data[hdr+5]);
46381   }else if( gap+2<=top ){
46382     /* Search the freelist looking for a free slot big enough to satisfy 
46383     ** the request. The allocation is made from the first free slot in 
46384     ** the list that is large enough to accomadate it.
46385     */
46386     int pc, addr;
46387     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
46388       int size;            /* Size of the free slot */
46389       if( pc>usableSize-4 || pc<addr+4 ){
46390         return SQLITE_CORRUPT_BKPT;
46391       }
46392       size = get2byte(&data[pc+2]);
46393       if( size>=nByte ){
46394         int x = size - nByte;
46395         testcase( x==4 );
46396         testcase( x==3 );
46397         if( x<4 ){
46398           /* Remove the slot from the free-list. Update the number of
46399           ** fragmented bytes within the page. */
46400           memcpy(&data[addr], &data[pc], 2);
46401           data[hdr+7] = (u8)(nFrag + x);
46402         }else if( size+pc > usableSize ){
46403           return SQLITE_CORRUPT_BKPT;
46404         }else{
46405           /* The slot remains on the free-list. Reduce its size to account
46406           ** for the portion used by the new allocation. */
46407           put2byte(&data[pc+2], x);
46408         }
46409         *pIdx = pc + x;
46410         return SQLITE_OK;
46411       }
46412     }
46413   }
46414
46415   /* Check to make sure there is enough space in the gap to satisfy
46416   ** the allocation.  If not, defragment.
46417   */
46418   testcase( gap+2+nByte==top );
46419   if( gap+2+nByte>top ){
46420     rc = defragmentPage(pPage);
46421     if( rc ) return rc;
46422     top = get2byteNotZero(&data[hdr+5]);
46423     assert( gap+nByte<=top );
46424   }
46425
46426
46427   /* Allocate memory from the gap in between the cell pointer array
46428   ** and the cell content area.  The btreeInitPage() call has already
46429   ** validated the freelist.  Given that the freelist is valid, there
46430   ** is no way that the allocation can extend off the end of the page.
46431   ** The assert() below verifies the previous sentence.
46432   */
46433   top -= nByte;
46434   put2byte(&data[hdr+5], top);
46435   assert( top+nByte <= pPage->pBt->usableSize );
46436   *pIdx = top;
46437   return SQLITE_OK;
46438 }
46439
46440 /*
46441 ** Return a section of the pPage->aData to the freelist.
46442 ** The first byte of the new free block is pPage->aDisk[start]
46443 ** and the size of the block is "size" bytes.
46444 **
46445 ** Most of the effort here is involved in coalesing adjacent
46446 ** free blocks into a single big free block.
46447 */
46448 static int freeSpace(MemPage *pPage, int start, int size){
46449   int addr, pbegin, hdr;
46450   int iLast;                        /* Largest possible freeblock offset */
46451   unsigned char *data = pPage->aData;
46452
46453   assert( pPage->pBt!=0 );
46454   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46455   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
46456   assert( (start + size)<=pPage->pBt->usableSize );
46457   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46458   assert( size>=0 );   /* Minimum cell size is 4 */
46459
46460   if( pPage->pBt->secureDelete ){
46461     /* Overwrite deleted information with zeros when the secure_delete
46462     ** option is enabled */
46463     memset(&data[start], 0, size);
46464   }
46465
46466   /* Add the space back into the linked list of freeblocks.  Note that
46467   ** even though the freeblock list was checked by btreeInitPage(),
46468   ** btreeInitPage() did not detect overlapping cells or
46469   ** freeblocks that overlapped cells.   Nor does it detect when the
46470   ** cell content area exceeds the value in the page header.  If these
46471   ** situations arise, then subsequent insert operations might corrupt
46472   ** the freelist.  So we do need to check for corruption while scanning
46473   ** the freelist.
46474   */
46475   hdr = pPage->hdrOffset;
46476   addr = hdr + 1;
46477   iLast = pPage->pBt->usableSize - 4;
46478   assert( start<=iLast );
46479   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
46480     if( pbegin<addr+4 ){
46481       return SQLITE_CORRUPT_BKPT;
46482     }
46483     addr = pbegin;
46484   }
46485   if( pbegin>iLast ){
46486     return SQLITE_CORRUPT_BKPT;
46487   }
46488   assert( pbegin>addr || pbegin==0 );
46489   put2byte(&data[addr], start);
46490   put2byte(&data[start], pbegin);
46491   put2byte(&data[start+2], size);
46492   pPage->nFree = pPage->nFree + (u16)size;
46493
46494   /* Coalesce adjacent free blocks */
46495   addr = hdr + 1;
46496   while( (pbegin = get2byte(&data[addr]))>0 ){
46497     int pnext, psize, x;
46498     assert( pbegin>addr );
46499     assert( pbegin<=pPage->pBt->usableSize-4 );
46500     pnext = get2byte(&data[pbegin]);
46501     psize = get2byte(&data[pbegin+2]);
46502     if( pbegin + psize + 3 >= pnext && pnext>0 ){
46503       int frag = pnext - (pbegin+psize);
46504       if( (frag<0) || (frag>(int)data[hdr+7]) ){
46505         return SQLITE_CORRUPT_BKPT;
46506       }
46507       data[hdr+7] -= (u8)frag;
46508       x = get2byte(&data[pnext]);
46509       put2byte(&data[pbegin], x);
46510       x = pnext + get2byte(&data[pnext+2]) - pbegin;
46511       put2byte(&data[pbegin+2], x);
46512     }else{
46513       addr = pbegin;
46514     }
46515   }
46516
46517   /* If the cell content area begins with a freeblock, remove it. */
46518   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
46519     int top;
46520     pbegin = get2byte(&data[hdr+1]);
46521     memcpy(&data[hdr+1], &data[pbegin], 2);
46522     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
46523     put2byte(&data[hdr+5], top);
46524   }
46525   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46526   return SQLITE_OK;
46527 }
46528
46529 /*
46530 ** Decode the flags byte (the first byte of the header) for a page
46531 ** and initialize fields of the MemPage structure accordingly.
46532 **
46533 ** Only the following combinations are supported.  Anything different
46534 ** indicates a corrupt database files:
46535 **
46536 **         PTF_ZERODATA
46537 **         PTF_ZERODATA | PTF_LEAF
46538 **         PTF_LEAFDATA | PTF_INTKEY
46539 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
46540 */
46541 static int decodeFlags(MemPage *pPage, int flagByte){
46542   BtShared *pBt;     /* A copy of pPage->pBt */
46543
46544   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
46545   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46546   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
46547   flagByte &= ~PTF_LEAF;
46548   pPage->childPtrSize = 4-4*pPage->leaf;
46549   pBt = pPage->pBt;
46550   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
46551     pPage->intKey = 1;
46552     pPage->hasData = pPage->leaf;
46553     pPage->maxLocal = pBt->maxLeaf;
46554     pPage->minLocal = pBt->minLeaf;
46555   }else if( flagByte==PTF_ZERODATA ){
46556     pPage->intKey = 0;
46557     pPage->hasData = 0;
46558     pPage->maxLocal = pBt->maxLocal;
46559     pPage->minLocal = pBt->minLocal;
46560   }else{
46561     return SQLITE_CORRUPT_BKPT;
46562   }
46563   return SQLITE_OK;
46564 }
46565
46566 /*
46567 ** Initialize the auxiliary information for a disk block.
46568 **
46569 ** Return SQLITE_OK on success.  If we see that the page does
46570 ** not contain a well-formed database page, then return 
46571 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
46572 ** guarantee that the page is well-formed.  It only shows that
46573 ** we failed to detect any corruption.
46574 */
46575 static int btreeInitPage(MemPage *pPage){
46576
46577   assert( pPage->pBt!=0 );
46578   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46579   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
46580   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
46581   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
46582
46583   if( !pPage->isInit ){
46584     u16 pc;            /* Address of a freeblock within pPage->aData[] */
46585     u8 hdr;            /* Offset to beginning of page header */
46586     u8 *data;          /* Equal to pPage->aData */
46587     BtShared *pBt;        /* The main btree structure */
46588     int usableSize;    /* Amount of usable space on each page */
46589     u16 cellOffset;    /* Offset from start of page to first cell pointer */
46590     int nFree;         /* Number of unused bytes on the page */
46591     int top;           /* First byte of the cell content area */
46592     int iCellFirst;    /* First allowable cell or freeblock offset */
46593     int iCellLast;     /* Last possible cell or freeblock offset */
46594
46595     pBt = pPage->pBt;
46596
46597     hdr = pPage->hdrOffset;
46598     data = pPage->aData;
46599     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
46600     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
46601     pPage->maskPage = (u16)(pBt->pageSize - 1);
46602     pPage->nOverflow = 0;
46603     usableSize = pBt->usableSize;
46604     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
46605     top = get2byteNotZero(&data[hdr+5]);
46606     pPage->nCell = get2byte(&data[hdr+3]);
46607     if( pPage->nCell>MX_CELL(pBt) ){
46608       /* To many cells for a single page.  The page must be corrupt */
46609       return SQLITE_CORRUPT_BKPT;
46610     }
46611     testcase( pPage->nCell==MX_CELL(pBt) );
46612
46613     /* A malformed database page might cause us to read past the end
46614     ** of page when parsing a cell.  
46615     **
46616     ** The following block of code checks early to see if a cell extends
46617     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
46618     ** returned if it does.
46619     */
46620     iCellFirst = cellOffset + 2*pPage->nCell;
46621     iCellLast = usableSize - 4;
46622 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
46623     {
46624       int i;            /* Index into the cell pointer array */
46625       int sz;           /* Size of a cell */
46626
46627       if( !pPage->leaf ) iCellLast--;
46628       for(i=0; i<pPage->nCell; i++){
46629         pc = get2byte(&data[cellOffset+i*2]);
46630         testcase( pc==iCellFirst );
46631         testcase( pc==iCellLast );
46632         if( pc<iCellFirst || pc>iCellLast ){
46633           return SQLITE_CORRUPT_BKPT;
46634         }
46635         sz = cellSizePtr(pPage, &data[pc]);
46636         testcase( pc+sz==usableSize );
46637         if( pc+sz>usableSize ){
46638           return SQLITE_CORRUPT_BKPT;
46639         }
46640       }
46641       if( !pPage->leaf ) iCellLast++;
46642     }  
46643 #endif
46644
46645     /* Compute the total free space on the page */
46646     pc = get2byte(&data[hdr+1]);
46647     nFree = data[hdr+7] + top;
46648     while( pc>0 ){
46649       u16 next, size;
46650       if( pc<iCellFirst || pc>iCellLast ){
46651         /* Start of free block is off the page */
46652         return SQLITE_CORRUPT_BKPT; 
46653       }
46654       next = get2byte(&data[pc]);
46655       size = get2byte(&data[pc+2]);
46656       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
46657         /* Free blocks must be in ascending order. And the last byte of
46658         ** the free-block must lie on the database page.  */
46659         return SQLITE_CORRUPT_BKPT; 
46660       }
46661       nFree = nFree + size;
46662       pc = next;
46663     }
46664
46665     /* At this point, nFree contains the sum of the offset to the start
46666     ** of the cell-content area plus the number of free bytes within
46667     ** the cell-content area. If this is greater than the usable-size
46668     ** of the page, then the page must be corrupted. This check also
46669     ** serves to verify that the offset to the start of the cell-content
46670     ** area, according to the page header, lies within the page.
46671     */
46672     if( nFree>usableSize ){
46673       return SQLITE_CORRUPT_BKPT; 
46674     }
46675     pPage->nFree = (u16)(nFree - iCellFirst);
46676     pPage->isInit = 1;
46677   }
46678   return SQLITE_OK;
46679 }
46680
46681 /*
46682 ** Set up a raw page so that it looks like a database page holding
46683 ** no entries.
46684 */
46685 static void zeroPage(MemPage *pPage, int flags){
46686   unsigned char *data = pPage->aData;
46687   BtShared *pBt = pPage->pBt;
46688   u8 hdr = pPage->hdrOffset;
46689   u16 first;
46690
46691   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
46692   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
46693   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
46694   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
46695   assert( sqlite3_mutex_held(pBt->mutex) );
46696   if( pBt->secureDelete ){
46697     memset(&data[hdr], 0, pBt->usableSize - hdr);
46698   }
46699   data[hdr] = (char)flags;
46700   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
46701   memset(&data[hdr+1], 0, 4);
46702   data[hdr+7] = 0;
46703   put2byte(&data[hdr+5], pBt->usableSize);
46704   pPage->nFree = (u16)(pBt->usableSize - first);
46705   decodeFlags(pPage, flags);
46706   pPage->hdrOffset = hdr;
46707   pPage->cellOffset = first;
46708   pPage->nOverflow = 0;
46709   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
46710   pPage->maskPage = (u16)(pBt->pageSize - 1);
46711   pPage->nCell = 0;
46712   pPage->isInit = 1;
46713 }
46714
46715
46716 /*
46717 ** Convert a DbPage obtained from the pager into a MemPage used by
46718 ** the btree layer.
46719 */
46720 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
46721   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
46722   pPage->aData = sqlite3PagerGetData(pDbPage);
46723   pPage->pDbPage = pDbPage;
46724   pPage->pBt = pBt;
46725   pPage->pgno = pgno;
46726   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
46727   return pPage; 
46728 }
46729
46730 /*
46731 ** Get a page from the pager.  Initialize the MemPage.pBt and
46732 ** MemPage.aData elements if needed.
46733 **
46734 ** If the noContent flag is set, it means that we do not care about
46735 ** the content of the page at this time.  So do not go to the disk
46736 ** to fetch the content.  Just fill in the content with zeros for now.
46737 ** If in the future we call sqlite3PagerWrite() on this page, that
46738 ** means we have started to be concerned about content and the disk
46739 ** read should occur at that point.
46740 */
46741 static int btreeGetPage(
46742   BtShared *pBt,       /* The btree */
46743   Pgno pgno,           /* Number of the page to fetch */
46744   MemPage **ppPage,    /* Return the page in this parameter */
46745   int noContent        /* Do not load page content if true */
46746 ){
46747   int rc;
46748   DbPage *pDbPage;
46749
46750   assert( sqlite3_mutex_held(pBt->mutex) );
46751   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
46752   if( rc ) return rc;
46753   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
46754   return SQLITE_OK;
46755 }
46756
46757 /*
46758 ** Retrieve a page from the pager cache. If the requested page is not
46759 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
46760 ** MemPage.aData elements if needed.
46761 */
46762 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
46763   DbPage *pDbPage;
46764   assert( sqlite3_mutex_held(pBt->mutex) );
46765   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
46766   if( pDbPage ){
46767     return btreePageFromDbPage(pDbPage, pgno, pBt);
46768   }
46769   return 0;
46770 }
46771
46772 /*
46773 ** Return the size of the database file in pages. If there is any kind of
46774 ** error, return ((unsigned int)-1).
46775 */
46776 static Pgno btreePagecount(BtShared *pBt){
46777   return pBt->nPage;
46778 }
46779 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
46780   assert( sqlite3BtreeHoldsMutex(p) );
46781   assert( ((p->pBt->nPage)&0x8000000)==0 );
46782   return (int)btreePagecount(p->pBt);
46783 }
46784
46785 /*
46786 ** Get a page from the pager and initialize it.  This routine is just a
46787 ** convenience wrapper around separate calls to btreeGetPage() and 
46788 ** btreeInitPage().
46789 **
46790 ** If an error occurs, then the value *ppPage is set to is undefined. It
46791 ** may remain unchanged, or it may be set to an invalid value.
46792 */
46793 static int getAndInitPage(
46794   BtShared *pBt,          /* The database file */
46795   Pgno pgno,           /* Number of the page to get */
46796   MemPage **ppPage     /* Write the page pointer here */
46797 ){
46798   int rc;
46799   assert( sqlite3_mutex_held(pBt->mutex) );
46800
46801   if( pgno>btreePagecount(pBt) ){
46802     rc = SQLITE_CORRUPT_BKPT;
46803   }else{
46804     rc = btreeGetPage(pBt, pgno, ppPage, 0);
46805     if( rc==SQLITE_OK ){
46806       rc = btreeInitPage(*ppPage);
46807       if( rc!=SQLITE_OK ){
46808         releasePage(*ppPage);
46809       }
46810     }
46811   }
46812
46813   testcase( pgno==0 );
46814   assert( pgno!=0 || rc==SQLITE_CORRUPT );
46815   return rc;
46816 }
46817
46818 /*
46819 ** Release a MemPage.  This should be called once for each prior
46820 ** call to btreeGetPage.
46821 */
46822 static void releasePage(MemPage *pPage){
46823   if( pPage ){
46824     assert( pPage->aData );
46825     assert( pPage->pBt );
46826     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
46827     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
46828     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46829     sqlite3PagerUnref(pPage->pDbPage);
46830   }
46831 }
46832
46833 /*
46834 ** During a rollback, when the pager reloads information into the cache
46835 ** so that the cache is restored to its original state at the start of
46836 ** the transaction, for each page restored this routine is called.
46837 **
46838 ** This routine needs to reset the extra data section at the end of the
46839 ** page to agree with the restored data.
46840 */
46841 static void pageReinit(DbPage *pData){
46842   MemPage *pPage;
46843   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
46844   assert( sqlite3PagerPageRefcount(pData)>0 );
46845   if( pPage->isInit ){
46846     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
46847     pPage->isInit = 0;
46848     if( sqlite3PagerPageRefcount(pData)>1 ){
46849       /* pPage might not be a btree page;  it might be an overflow page
46850       ** or ptrmap page or a free page.  In those cases, the following
46851       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
46852       ** But no harm is done by this.  And it is very important that
46853       ** btreeInitPage() be called on every btree page so we make
46854       ** the call for every page that comes in for re-initing. */
46855       btreeInitPage(pPage);
46856     }
46857   }
46858 }
46859
46860 /*
46861 ** Invoke the busy handler for a btree.
46862 */
46863 static int btreeInvokeBusyHandler(void *pArg){
46864   BtShared *pBt = (BtShared*)pArg;
46865   assert( pBt->db );
46866   assert( sqlite3_mutex_held(pBt->db->mutex) );
46867   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
46868 }
46869
46870 /*
46871 ** Open a database file.
46872 ** 
46873 ** zFilename is the name of the database file.  If zFilename is NULL
46874 ** then an ephemeral database is created.  The ephemeral database might
46875 ** be exclusively in memory, or it might use a disk-based memory cache.
46876 ** Either way, the ephemeral database will be automatically deleted 
46877 ** when sqlite3BtreeClose() is called.
46878 **
46879 ** If zFilename is ":memory:" then an in-memory database is created
46880 ** that is automatically destroyed when it is closed.
46881 **
46882 ** The "flags" parameter is a bitmask that might contain bits
46883 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
46884 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
46885 ** These flags are passed through into sqlite3PagerOpen() and must
46886 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
46887 **
46888 ** If the database is already opened in the same database connection
46889 ** and we are in shared cache mode, then the open will fail with an
46890 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
46891 ** objects in the same database connection since doing so will lead
46892 ** to problems with locking.
46893 */
46894 SQLITE_PRIVATE int sqlite3BtreeOpen(
46895   const char *zFilename,  /* Name of the file containing the BTree database */
46896   sqlite3 *db,            /* Associated database handle */
46897   Btree **ppBtree,        /* Pointer to new Btree object written here */
46898   int flags,              /* Options */
46899   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
46900 ){
46901   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
46902   BtShared *pBt = 0;             /* Shared part of btree structure */
46903   Btree *p;                      /* Handle to return */
46904   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
46905   int rc = SQLITE_OK;            /* Result code from this function */
46906   u8 nReserve;                   /* Byte of unused space on each page */
46907   unsigned char zDbHeader[100];  /* Database header content */
46908
46909   /* True if opening an ephemeral, temporary database */
46910   const int isTempDb = zFilename==0 || zFilename[0]==0;
46911
46912   /* Set the variable isMemdb to true for an in-memory database, or 
46913   ** false for a file-based database.
46914   */
46915 #ifdef SQLITE_OMIT_MEMORYDB
46916   const int isMemdb = 0;
46917 #else
46918   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
46919                        || (isTempDb && sqlite3TempInMemory(db));
46920 #endif
46921
46922   assert( db!=0 );
46923   assert( sqlite3_mutex_held(db->mutex) );
46924   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
46925
46926   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
46927   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
46928
46929   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
46930   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
46931
46932   if( db->flags & SQLITE_NoReadlock ){
46933     flags |= BTREE_NO_READLOCK;
46934   }
46935   if( isMemdb ){
46936     flags |= BTREE_MEMORY;
46937   }
46938   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
46939     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
46940   }
46941   pVfs = db->pVfs;
46942   p = sqlite3MallocZero(sizeof(Btree));
46943   if( !p ){
46944     return SQLITE_NOMEM;
46945   }
46946   p->inTrans = TRANS_NONE;
46947   p->db = db;
46948 #ifndef SQLITE_OMIT_SHARED_CACHE
46949   p->lock.pBtree = p;
46950   p->lock.iTable = 1;
46951 #endif
46952
46953 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
46954   /*
46955   ** If this Btree is a candidate for shared cache, try to find an
46956   ** existing BtShared object that we can share with
46957   */
46958   if( isMemdb==0 && isTempDb==0 ){
46959     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
46960       int nFullPathname = pVfs->mxPathname+1;
46961       char *zFullPathname = sqlite3Malloc(nFullPathname);
46962       sqlite3_mutex *mutexShared;
46963       p->sharable = 1;
46964       if( !zFullPathname ){
46965         sqlite3_free(p);
46966         return SQLITE_NOMEM;
46967       }
46968       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
46969       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
46970       sqlite3_mutex_enter(mutexOpen);
46971       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
46972       sqlite3_mutex_enter(mutexShared);
46973       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
46974         assert( pBt->nRef>0 );
46975         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
46976                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
46977           int iDb;
46978           for(iDb=db->nDb-1; iDb>=0; iDb--){
46979             Btree *pExisting = db->aDb[iDb].pBt;
46980             if( pExisting && pExisting->pBt==pBt ){
46981               sqlite3_mutex_leave(mutexShared);
46982               sqlite3_mutex_leave(mutexOpen);
46983               sqlite3_free(zFullPathname);
46984               sqlite3_free(p);
46985               return SQLITE_CONSTRAINT;
46986             }
46987           }
46988           p->pBt = pBt;
46989           pBt->nRef++;
46990           break;
46991         }
46992       }
46993       sqlite3_mutex_leave(mutexShared);
46994       sqlite3_free(zFullPathname);
46995     }
46996 #ifdef SQLITE_DEBUG
46997     else{
46998       /* In debug mode, we mark all persistent databases as sharable
46999       ** even when they are not.  This exercises the locking code and
47000       ** gives more opportunity for asserts(sqlite3_mutex_held())
47001       ** statements to find locking problems.
47002       */
47003       p->sharable = 1;
47004     }
47005 #endif
47006   }
47007 #endif
47008   if( pBt==0 ){
47009     /*
47010     ** The following asserts make sure that structures used by the btree are
47011     ** the right size.  This is to guard against size changes that result
47012     ** when compiling on a different architecture.
47013     */
47014     assert( sizeof(i64)==8 || sizeof(i64)==4 );
47015     assert( sizeof(u64)==8 || sizeof(u64)==4 );
47016     assert( sizeof(u32)==4 );
47017     assert( sizeof(u16)==2 );
47018     assert( sizeof(Pgno)==4 );
47019   
47020     pBt = sqlite3MallocZero( sizeof(*pBt) );
47021     if( pBt==0 ){
47022       rc = SQLITE_NOMEM;
47023       goto btree_open_out;
47024     }
47025     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
47026                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
47027     if( rc==SQLITE_OK ){
47028       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
47029     }
47030     if( rc!=SQLITE_OK ){
47031       goto btree_open_out;
47032     }
47033     pBt->openFlags = (u8)flags;
47034     pBt->db = db;
47035     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
47036     p->pBt = pBt;
47037   
47038     pBt->pCursor = 0;
47039     pBt->pPage1 = 0;
47040     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
47041 #ifdef SQLITE_SECURE_DELETE
47042     pBt->secureDelete = 1;
47043 #endif
47044     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
47045     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
47046          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
47047       pBt->pageSize = 0;
47048 #ifndef SQLITE_OMIT_AUTOVACUUM
47049       /* If the magic name ":memory:" will create an in-memory database, then
47050       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
47051       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
47052       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
47053       ** regular file-name. In this case the auto-vacuum applies as per normal.
47054       */
47055       if( zFilename && !isMemdb ){
47056         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
47057         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
47058       }
47059 #endif
47060       nReserve = 0;
47061     }else{
47062       nReserve = zDbHeader[20];
47063       pBt->pageSizeFixed = 1;
47064 #ifndef SQLITE_OMIT_AUTOVACUUM
47065       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
47066       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
47067 #endif
47068     }
47069     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
47070     if( rc ) goto btree_open_out;
47071     pBt->usableSize = pBt->pageSize - nReserve;
47072     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
47073    
47074 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
47075     /* Add the new BtShared object to the linked list sharable BtShareds.
47076     */
47077     if( p->sharable ){
47078       sqlite3_mutex *mutexShared;
47079       pBt->nRef = 1;
47080       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
47081       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
47082         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
47083         if( pBt->mutex==0 ){
47084           rc = SQLITE_NOMEM;
47085           db->mallocFailed = 0;
47086           goto btree_open_out;
47087         }
47088       }
47089       sqlite3_mutex_enter(mutexShared);
47090       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
47091       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
47092       sqlite3_mutex_leave(mutexShared);
47093     }
47094 #endif
47095   }
47096
47097 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
47098   /* If the new Btree uses a sharable pBtShared, then link the new
47099   ** Btree into the list of all sharable Btrees for the same connection.
47100   ** The list is kept in ascending order by pBt address.
47101   */
47102   if( p->sharable ){
47103     int i;
47104     Btree *pSib;
47105     for(i=0; i<db->nDb; i++){
47106       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
47107         while( pSib->pPrev ){ pSib = pSib->pPrev; }
47108         if( p->pBt<pSib->pBt ){
47109           p->pNext = pSib;
47110           p->pPrev = 0;
47111           pSib->pPrev = p;
47112         }else{
47113           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
47114             pSib = pSib->pNext;
47115           }
47116           p->pNext = pSib->pNext;
47117           p->pPrev = pSib;
47118           if( p->pNext ){
47119             p->pNext->pPrev = p;
47120           }
47121           pSib->pNext = p;
47122         }
47123         break;
47124       }
47125     }
47126   }
47127 #endif
47128   *ppBtree = p;
47129
47130 btree_open_out:
47131   if( rc!=SQLITE_OK ){
47132     if( pBt && pBt->pPager ){
47133       sqlite3PagerClose(pBt->pPager);
47134     }
47135     sqlite3_free(pBt);
47136     sqlite3_free(p);
47137     *ppBtree = 0;
47138   }else{
47139     /* If the B-Tree was successfully opened, set the pager-cache size to the
47140     ** default value. Except, when opening on an existing shared pager-cache,
47141     ** do not change the pager-cache size.
47142     */
47143     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
47144       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
47145     }
47146   }
47147   if( mutexOpen ){
47148     assert( sqlite3_mutex_held(mutexOpen) );
47149     sqlite3_mutex_leave(mutexOpen);
47150   }
47151   return rc;
47152 }
47153
47154 /*
47155 ** Decrement the BtShared.nRef counter.  When it reaches zero,
47156 ** remove the BtShared structure from the sharing list.  Return
47157 ** true if the BtShared.nRef counter reaches zero and return
47158 ** false if it is still positive.
47159 */
47160 static int removeFromSharingList(BtShared *pBt){
47161 #ifndef SQLITE_OMIT_SHARED_CACHE
47162   sqlite3_mutex *pMaster;
47163   BtShared *pList;
47164   int removed = 0;
47165
47166   assert( sqlite3_mutex_notheld(pBt->mutex) );
47167   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
47168   sqlite3_mutex_enter(pMaster);
47169   pBt->nRef--;
47170   if( pBt->nRef<=0 ){
47171     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
47172       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
47173     }else{
47174       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
47175       while( ALWAYS(pList) && pList->pNext!=pBt ){
47176         pList=pList->pNext;
47177       }
47178       if( ALWAYS(pList) ){
47179         pList->pNext = pBt->pNext;
47180       }
47181     }
47182     if( SQLITE_THREADSAFE ){
47183       sqlite3_mutex_free(pBt->mutex);
47184     }
47185     removed = 1;
47186   }
47187   sqlite3_mutex_leave(pMaster);
47188   return removed;
47189 #else
47190   return 1;
47191 #endif
47192 }
47193
47194 /*
47195 ** Make sure pBt->pTmpSpace points to an allocation of 
47196 ** MX_CELL_SIZE(pBt) bytes.
47197 */
47198 static void allocateTempSpace(BtShared *pBt){
47199   if( !pBt->pTmpSpace ){
47200     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
47201   }
47202 }
47203
47204 /*
47205 ** Free the pBt->pTmpSpace allocation
47206 */
47207 static void freeTempSpace(BtShared *pBt){
47208   sqlite3PageFree( pBt->pTmpSpace);
47209   pBt->pTmpSpace = 0;
47210 }
47211
47212 /*
47213 ** Close an open database and invalidate all cursors.
47214 */
47215 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
47216   BtShared *pBt = p->pBt;
47217   BtCursor *pCur;
47218
47219   /* Close all cursors opened via this handle.  */
47220   assert( sqlite3_mutex_held(p->db->mutex) );
47221   sqlite3BtreeEnter(p);
47222   pCur = pBt->pCursor;
47223   while( pCur ){
47224     BtCursor *pTmp = pCur;
47225     pCur = pCur->pNext;
47226     if( pTmp->pBtree==p ){
47227       sqlite3BtreeCloseCursor(pTmp);
47228     }
47229   }
47230
47231   /* Rollback any active transaction and free the handle structure.
47232   ** The call to sqlite3BtreeRollback() drops any table-locks held by
47233   ** this handle.
47234   */
47235   sqlite3BtreeRollback(p);
47236   sqlite3BtreeLeave(p);
47237
47238   /* If there are still other outstanding references to the shared-btree
47239   ** structure, return now. The remainder of this procedure cleans 
47240   ** up the shared-btree.
47241   */
47242   assert( p->wantToLock==0 && p->locked==0 );
47243   if( !p->sharable || removeFromSharingList(pBt) ){
47244     /* The pBt is no longer on the sharing list, so we can access
47245     ** it without having to hold the mutex.
47246     **
47247     ** Clean out and delete the BtShared object.
47248     */
47249     assert( !pBt->pCursor );
47250     sqlite3PagerClose(pBt->pPager);
47251     if( pBt->xFreeSchema && pBt->pSchema ){
47252       pBt->xFreeSchema(pBt->pSchema);
47253     }
47254     sqlite3DbFree(0, pBt->pSchema);
47255     freeTempSpace(pBt);
47256     sqlite3_free(pBt);
47257   }
47258
47259 #ifndef SQLITE_OMIT_SHARED_CACHE
47260   assert( p->wantToLock==0 );
47261   assert( p->locked==0 );
47262   if( p->pPrev ) p->pPrev->pNext = p->pNext;
47263   if( p->pNext ) p->pNext->pPrev = p->pPrev;
47264 #endif
47265
47266   sqlite3_free(p);
47267   return SQLITE_OK;
47268 }
47269
47270 /*
47271 ** Change the limit on the number of pages allowed in the cache.
47272 **
47273 ** The maximum number of cache pages is set to the absolute
47274 ** value of mxPage.  If mxPage is negative, the pager will
47275 ** operate asynchronously - it will not stop to do fsync()s
47276 ** to insure data is written to the disk surface before
47277 ** continuing.  Transactions still work if synchronous is off,
47278 ** and the database cannot be corrupted if this program
47279 ** crashes.  But if the operating system crashes or there is
47280 ** an abrupt power failure when synchronous is off, the database
47281 ** could be left in an inconsistent and unrecoverable state.
47282 ** Synchronous is on by default so database corruption is not
47283 ** normally a worry.
47284 */
47285 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
47286   BtShared *pBt = p->pBt;
47287   assert( sqlite3_mutex_held(p->db->mutex) );
47288   sqlite3BtreeEnter(p);
47289   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
47290   sqlite3BtreeLeave(p);
47291   return SQLITE_OK;
47292 }
47293
47294 /*
47295 ** Change the way data is synced to disk in order to increase or decrease
47296 ** how well the database resists damage due to OS crashes and power
47297 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
47298 ** there is a high probability of damage)  Level 2 is the default.  There
47299 ** is a very low but non-zero probability of damage.  Level 3 reduces the
47300 ** probability of damage to near zero but with a write performance reduction.
47301 */
47302 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
47303 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
47304   Btree *p,              /* The btree to set the safety level on */
47305   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
47306   int fullSync,          /* PRAGMA fullfsync. */
47307   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
47308 ){
47309   BtShared *pBt = p->pBt;
47310   assert( sqlite3_mutex_held(p->db->mutex) );
47311   assert( level>=1 && level<=3 );
47312   sqlite3BtreeEnter(p);
47313   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
47314   sqlite3BtreeLeave(p);
47315   return SQLITE_OK;
47316 }
47317 #endif
47318
47319 /*
47320 ** Return TRUE if the given btree is set to safety level 1.  In other
47321 ** words, return TRUE if no sync() occurs on the disk files.
47322 */
47323 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
47324   BtShared *pBt = p->pBt;
47325   int rc;
47326   assert( sqlite3_mutex_held(p->db->mutex) );  
47327   sqlite3BtreeEnter(p);
47328   assert( pBt && pBt->pPager );
47329   rc = sqlite3PagerNosync(pBt->pPager);
47330   sqlite3BtreeLeave(p);
47331   return rc;
47332 }
47333
47334 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
47335 /*
47336 ** Change the default pages size and the number of reserved bytes per page.
47337 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
47338 ** without changing anything.
47339 **
47340 ** The page size must be a power of 2 between 512 and 65536.  If the page
47341 ** size supplied does not meet this constraint then the page size is not
47342 ** changed.
47343 **
47344 ** Page sizes are constrained to be a power of two so that the region
47345 ** of the database file used for locking (beginning at PENDING_BYTE,
47346 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
47347 ** at the beginning of a page.
47348 **
47349 ** If parameter nReserve is less than zero, then the number of reserved
47350 ** bytes per page is left unchanged.
47351 **
47352 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
47353 ** and autovacuum mode can no longer be changed.
47354 */
47355 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
47356   int rc = SQLITE_OK;
47357   BtShared *pBt = p->pBt;
47358   assert( nReserve>=-1 && nReserve<=255 );
47359   sqlite3BtreeEnter(p);
47360   if( pBt->pageSizeFixed ){
47361     sqlite3BtreeLeave(p);
47362     return SQLITE_READONLY;
47363   }
47364   if( nReserve<0 ){
47365     nReserve = pBt->pageSize - pBt->usableSize;
47366   }
47367   assert( nReserve>=0 && nReserve<=255 );
47368   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
47369         ((pageSize-1)&pageSize)==0 ){
47370     assert( (pageSize & 7)==0 );
47371     assert( !pBt->pPage1 && !pBt->pCursor );
47372     pBt->pageSize = (u32)pageSize;
47373     freeTempSpace(pBt);
47374   }
47375   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
47376   pBt->usableSize = pBt->pageSize - (u16)nReserve;
47377   if( iFix ) pBt->pageSizeFixed = 1;
47378   sqlite3BtreeLeave(p);
47379   return rc;
47380 }
47381
47382 /*
47383 ** Return the currently defined page size
47384 */
47385 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
47386   return p->pBt->pageSize;
47387 }
47388
47389 /*
47390 ** Return the number of bytes of space at the end of every page that
47391 ** are intentually left unused.  This is the "reserved" space that is
47392 ** sometimes used by extensions.
47393 */
47394 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
47395   int n;
47396   sqlite3BtreeEnter(p);
47397   n = p->pBt->pageSize - p->pBt->usableSize;
47398   sqlite3BtreeLeave(p);
47399   return n;
47400 }
47401
47402 /*
47403 ** Set the maximum page count for a database if mxPage is positive.
47404 ** No changes are made if mxPage is 0 or negative.
47405 ** Regardless of the value of mxPage, return the maximum page count.
47406 */
47407 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
47408   int n;
47409   sqlite3BtreeEnter(p);
47410   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
47411   sqlite3BtreeLeave(p);
47412   return n;
47413 }
47414
47415 /*
47416 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
47417 ** then make no changes.  Always return the value of the secureDelete
47418 ** setting after the change.
47419 */
47420 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
47421   int b;
47422   if( p==0 ) return 0;
47423   sqlite3BtreeEnter(p);
47424   if( newFlag>=0 ){
47425     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
47426   } 
47427   b = p->pBt->secureDelete;
47428   sqlite3BtreeLeave(p);
47429   return b;
47430 }
47431 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
47432
47433 /*
47434 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
47435 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
47436 ** is disabled. The default value for the auto-vacuum property is 
47437 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
47438 */
47439 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
47440 #ifdef SQLITE_OMIT_AUTOVACUUM
47441   return SQLITE_READONLY;
47442 #else
47443   BtShared *pBt = p->pBt;
47444   int rc = SQLITE_OK;
47445   u8 av = (u8)autoVacuum;
47446
47447   sqlite3BtreeEnter(p);
47448   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
47449     rc = SQLITE_READONLY;
47450   }else{
47451     pBt->autoVacuum = av ?1:0;
47452     pBt->incrVacuum = av==2 ?1:0;
47453   }
47454   sqlite3BtreeLeave(p);
47455   return rc;
47456 #endif
47457 }
47458
47459 /*
47460 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
47461 ** enabled 1 is returned. Otherwise 0.
47462 */
47463 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
47464 #ifdef SQLITE_OMIT_AUTOVACUUM
47465   return BTREE_AUTOVACUUM_NONE;
47466 #else
47467   int rc;
47468   sqlite3BtreeEnter(p);
47469   rc = (
47470     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
47471     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
47472     BTREE_AUTOVACUUM_INCR
47473   );
47474   sqlite3BtreeLeave(p);
47475   return rc;
47476 #endif
47477 }
47478
47479
47480 /*
47481 ** Get a reference to pPage1 of the database file.  This will
47482 ** also acquire a readlock on that file.
47483 **
47484 ** SQLITE_OK is returned on success.  If the file is not a
47485 ** well-formed database file, then SQLITE_CORRUPT is returned.
47486 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
47487 ** is returned if we run out of memory. 
47488 */
47489 static int lockBtree(BtShared *pBt){
47490   int rc;              /* Result code from subfunctions */
47491   MemPage *pPage1;     /* Page 1 of the database file */
47492   int nPage;           /* Number of pages in the database */
47493   int nPageFile = 0;   /* Number of pages in the database file */
47494   int nPageHeader;     /* Number of pages in the database according to hdr */
47495
47496   assert( sqlite3_mutex_held(pBt->mutex) );
47497   assert( pBt->pPage1==0 );
47498   rc = sqlite3PagerSharedLock(pBt->pPager);
47499   if( rc!=SQLITE_OK ) return rc;
47500   rc = btreeGetPage(pBt, 1, &pPage1, 0);
47501   if( rc!=SQLITE_OK ) return rc;
47502
47503   /* Do some checking to help insure the file we opened really is
47504   ** a valid database file. 
47505   */
47506   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
47507   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
47508   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
47509     nPage = nPageFile;
47510   }
47511   if( nPage>0 ){
47512     u32 pageSize;
47513     u32 usableSize;
47514     u8 *page1 = pPage1->aData;
47515     rc = SQLITE_NOTADB;
47516     if( memcmp(page1, zMagicHeader, 16)!=0 ){
47517       goto page1_init_failed;
47518     }
47519
47520 #ifdef SQLITE_OMIT_WAL
47521     if( page1[18]>1 ){
47522       pBt->readOnly = 1;
47523     }
47524     if( page1[19]>1 ){
47525       goto page1_init_failed;
47526     }
47527 #else
47528     if( page1[18]>2 ){
47529       pBt->readOnly = 1;
47530     }
47531     if( page1[19]>2 ){
47532       goto page1_init_failed;
47533     }
47534
47535     /* If the write version is set to 2, this database should be accessed
47536     ** in WAL mode. If the log is not already open, open it now. Then 
47537     ** return SQLITE_OK and return without populating BtShared.pPage1.
47538     ** The caller detects this and calls this function again. This is
47539     ** required as the version of page 1 currently in the page1 buffer
47540     ** may not be the latest version - there may be a newer one in the log
47541     ** file.
47542     */
47543     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
47544       int isOpen = 0;
47545       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
47546       if( rc!=SQLITE_OK ){
47547         goto page1_init_failed;
47548       }else if( isOpen==0 ){
47549         releasePage(pPage1);
47550         return SQLITE_OK;
47551       }
47552       rc = SQLITE_NOTADB;
47553     }
47554 #endif
47555
47556     /* The maximum embedded fraction must be exactly 25%.  And the minimum
47557     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
47558     ** The original design allowed these amounts to vary, but as of
47559     ** version 3.6.0, we require them to be fixed.
47560     */
47561     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
47562       goto page1_init_failed;
47563     }
47564     pageSize = (page1[16]<<8) | (page1[17]<<16);
47565     if( ((pageSize-1)&pageSize)!=0
47566      || pageSize>SQLITE_MAX_PAGE_SIZE 
47567      || pageSize<=256 
47568     ){
47569       goto page1_init_failed;
47570     }
47571     assert( (pageSize & 7)==0 );
47572     usableSize = pageSize - page1[20];
47573     if( (u32)pageSize!=pBt->pageSize ){
47574       /* After reading the first page of the database assuming a page size
47575       ** of BtShared.pageSize, we have discovered that the page-size is
47576       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
47577       ** zero and return SQLITE_OK. The caller will call this function
47578       ** again with the correct page-size.
47579       */
47580       releasePage(pPage1);
47581       pBt->usableSize = usableSize;
47582       pBt->pageSize = pageSize;
47583       freeTempSpace(pBt);
47584       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
47585                                    pageSize-usableSize);
47586       return rc;
47587     }
47588     if( nPageHeader>nPageFile ){
47589       rc = SQLITE_CORRUPT_BKPT;
47590       goto page1_init_failed;
47591     }
47592     if( usableSize<480 ){
47593       goto page1_init_failed;
47594     }
47595     pBt->pageSize = pageSize;
47596     pBt->usableSize = usableSize;
47597 #ifndef SQLITE_OMIT_AUTOVACUUM
47598     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
47599     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
47600 #endif
47601   }
47602
47603   /* maxLocal is the maximum amount of payload to store locally for
47604   ** a cell.  Make sure it is small enough so that at least minFanout
47605   ** cells can will fit on one page.  We assume a 10-byte page header.
47606   ** Besides the payload, the cell must store:
47607   **     2-byte pointer to the cell
47608   **     4-byte child pointer
47609   **     9-byte nKey value
47610   **     4-byte nData value
47611   **     4-byte overflow page pointer
47612   ** So a cell consists of a 2-byte pointer, a header which is as much as
47613   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
47614   ** page pointer.
47615   */
47616   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
47617   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
47618   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
47619   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
47620   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
47621   pBt->pPage1 = pPage1;
47622   pBt->nPage = nPage;
47623   return SQLITE_OK;
47624
47625 page1_init_failed:
47626   releasePage(pPage1);
47627   pBt->pPage1 = 0;
47628   return rc;
47629 }
47630
47631 /*
47632 ** If there are no outstanding cursors and we are not in the middle
47633 ** of a transaction but there is a read lock on the database, then
47634 ** this routine unrefs the first page of the database file which 
47635 ** has the effect of releasing the read lock.
47636 **
47637 ** If there is a transaction in progress, this routine is a no-op.
47638 */
47639 static void unlockBtreeIfUnused(BtShared *pBt){
47640   assert( sqlite3_mutex_held(pBt->mutex) );
47641   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
47642   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
47643     assert( pBt->pPage1->aData );
47644     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
47645     assert( pBt->pPage1->aData );
47646     releasePage(pBt->pPage1);
47647     pBt->pPage1 = 0;
47648   }
47649 }
47650
47651 /*
47652 ** If pBt points to an empty file then convert that empty file
47653 ** into a new empty database by initializing the first page of
47654 ** the database.
47655 */
47656 static int newDatabase(BtShared *pBt){
47657   MemPage *pP1;
47658   unsigned char *data;
47659   int rc;
47660
47661   assert( sqlite3_mutex_held(pBt->mutex) );
47662   if( pBt->nPage>0 ){
47663     return SQLITE_OK;
47664   }
47665   pP1 = pBt->pPage1;
47666   assert( pP1!=0 );
47667   data = pP1->aData;
47668   rc = sqlite3PagerWrite(pP1->pDbPage);
47669   if( rc ) return rc;
47670   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
47671   assert( sizeof(zMagicHeader)==16 );
47672   data[16] = (u8)((pBt->pageSize>>8)&0xff);
47673   data[17] = (u8)((pBt->pageSize>>16)&0xff);
47674   data[18] = 1;
47675   data[19] = 1;
47676   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
47677   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
47678   data[21] = 64;
47679   data[22] = 32;
47680   data[23] = 32;
47681   memset(&data[24], 0, 100-24);
47682   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
47683   pBt->pageSizeFixed = 1;
47684 #ifndef SQLITE_OMIT_AUTOVACUUM
47685   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
47686   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
47687   put4byte(&data[36 + 4*4], pBt->autoVacuum);
47688   put4byte(&data[36 + 7*4], pBt->incrVacuum);
47689 #endif
47690   pBt->nPage = 1;
47691   data[31] = 1;
47692   return SQLITE_OK;
47693 }
47694
47695 /*
47696 ** Attempt to start a new transaction. A write-transaction
47697 ** is started if the second argument is nonzero, otherwise a read-
47698 ** transaction.  If the second argument is 2 or more and exclusive
47699 ** transaction is started, meaning that no other process is allowed
47700 ** to access the database.  A preexisting transaction may not be
47701 ** upgraded to exclusive by calling this routine a second time - the
47702 ** exclusivity flag only works for a new transaction.
47703 **
47704 ** A write-transaction must be started before attempting any 
47705 ** changes to the database.  None of the following routines 
47706 ** will work unless a transaction is started first:
47707 **
47708 **      sqlite3BtreeCreateTable()
47709 **      sqlite3BtreeCreateIndex()
47710 **      sqlite3BtreeClearTable()
47711 **      sqlite3BtreeDropTable()
47712 **      sqlite3BtreeInsert()
47713 **      sqlite3BtreeDelete()
47714 **      sqlite3BtreeUpdateMeta()
47715 **
47716 ** If an initial attempt to acquire the lock fails because of lock contention
47717 ** and the database was previously unlocked, then invoke the busy handler
47718 ** if there is one.  But if there was previously a read-lock, do not
47719 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
47720 ** returned when there is already a read-lock in order to avoid a deadlock.
47721 **
47722 ** Suppose there are two processes A and B.  A has a read lock and B has
47723 ** a reserved lock.  B tries to promote to exclusive but is blocked because
47724 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
47725 ** One or the other of the two processes must give way or there can be
47726 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
47727 ** when A already has a read lock, we encourage A to give up and let B
47728 ** proceed.
47729 */
47730 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
47731   sqlite3 *pBlock = 0;
47732   BtShared *pBt = p->pBt;
47733   int rc = SQLITE_OK;
47734
47735   sqlite3BtreeEnter(p);
47736   btreeIntegrity(p);
47737
47738   /* If the btree is already in a write-transaction, or it
47739   ** is already in a read-transaction and a read-transaction
47740   ** is requested, this is a no-op.
47741   */
47742   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
47743     goto trans_begun;
47744   }
47745
47746   /* Write transactions are not possible on a read-only database */
47747   if( pBt->readOnly && wrflag ){
47748     rc = SQLITE_READONLY;
47749     goto trans_begun;
47750   }
47751
47752 #ifndef SQLITE_OMIT_SHARED_CACHE
47753   /* If another database handle has already opened a write transaction 
47754   ** on this shared-btree structure and a second write transaction is
47755   ** requested, return SQLITE_LOCKED.
47756   */
47757   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
47758     pBlock = pBt->pWriter->db;
47759   }else if( wrflag>1 ){
47760     BtLock *pIter;
47761     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
47762       if( pIter->pBtree!=p ){
47763         pBlock = pIter->pBtree->db;
47764         break;
47765       }
47766     }
47767   }
47768   if( pBlock ){
47769     sqlite3ConnectionBlocked(p->db, pBlock);
47770     rc = SQLITE_LOCKED_SHAREDCACHE;
47771     goto trans_begun;
47772   }
47773 #endif
47774
47775   /* Any read-only or read-write transaction implies a read-lock on 
47776   ** page 1. So if some other shared-cache client already has a write-lock 
47777   ** on page 1, the transaction cannot be opened. */
47778   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
47779   if( SQLITE_OK!=rc ) goto trans_begun;
47780
47781   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
47782   do {
47783     /* Call lockBtree() until either pBt->pPage1 is populated or
47784     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
47785     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
47786     ** reading page 1 it discovers that the page-size of the database 
47787     ** file is not pBt->pageSize. In this case lockBtree() will update
47788     ** pBt->pageSize to the page-size of the file on disk.
47789     */
47790     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
47791
47792     if( rc==SQLITE_OK && wrflag ){
47793       if( pBt->readOnly ){
47794         rc = SQLITE_READONLY;
47795       }else{
47796         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
47797         if( rc==SQLITE_OK ){
47798           rc = newDatabase(pBt);
47799         }
47800       }
47801     }
47802   
47803     if( rc!=SQLITE_OK ){
47804       unlockBtreeIfUnused(pBt);
47805     }
47806   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
47807           btreeInvokeBusyHandler(pBt) );
47808
47809   if( rc==SQLITE_OK ){
47810     if( p->inTrans==TRANS_NONE ){
47811       pBt->nTransaction++;
47812 #ifndef SQLITE_OMIT_SHARED_CACHE
47813       if( p->sharable ){
47814         assert( p->lock.pBtree==p && p->lock.iTable==1 );
47815         p->lock.eLock = READ_LOCK;
47816         p->lock.pNext = pBt->pLock;
47817         pBt->pLock = &p->lock;
47818       }
47819 #endif
47820     }
47821     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
47822     if( p->inTrans>pBt->inTransaction ){
47823       pBt->inTransaction = p->inTrans;
47824     }
47825     if( wrflag ){
47826       MemPage *pPage1 = pBt->pPage1;
47827 #ifndef SQLITE_OMIT_SHARED_CACHE
47828       assert( !pBt->pWriter );
47829       pBt->pWriter = p;
47830       pBt->isExclusive = (u8)(wrflag>1);
47831 #endif
47832
47833       /* If the db-size header field is incorrect (as it may be if an old
47834       ** client has been writing the database file), update it now. Doing
47835       ** this sooner rather than later means the database size can safely 
47836       ** re-read the database size from page 1 if a savepoint or transaction
47837       ** rollback occurs within the transaction.
47838       */
47839       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
47840         rc = sqlite3PagerWrite(pPage1->pDbPage);
47841         if( rc==SQLITE_OK ){
47842           put4byte(&pPage1->aData[28], pBt->nPage);
47843         }
47844       }
47845     }
47846   }
47847
47848
47849 trans_begun:
47850   if( rc==SQLITE_OK && wrflag ){
47851     /* This call makes sure that the pager has the correct number of
47852     ** open savepoints. If the second parameter is greater than 0 and
47853     ** the sub-journal is not already open, then it will be opened here.
47854     */
47855     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
47856   }
47857
47858   btreeIntegrity(p);
47859   sqlite3BtreeLeave(p);
47860   return rc;
47861 }
47862
47863 #ifndef SQLITE_OMIT_AUTOVACUUM
47864
47865 /*
47866 ** Set the pointer-map entries for all children of page pPage. Also, if
47867 ** pPage contains cells that point to overflow pages, set the pointer
47868 ** map entries for the overflow pages as well.
47869 */
47870 static int setChildPtrmaps(MemPage *pPage){
47871   int i;                             /* Counter variable */
47872   int nCell;                         /* Number of cells in page pPage */
47873   int rc;                            /* Return code */
47874   BtShared *pBt = pPage->pBt;
47875   u8 isInitOrig = pPage->isInit;
47876   Pgno pgno = pPage->pgno;
47877
47878   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47879   rc = btreeInitPage(pPage);
47880   if( rc!=SQLITE_OK ){
47881     goto set_child_ptrmaps_out;
47882   }
47883   nCell = pPage->nCell;
47884
47885   for(i=0; i<nCell; i++){
47886     u8 *pCell = findCell(pPage, i);
47887
47888     ptrmapPutOvflPtr(pPage, pCell, &rc);
47889
47890     if( !pPage->leaf ){
47891       Pgno childPgno = get4byte(pCell);
47892       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
47893     }
47894   }
47895
47896   if( !pPage->leaf ){
47897     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
47898     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
47899   }
47900
47901 set_child_ptrmaps_out:
47902   pPage->isInit = isInitOrig;
47903   return rc;
47904 }
47905
47906 /*
47907 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
47908 ** that it points to iTo. Parameter eType describes the type of pointer to
47909 ** be modified, as  follows:
47910 **
47911 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
47912 **                   page of pPage.
47913 **
47914 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
47915 **                   page pointed to by one of the cells on pPage.
47916 **
47917 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
47918 **                   overflow page in the list.
47919 */
47920 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
47921   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
47922   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
47923   if( eType==PTRMAP_OVERFLOW2 ){
47924     /* The pointer is always the first 4 bytes of the page in this case.  */
47925     if( get4byte(pPage->aData)!=iFrom ){
47926       return SQLITE_CORRUPT_BKPT;
47927     }
47928     put4byte(pPage->aData, iTo);
47929   }else{
47930     u8 isInitOrig = pPage->isInit;
47931     int i;
47932     int nCell;
47933
47934     btreeInitPage(pPage);
47935     nCell = pPage->nCell;
47936
47937     for(i=0; i<nCell; i++){
47938       u8 *pCell = findCell(pPage, i);
47939       if( eType==PTRMAP_OVERFLOW1 ){
47940         CellInfo info;
47941         btreeParseCellPtr(pPage, pCell, &info);
47942         if( info.iOverflow ){
47943           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
47944             put4byte(&pCell[info.iOverflow], iTo);
47945             break;
47946           }
47947         }
47948       }else{
47949         if( get4byte(pCell)==iFrom ){
47950           put4byte(pCell, iTo);
47951           break;
47952         }
47953       }
47954     }
47955   
47956     if( i==nCell ){
47957       if( eType!=PTRMAP_BTREE || 
47958           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
47959         return SQLITE_CORRUPT_BKPT;
47960       }
47961       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
47962     }
47963
47964     pPage->isInit = isInitOrig;
47965   }
47966   return SQLITE_OK;
47967 }
47968
47969
47970 /*
47971 ** Move the open database page pDbPage to location iFreePage in the 
47972 ** database. The pDbPage reference remains valid.
47973 **
47974 ** The isCommit flag indicates that there is no need to remember that
47975 ** the journal needs to be sync()ed before database page pDbPage->pgno 
47976 ** can be written to. The caller has already promised not to write to that
47977 ** page.
47978 */
47979 static int relocatePage(
47980   BtShared *pBt,           /* Btree */
47981   MemPage *pDbPage,        /* Open page to move */
47982   u8 eType,                /* Pointer map 'type' entry for pDbPage */
47983   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
47984   Pgno iFreePage,          /* The location to move pDbPage to */
47985   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
47986 ){
47987   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
47988   Pgno iDbPage = pDbPage->pgno;
47989   Pager *pPager = pBt->pPager;
47990   int rc;
47991
47992   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
47993       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
47994   assert( sqlite3_mutex_held(pBt->mutex) );
47995   assert( pDbPage->pBt==pBt );
47996
47997   /* Move page iDbPage from its current location to page number iFreePage */
47998   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
47999       iDbPage, iFreePage, iPtrPage, eType));
48000   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
48001   if( rc!=SQLITE_OK ){
48002     return rc;
48003   }
48004   pDbPage->pgno = iFreePage;
48005
48006   /* If pDbPage was a btree-page, then it may have child pages and/or cells
48007   ** that point to overflow pages. The pointer map entries for all these
48008   ** pages need to be changed.
48009   **
48010   ** If pDbPage is an overflow page, then the first 4 bytes may store a
48011   ** pointer to a subsequent overflow page. If this is the case, then
48012   ** the pointer map needs to be updated for the subsequent overflow page.
48013   */
48014   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
48015     rc = setChildPtrmaps(pDbPage);
48016     if( rc!=SQLITE_OK ){
48017       return rc;
48018     }
48019   }else{
48020     Pgno nextOvfl = get4byte(pDbPage->aData);
48021     if( nextOvfl!=0 ){
48022       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
48023       if( rc!=SQLITE_OK ){
48024         return rc;
48025       }
48026     }
48027   }
48028
48029   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
48030   ** that it points at iFreePage. Also fix the pointer map entry for
48031   ** iPtrPage.
48032   */
48033   if( eType!=PTRMAP_ROOTPAGE ){
48034     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
48035     if( rc!=SQLITE_OK ){
48036       return rc;
48037     }
48038     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
48039     if( rc!=SQLITE_OK ){
48040       releasePage(pPtrPage);
48041       return rc;
48042     }
48043     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
48044     releasePage(pPtrPage);
48045     if( rc==SQLITE_OK ){
48046       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
48047     }
48048   }
48049   return rc;
48050 }
48051
48052 /* Forward declaration required by incrVacuumStep(). */
48053 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
48054
48055 /*
48056 ** Perform a single step of an incremental-vacuum. If successful,
48057 ** return SQLITE_OK. If there is no work to do (and therefore no
48058 ** point in calling this function again), return SQLITE_DONE.
48059 **
48060 ** More specificly, this function attempts to re-organize the 
48061 ** database so that the last page of the file currently in use
48062 ** is no longer in use.
48063 **
48064 ** If the nFin parameter is non-zero, this function assumes
48065 ** that the caller will keep calling incrVacuumStep() until
48066 ** it returns SQLITE_DONE or an error, and that nFin is the
48067 ** number of pages the database file will contain after this 
48068 ** process is complete.  If nFin is zero, it is assumed that
48069 ** incrVacuumStep() will be called a finite amount of times
48070 ** which may or may not empty the freelist.  A full autovacuum
48071 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
48072 */
48073 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
48074   Pgno nFreeList;           /* Number of pages still on the free-list */
48075   int rc;
48076
48077   assert( sqlite3_mutex_held(pBt->mutex) );
48078   assert( iLastPg>nFin );
48079
48080   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
48081     u8 eType;
48082     Pgno iPtrPage;
48083
48084     nFreeList = get4byte(&pBt->pPage1->aData[36]);
48085     if( nFreeList==0 ){
48086       return SQLITE_DONE;
48087     }
48088
48089     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
48090     if( rc!=SQLITE_OK ){
48091       return rc;
48092     }
48093     if( eType==PTRMAP_ROOTPAGE ){
48094       return SQLITE_CORRUPT_BKPT;
48095     }
48096
48097     if( eType==PTRMAP_FREEPAGE ){
48098       if( nFin==0 ){
48099         /* Remove the page from the files free-list. This is not required
48100         ** if nFin is non-zero. In that case, the free-list will be
48101         ** truncated to zero after this function returns, so it doesn't 
48102         ** matter if it still contains some garbage entries.
48103         */
48104         Pgno iFreePg;
48105         MemPage *pFreePg;
48106         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
48107         if( rc!=SQLITE_OK ){
48108           return rc;
48109         }
48110         assert( iFreePg==iLastPg );
48111         releasePage(pFreePg);
48112       }
48113     } else {
48114       Pgno iFreePg;             /* Index of free page to move pLastPg to */
48115       MemPage *pLastPg;
48116
48117       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
48118       if( rc!=SQLITE_OK ){
48119         return rc;
48120       }
48121
48122       /* If nFin is zero, this loop runs exactly once and page pLastPg
48123       ** is swapped with the first free page pulled off the free list.
48124       **
48125       ** On the other hand, if nFin is greater than zero, then keep
48126       ** looping until a free-page located within the first nFin pages
48127       ** of the file is found.
48128       */
48129       do {
48130         MemPage *pFreePg;
48131         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
48132         if( rc!=SQLITE_OK ){
48133           releasePage(pLastPg);
48134           return rc;
48135         }
48136         releasePage(pFreePg);
48137       }while( nFin!=0 && iFreePg>nFin );
48138       assert( iFreePg<iLastPg );
48139       
48140       rc = sqlite3PagerWrite(pLastPg->pDbPage);
48141       if( rc==SQLITE_OK ){
48142         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
48143       }
48144       releasePage(pLastPg);
48145       if( rc!=SQLITE_OK ){
48146         return rc;
48147       }
48148     }
48149   }
48150
48151   if( nFin==0 ){
48152     iLastPg--;
48153     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
48154       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
48155         MemPage *pPg;
48156         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
48157         if( rc!=SQLITE_OK ){
48158           return rc;
48159         }
48160         rc = sqlite3PagerWrite(pPg->pDbPage);
48161         releasePage(pPg);
48162         if( rc!=SQLITE_OK ){
48163           return rc;
48164         }
48165       }
48166       iLastPg--;
48167     }
48168     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
48169     pBt->nPage = iLastPg;
48170   }
48171   return SQLITE_OK;
48172 }
48173
48174 /*
48175 ** A write-transaction must be opened before calling this function.
48176 ** It performs a single unit of work towards an incremental vacuum.
48177 **
48178 ** If the incremental vacuum is finished after this function has run,
48179 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
48180 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
48181 */
48182 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
48183   int rc;
48184   BtShared *pBt = p->pBt;
48185
48186   sqlite3BtreeEnter(p);
48187   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
48188   if( !pBt->autoVacuum ){
48189     rc = SQLITE_DONE;
48190   }else{
48191     invalidateAllOverflowCache(pBt);
48192     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
48193     if( rc==SQLITE_OK ){
48194       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
48195       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
48196     }
48197   }
48198   sqlite3BtreeLeave(p);
48199   return rc;
48200 }
48201
48202 /*
48203 ** This routine is called prior to sqlite3PagerCommit when a transaction
48204 ** is commited for an auto-vacuum database.
48205 **
48206 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
48207 ** the database file should be truncated to during the commit process. 
48208 ** i.e. the database has been reorganized so that only the first *pnTrunc
48209 ** pages are in use.
48210 */
48211 static int autoVacuumCommit(BtShared *pBt){
48212   int rc = SQLITE_OK;
48213   Pager *pPager = pBt->pPager;
48214   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
48215
48216   assert( sqlite3_mutex_held(pBt->mutex) );
48217   invalidateAllOverflowCache(pBt);
48218   assert(pBt->autoVacuum);
48219   if( !pBt->incrVacuum ){
48220     Pgno nFin;         /* Number of pages in database after autovacuuming */
48221     Pgno nFree;        /* Number of pages on the freelist initially */
48222     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
48223     Pgno iFree;        /* The next page to be freed */
48224     int nEntry;        /* Number of entries on one ptrmap page */
48225     Pgno nOrig;        /* Database size before freeing */
48226
48227     nOrig = btreePagecount(pBt);
48228     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
48229       /* It is not possible to create a database for which the final page
48230       ** is either a pointer-map page or the pending-byte page. If one
48231       ** is encountered, this indicates corruption.
48232       */
48233       return SQLITE_CORRUPT_BKPT;
48234     }
48235
48236     nFree = get4byte(&pBt->pPage1->aData[36]);
48237     nEntry = pBt->usableSize/5;
48238     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
48239     nFin = nOrig - nFree - nPtrmap;
48240     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
48241       nFin--;
48242     }
48243     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
48244       nFin--;
48245     }
48246     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
48247
48248     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
48249       rc = incrVacuumStep(pBt, nFin, iFree);
48250     }
48251     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
48252       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
48253       put4byte(&pBt->pPage1->aData[32], 0);
48254       put4byte(&pBt->pPage1->aData[36], 0);
48255       put4byte(&pBt->pPage1->aData[28], nFin);
48256       sqlite3PagerTruncateImage(pBt->pPager, nFin);
48257       pBt->nPage = nFin;
48258     }
48259     if( rc!=SQLITE_OK ){
48260       sqlite3PagerRollback(pPager);
48261     }
48262   }
48263
48264   assert( nRef==sqlite3PagerRefcount(pPager) );
48265   return rc;
48266 }
48267
48268 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
48269 # define setChildPtrmaps(x) SQLITE_OK
48270 #endif
48271
48272 /*
48273 ** This routine does the first phase of a two-phase commit.  This routine
48274 ** causes a rollback journal to be created (if it does not already exist)
48275 ** and populated with enough information so that if a power loss occurs
48276 ** the database can be restored to its original state by playing back
48277 ** the journal.  Then the contents of the journal are flushed out to
48278 ** the disk.  After the journal is safely on oxide, the changes to the
48279 ** database are written into the database file and flushed to oxide.
48280 ** At the end of this call, the rollback journal still exists on the
48281 ** disk and we are still holding all locks, so the transaction has not
48282 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
48283 ** commit process.
48284 **
48285 ** This call is a no-op if no write-transaction is currently active on pBt.
48286 **
48287 ** Otherwise, sync the database file for the btree pBt. zMaster points to
48288 ** the name of a master journal file that should be written into the
48289 ** individual journal file, or is NULL, indicating no master journal file 
48290 ** (single database transaction).
48291 **
48292 ** When this is called, the master journal should already have been
48293 ** created, populated with this journal pointer and synced to disk.
48294 **
48295 ** Once this is routine has returned, the only thing required to commit
48296 ** the write-transaction for this database file is to delete the journal.
48297 */
48298 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
48299   int rc = SQLITE_OK;
48300   if( p->inTrans==TRANS_WRITE ){
48301     BtShared *pBt = p->pBt;
48302     sqlite3BtreeEnter(p);
48303 #ifndef SQLITE_OMIT_AUTOVACUUM
48304     if( pBt->autoVacuum ){
48305       rc = autoVacuumCommit(pBt);
48306       if( rc!=SQLITE_OK ){
48307         sqlite3BtreeLeave(p);
48308         return rc;
48309       }
48310     }
48311 #endif
48312     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
48313     sqlite3BtreeLeave(p);
48314   }
48315   return rc;
48316 }
48317
48318 /*
48319 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
48320 ** at the conclusion of a transaction.
48321 */
48322 static void btreeEndTransaction(Btree *p){
48323   BtShared *pBt = p->pBt;
48324   assert( sqlite3BtreeHoldsMutex(p) );
48325
48326   btreeClearHasContent(pBt);
48327   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
48328     /* If there are other active statements that belong to this database
48329     ** handle, downgrade to a read-only transaction. The other statements
48330     ** may still be reading from the database.  */
48331     downgradeAllSharedCacheTableLocks(p);
48332     p->inTrans = TRANS_READ;
48333   }else{
48334     /* If the handle had any kind of transaction open, decrement the 
48335     ** transaction count of the shared btree. If the transaction count 
48336     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
48337     ** call below will unlock the pager.  */
48338     if( p->inTrans!=TRANS_NONE ){
48339       clearAllSharedCacheTableLocks(p);
48340       pBt->nTransaction--;
48341       if( 0==pBt->nTransaction ){
48342         pBt->inTransaction = TRANS_NONE;
48343       }
48344     }
48345
48346     /* Set the current transaction state to TRANS_NONE and unlock the 
48347     ** pager if this call closed the only read or write transaction.  */
48348     p->inTrans = TRANS_NONE;
48349     unlockBtreeIfUnused(pBt);
48350   }
48351
48352   btreeIntegrity(p);
48353 }
48354
48355 /*
48356 ** Commit the transaction currently in progress.
48357 **
48358 ** This routine implements the second phase of a 2-phase commit.  The
48359 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
48360 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
48361 ** routine did all the work of writing information out to disk and flushing the
48362 ** contents so that they are written onto the disk platter.  All this
48363 ** routine has to do is delete or truncate or zero the header in the
48364 ** the rollback journal (which causes the transaction to commit) and
48365 ** drop locks.
48366 **
48367 ** This will release the write lock on the database file.  If there
48368 ** are no active cursors, it also releases the read lock.
48369 */
48370 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
48371
48372   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
48373   sqlite3BtreeEnter(p);
48374   btreeIntegrity(p);
48375
48376   /* If the handle has a write-transaction open, commit the shared-btrees 
48377   ** transaction and set the shared state to TRANS_READ.
48378   */
48379   if( p->inTrans==TRANS_WRITE ){
48380     int rc;
48381     BtShared *pBt = p->pBt;
48382     assert( pBt->inTransaction==TRANS_WRITE );
48383     assert( pBt->nTransaction>0 );
48384     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
48385     if( rc!=SQLITE_OK ){
48386       sqlite3BtreeLeave(p);
48387       return rc;
48388     }
48389     pBt->inTransaction = TRANS_READ;
48390   }
48391
48392   btreeEndTransaction(p);
48393   sqlite3BtreeLeave(p);
48394   return SQLITE_OK;
48395 }
48396
48397 /*
48398 ** Do both phases of a commit.
48399 */
48400 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
48401   int rc;
48402   sqlite3BtreeEnter(p);
48403   rc = sqlite3BtreeCommitPhaseOne(p, 0);
48404   if( rc==SQLITE_OK ){
48405     rc = sqlite3BtreeCommitPhaseTwo(p);
48406   }
48407   sqlite3BtreeLeave(p);
48408   return rc;
48409 }
48410
48411 #ifndef NDEBUG
48412 /*
48413 ** Return the number of write-cursors open on this handle. This is for use
48414 ** in assert() expressions, so it is only compiled if NDEBUG is not
48415 ** defined.
48416 **
48417 ** For the purposes of this routine, a write-cursor is any cursor that
48418 ** is capable of writing to the databse.  That means the cursor was
48419 ** originally opened for writing and the cursor has not be disabled
48420 ** by having its state changed to CURSOR_FAULT.
48421 */
48422 static int countWriteCursors(BtShared *pBt){
48423   BtCursor *pCur;
48424   int r = 0;
48425   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
48426     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
48427   }
48428   return r;
48429 }
48430 #endif
48431
48432 /*
48433 ** This routine sets the state to CURSOR_FAULT and the error
48434 ** code to errCode for every cursor on BtShared that pBtree
48435 ** references.
48436 **
48437 ** Every cursor is tripped, including cursors that belong
48438 ** to other database connections that happen to be sharing
48439 ** the cache with pBtree.
48440 **
48441 ** This routine gets called when a rollback occurs.
48442 ** All cursors using the same cache must be tripped
48443 ** to prevent them from trying to use the btree after
48444 ** the rollback.  The rollback may have deleted tables
48445 ** or moved root pages, so it is not sufficient to
48446 ** save the state of the cursor.  The cursor must be
48447 ** invalidated.
48448 */
48449 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
48450   BtCursor *p;
48451   sqlite3BtreeEnter(pBtree);
48452   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
48453     int i;
48454     sqlite3BtreeClearCursor(p);
48455     p->eState = CURSOR_FAULT;
48456     p->skipNext = errCode;
48457     for(i=0; i<=p->iPage; i++){
48458       releasePage(p->apPage[i]);
48459       p->apPage[i] = 0;
48460     }
48461   }
48462   sqlite3BtreeLeave(pBtree);
48463 }
48464
48465 /*
48466 ** Rollback the transaction in progress.  All cursors will be
48467 ** invalided by this operation.  Any attempt to use a cursor
48468 ** that was open at the beginning of this operation will result
48469 ** in an error.
48470 **
48471 ** This will release the write lock on the database file.  If there
48472 ** are no active cursors, it also releases the read lock.
48473 */
48474 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
48475   int rc;
48476   BtShared *pBt = p->pBt;
48477   MemPage *pPage1;
48478
48479   sqlite3BtreeEnter(p);
48480   rc = saveAllCursors(pBt, 0, 0);
48481 #ifndef SQLITE_OMIT_SHARED_CACHE
48482   if( rc!=SQLITE_OK ){
48483     /* This is a horrible situation. An IO or malloc() error occurred whilst
48484     ** trying to save cursor positions. If this is an automatic rollback (as
48485     ** the result of a constraint, malloc() failure or IO error) then 
48486     ** the cache may be internally inconsistent (not contain valid trees) so
48487     ** we cannot simply return the error to the caller. Instead, abort 
48488     ** all queries that may be using any of the cursors that failed to save.
48489     */
48490     sqlite3BtreeTripAllCursors(p, rc);
48491   }
48492 #endif
48493   btreeIntegrity(p);
48494
48495   if( p->inTrans==TRANS_WRITE ){
48496     int rc2;
48497
48498     assert( TRANS_WRITE==pBt->inTransaction );
48499     rc2 = sqlite3PagerRollback(pBt->pPager);
48500     if( rc2!=SQLITE_OK ){
48501       rc = rc2;
48502     }
48503
48504     /* The rollback may have destroyed the pPage1->aData value.  So
48505     ** call btreeGetPage() on page 1 again to make
48506     ** sure pPage1->aData is set correctly. */
48507     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
48508       int nPage = get4byte(28+(u8*)pPage1->aData);
48509       testcase( nPage==0 );
48510       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
48511       testcase( pBt->nPage!=nPage );
48512       pBt->nPage = nPage;
48513       releasePage(pPage1);
48514     }
48515     assert( countWriteCursors(pBt)==0 );
48516     pBt->inTransaction = TRANS_READ;
48517   }
48518
48519   btreeEndTransaction(p);
48520   sqlite3BtreeLeave(p);
48521   return rc;
48522 }
48523
48524 /*
48525 ** Start a statement subtransaction. The subtransaction can can be rolled
48526 ** back independently of the main transaction. You must start a transaction 
48527 ** before starting a subtransaction. The subtransaction is ended automatically 
48528 ** if the main transaction commits or rolls back.
48529 **
48530 ** Statement subtransactions are used around individual SQL statements
48531 ** that are contained within a BEGIN...COMMIT block.  If a constraint
48532 ** error occurs within the statement, the effect of that one statement
48533 ** can be rolled back without having to rollback the entire transaction.
48534 **
48535 ** A statement sub-transaction is implemented as an anonymous savepoint. The
48536 ** value passed as the second parameter is the total number of savepoints,
48537 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
48538 ** are no active savepoints and no other statement-transactions open,
48539 ** iStatement is 1. This anonymous savepoint can be released or rolled back
48540 ** using the sqlite3BtreeSavepoint() function.
48541 */
48542 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
48543   int rc;
48544   BtShared *pBt = p->pBt;
48545   sqlite3BtreeEnter(p);
48546   assert( p->inTrans==TRANS_WRITE );
48547   assert( pBt->readOnly==0 );
48548   assert( iStatement>0 );
48549   assert( iStatement>p->db->nSavepoint );
48550   assert( pBt->inTransaction==TRANS_WRITE );
48551   /* At the pager level, a statement transaction is a savepoint with
48552   ** an index greater than all savepoints created explicitly using
48553   ** SQL statements. It is illegal to open, release or rollback any
48554   ** such savepoints while the statement transaction savepoint is active.
48555   */
48556   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
48557   sqlite3BtreeLeave(p);
48558   return rc;
48559 }
48560
48561 /*
48562 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
48563 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
48564 ** savepoint identified by parameter iSavepoint, depending on the value 
48565 ** of op.
48566 **
48567 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
48568 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
48569 ** contents of the entire transaction are rolled back. This is different
48570 ** from a normal transaction rollback, as no locks are released and the
48571 ** transaction remains open.
48572 */
48573 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
48574   int rc = SQLITE_OK;
48575   if( p && p->inTrans==TRANS_WRITE ){
48576     BtShared *pBt = p->pBt;
48577     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
48578     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
48579     sqlite3BtreeEnter(p);
48580     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
48581     if( rc==SQLITE_OK ){
48582       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
48583       rc = newDatabase(pBt);
48584       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
48585
48586       /* The database size was written into the offset 28 of the header
48587       ** when the transaction started, so we know that the value at offset
48588       ** 28 is nonzero. */
48589       assert( pBt->nPage>0 );
48590     }
48591     sqlite3BtreeLeave(p);
48592   }
48593   return rc;
48594 }
48595
48596 /*
48597 ** Create a new cursor for the BTree whose root is on the page
48598 ** iTable. If a read-only cursor is requested, it is assumed that
48599 ** the caller already has at least a read-only transaction open
48600 ** on the database already. If a write-cursor is requested, then
48601 ** the caller is assumed to have an open write transaction.
48602 **
48603 ** If wrFlag==0, then the cursor can only be used for reading.
48604 ** If wrFlag==1, then the cursor can be used for reading or for
48605 ** writing if other conditions for writing are also met.  These
48606 ** are the conditions that must be met in order for writing to
48607 ** be allowed:
48608 **
48609 ** 1:  The cursor must have been opened with wrFlag==1
48610 **
48611 ** 2:  Other database connections that share the same pager cache
48612 **     but which are not in the READ_UNCOMMITTED state may not have
48613 **     cursors open with wrFlag==0 on the same table.  Otherwise
48614 **     the changes made by this write cursor would be visible to
48615 **     the read cursors in the other database connection.
48616 **
48617 ** 3:  The database must be writable (not on read-only media)
48618 **
48619 ** 4:  There must be an active transaction.
48620 **
48621 ** No checking is done to make sure that page iTable really is the
48622 ** root page of a b-tree.  If it is not, then the cursor acquired
48623 ** will not work correctly.
48624 **
48625 ** It is assumed that the sqlite3BtreeCursorZero() has been called
48626 ** on pCur to initialize the memory space prior to invoking this routine.
48627 */
48628 static int btreeCursor(
48629   Btree *p,                              /* The btree */
48630   int iTable,                            /* Root page of table to open */
48631   int wrFlag,                            /* 1 to write. 0 read-only */
48632   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
48633   BtCursor *pCur                         /* Space for new cursor */
48634 ){
48635   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
48636
48637   assert( sqlite3BtreeHoldsMutex(p) );
48638   assert( wrFlag==0 || wrFlag==1 );
48639
48640   /* The following assert statements verify that if this is a sharable 
48641   ** b-tree database, the connection is holding the required table locks, 
48642   ** and that no other connection has any open cursor that conflicts with 
48643   ** this lock.  */
48644   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
48645   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
48646
48647   /* Assert that the caller has opened the required transaction. */
48648   assert( p->inTrans>TRANS_NONE );
48649   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
48650   assert( pBt->pPage1 && pBt->pPage1->aData );
48651
48652   if( NEVER(wrFlag && pBt->readOnly) ){
48653     return SQLITE_READONLY;
48654   }
48655   if( iTable==1 && btreePagecount(pBt)==0 ){
48656     return SQLITE_EMPTY;
48657   }
48658
48659   /* Now that no other errors can occur, finish filling in the BtCursor
48660   ** variables and link the cursor into the BtShared list.  */
48661   pCur->pgnoRoot = (Pgno)iTable;
48662   pCur->iPage = -1;
48663   pCur->pKeyInfo = pKeyInfo;
48664   pCur->pBtree = p;
48665   pCur->pBt = pBt;
48666   pCur->wrFlag = (u8)wrFlag;
48667   pCur->pNext = pBt->pCursor;
48668   if( pCur->pNext ){
48669     pCur->pNext->pPrev = pCur;
48670   }
48671   pBt->pCursor = pCur;
48672   pCur->eState = CURSOR_INVALID;
48673   pCur->cachedRowid = 0;
48674   return SQLITE_OK;
48675 }
48676 SQLITE_PRIVATE int sqlite3BtreeCursor(
48677   Btree *p,                                   /* The btree */
48678   int iTable,                                 /* Root page of table to open */
48679   int wrFlag,                                 /* 1 to write. 0 read-only */
48680   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
48681   BtCursor *pCur                              /* Write new cursor here */
48682 ){
48683   int rc;
48684   sqlite3BtreeEnter(p);
48685   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
48686   sqlite3BtreeLeave(p);
48687   return rc;
48688 }
48689
48690 /*
48691 ** Return the size of a BtCursor object in bytes.
48692 **
48693 ** This interfaces is needed so that users of cursors can preallocate
48694 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
48695 ** to users so they cannot do the sizeof() themselves - they must call
48696 ** this routine.
48697 */
48698 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
48699   return ROUND8(sizeof(BtCursor));
48700 }
48701
48702 /*
48703 ** Initialize memory that will be converted into a BtCursor object.
48704 **
48705 ** The simple approach here would be to memset() the entire object
48706 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
48707 ** do not need to be zeroed and they are large, so we can save a lot
48708 ** of run-time by skipping the initialization of those elements.
48709 */
48710 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
48711   memset(p, 0, offsetof(BtCursor, iPage));
48712 }
48713
48714 /*
48715 ** Set the cached rowid value of every cursor in the same database file
48716 ** as pCur and having the same root page number as pCur.  The value is
48717 ** set to iRowid.
48718 **
48719 ** Only positive rowid values are considered valid for this cache.
48720 ** The cache is initialized to zero, indicating an invalid cache.
48721 ** A btree will work fine with zero or negative rowids.  We just cannot
48722 ** cache zero or negative rowids, which means tables that use zero or
48723 ** negative rowids might run a little slower.  But in practice, zero
48724 ** or negative rowids are very uncommon so this should not be a problem.
48725 */
48726 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
48727   BtCursor *p;
48728   for(p=pCur->pBt->pCursor; p; p=p->pNext){
48729     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
48730   }
48731   assert( pCur->cachedRowid==iRowid );
48732 }
48733
48734 /*
48735 ** Return the cached rowid for the given cursor.  A negative or zero
48736 ** return value indicates that the rowid cache is invalid and should be
48737 ** ignored.  If the rowid cache has never before been set, then a
48738 ** zero is returned.
48739 */
48740 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
48741   return pCur->cachedRowid;
48742 }
48743
48744 /*
48745 ** Close a cursor.  The read lock on the database file is released
48746 ** when the last cursor is closed.
48747 */
48748 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
48749   Btree *pBtree = pCur->pBtree;
48750   if( pBtree ){
48751     int i;
48752     BtShared *pBt = pCur->pBt;
48753     sqlite3BtreeEnter(pBtree);
48754     sqlite3BtreeClearCursor(pCur);
48755     if( pCur->pPrev ){
48756       pCur->pPrev->pNext = pCur->pNext;
48757     }else{
48758       pBt->pCursor = pCur->pNext;
48759     }
48760     if( pCur->pNext ){
48761       pCur->pNext->pPrev = pCur->pPrev;
48762     }
48763     for(i=0; i<=pCur->iPage; i++){
48764       releasePage(pCur->apPage[i]);
48765     }
48766     unlockBtreeIfUnused(pBt);
48767     invalidateOverflowCache(pCur);
48768     /* sqlite3_free(pCur); */
48769     sqlite3BtreeLeave(pBtree);
48770   }
48771   return SQLITE_OK;
48772 }
48773
48774 /*
48775 ** Make sure the BtCursor* given in the argument has a valid
48776 ** BtCursor.info structure.  If it is not already valid, call
48777 ** btreeParseCell() to fill it in.
48778 **
48779 ** BtCursor.info is a cache of the information in the current cell.
48780 ** Using this cache reduces the number of calls to btreeParseCell().
48781 **
48782 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
48783 ** compiler to crash when getCellInfo() is implemented as a macro.
48784 ** But there is a measureable speed advantage to using the macro on gcc
48785 ** (when less compiler optimizations like -Os or -O0 are used and the
48786 ** compiler is not doing agressive inlining.)  So we use a real function
48787 ** for MSVC and a macro for everything else.  Ticket #2457.
48788 */
48789 #ifndef NDEBUG
48790   static void assertCellInfo(BtCursor *pCur){
48791     CellInfo info;
48792     int iPage = pCur->iPage;
48793     memset(&info, 0, sizeof(info));
48794     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
48795     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
48796   }
48797 #else
48798   #define assertCellInfo(x)
48799 #endif
48800 #ifdef _MSC_VER
48801   /* Use a real function in MSVC to work around bugs in that compiler. */
48802   static void getCellInfo(BtCursor *pCur){
48803     if( pCur->info.nSize==0 ){
48804       int iPage = pCur->iPage;
48805       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
48806       pCur->validNKey = 1;
48807     }else{
48808       assertCellInfo(pCur);
48809     }
48810   }
48811 #else /* if not _MSC_VER */
48812   /* Use a macro in all other compilers so that the function is inlined */
48813 #define getCellInfo(pCur)                                                      \
48814   if( pCur->info.nSize==0 ){                                                   \
48815     int iPage = pCur->iPage;                                                   \
48816     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
48817     pCur->validNKey = 1;                                                       \
48818   }else{                                                                       \
48819     assertCellInfo(pCur);                                                      \
48820   }
48821 #endif /* _MSC_VER */
48822
48823 #ifndef NDEBUG  /* The next routine used only within assert() statements */
48824 /*
48825 ** Return true if the given BtCursor is valid.  A valid cursor is one
48826 ** that is currently pointing to a row in a (non-empty) table.
48827 ** This is a verification routine is used only within assert() statements.
48828 */
48829 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
48830   return pCur && pCur->eState==CURSOR_VALID;
48831 }
48832 #endif /* NDEBUG */
48833
48834 /*
48835 ** Set *pSize to the size of the buffer needed to hold the value of
48836 ** the key for the current entry.  If the cursor is not pointing
48837 ** to a valid entry, *pSize is set to 0. 
48838 **
48839 ** For a table with the INTKEY flag set, this routine returns the key
48840 ** itself, not the number of bytes in the key.
48841 **
48842 ** The caller must position the cursor prior to invoking this routine.
48843 ** 
48844 ** This routine cannot fail.  It always returns SQLITE_OK.  
48845 */
48846 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
48847   assert( cursorHoldsMutex(pCur) );
48848   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
48849   if( pCur->eState!=CURSOR_VALID ){
48850     *pSize = 0;
48851   }else{
48852     getCellInfo(pCur);
48853     *pSize = pCur->info.nKey;
48854   }
48855   return SQLITE_OK;
48856 }
48857
48858 /*
48859 ** Set *pSize to the number of bytes of data in the entry the
48860 ** cursor currently points to.
48861 **
48862 ** The caller must guarantee that the cursor is pointing to a non-NULL
48863 ** valid entry.  In other words, the calling procedure must guarantee
48864 ** that the cursor has Cursor.eState==CURSOR_VALID.
48865 **
48866 ** Failure is not possible.  This function always returns SQLITE_OK.
48867 ** It might just as well be a procedure (returning void) but we continue
48868 ** to return an integer result code for historical reasons.
48869 */
48870 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
48871   assert( cursorHoldsMutex(pCur) );
48872   assert( pCur->eState==CURSOR_VALID );
48873   getCellInfo(pCur);
48874   *pSize = pCur->info.nData;
48875   return SQLITE_OK;
48876 }
48877
48878 /*
48879 ** Given the page number of an overflow page in the database (parameter
48880 ** ovfl), this function finds the page number of the next page in the 
48881 ** linked list of overflow pages. If possible, it uses the auto-vacuum
48882 ** pointer-map data instead of reading the content of page ovfl to do so. 
48883 **
48884 ** If an error occurs an SQLite error code is returned. Otherwise:
48885 **
48886 ** The page number of the next overflow page in the linked list is 
48887 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
48888 ** list, *pPgnoNext is set to zero. 
48889 **
48890 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
48891 ** to page number pOvfl was obtained, then *ppPage is set to point to that
48892 ** reference. It is the responsibility of the caller to call releasePage()
48893 ** on *ppPage to free the reference. In no reference was obtained (because
48894 ** the pointer-map was used to obtain the value for *pPgnoNext), then
48895 ** *ppPage is set to zero.
48896 */
48897 static int getOverflowPage(
48898   BtShared *pBt,               /* The database file */
48899   Pgno ovfl,                   /* Current overflow page number */
48900   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
48901   Pgno *pPgnoNext              /* OUT: Next overflow page number */
48902 ){
48903   Pgno next = 0;
48904   MemPage *pPage = 0;
48905   int rc = SQLITE_OK;
48906
48907   assert( sqlite3_mutex_held(pBt->mutex) );
48908   assert(pPgnoNext);
48909
48910 #ifndef SQLITE_OMIT_AUTOVACUUM
48911   /* Try to find the next page in the overflow list using the
48912   ** autovacuum pointer-map pages. Guess that the next page in 
48913   ** the overflow list is page number (ovfl+1). If that guess turns 
48914   ** out to be wrong, fall back to loading the data of page 
48915   ** number ovfl to determine the next page number.
48916   */
48917   if( pBt->autoVacuum ){
48918     Pgno pgno;
48919     Pgno iGuess = ovfl+1;
48920     u8 eType;
48921
48922     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
48923       iGuess++;
48924     }
48925
48926     if( iGuess<=btreePagecount(pBt) ){
48927       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
48928       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
48929         next = iGuess;
48930         rc = SQLITE_DONE;
48931       }
48932     }
48933   }
48934 #endif
48935
48936   assert( next==0 || rc==SQLITE_DONE );
48937   if( rc==SQLITE_OK ){
48938     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
48939     assert( rc==SQLITE_OK || pPage==0 );
48940     if( rc==SQLITE_OK ){
48941       next = get4byte(pPage->aData);
48942     }
48943   }
48944
48945   *pPgnoNext = next;
48946   if( ppPage ){
48947     *ppPage = pPage;
48948   }else{
48949     releasePage(pPage);
48950   }
48951   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
48952 }
48953
48954 /*
48955 ** Copy data from a buffer to a page, or from a page to a buffer.
48956 **
48957 ** pPayload is a pointer to data stored on database page pDbPage.
48958 ** If argument eOp is false, then nByte bytes of data are copied
48959 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
48960 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
48961 ** of data are copied from the buffer pBuf to pPayload.
48962 **
48963 ** SQLITE_OK is returned on success, otherwise an error code.
48964 */
48965 static int copyPayload(
48966   void *pPayload,           /* Pointer to page data */
48967   void *pBuf,               /* Pointer to buffer */
48968   int nByte,                /* Number of bytes to copy */
48969   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
48970   DbPage *pDbPage           /* Page containing pPayload */
48971 ){
48972   if( eOp ){
48973     /* Copy data from buffer to page (a write operation) */
48974     int rc = sqlite3PagerWrite(pDbPage);
48975     if( rc!=SQLITE_OK ){
48976       return rc;
48977     }
48978     memcpy(pPayload, pBuf, nByte);
48979   }else{
48980     /* Copy data from page to buffer (a read operation) */
48981     memcpy(pBuf, pPayload, nByte);
48982   }
48983   return SQLITE_OK;
48984 }
48985
48986 /*
48987 ** This function is used to read or overwrite payload information
48988 ** for the entry that the pCur cursor is pointing to. If the eOp
48989 ** parameter is 0, this is a read operation (data copied into
48990 ** buffer pBuf). If it is non-zero, a write (data copied from
48991 ** buffer pBuf).
48992 **
48993 ** A total of "amt" bytes are read or written beginning at "offset".
48994 ** Data is read to or from the buffer pBuf.
48995 **
48996 ** The content being read or written might appear on the main page
48997 ** or be scattered out on multiple overflow pages.
48998 **
48999 ** If the BtCursor.isIncrblobHandle flag is set, and the current
49000 ** cursor entry uses one or more overflow pages, this function
49001 ** allocates space for and lazily popluates the overflow page-list 
49002 ** cache array (BtCursor.aOverflow). Subsequent calls use this
49003 ** cache to make seeking to the supplied offset more efficient.
49004 **
49005 ** Once an overflow page-list cache has been allocated, it may be
49006 ** invalidated if some other cursor writes to the same table, or if
49007 ** the cursor is moved to a different row. Additionally, in auto-vacuum
49008 ** mode, the following events may invalidate an overflow page-list cache.
49009 **
49010 **   * An incremental vacuum,
49011 **   * A commit in auto_vacuum="full" mode,
49012 **   * Creating a table (may require moving an overflow page).
49013 */
49014 static int accessPayload(
49015   BtCursor *pCur,      /* Cursor pointing to entry to read from */
49016   u32 offset,          /* Begin reading this far into payload */
49017   u32 amt,             /* Read this many bytes */
49018   unsigned char *pBuf, /* Write the bytes into this buffer */ 
49019   int eOp              /* zero to read. non-zero to write. */
49020 ){
49021   unsigned char *aPayload;
49022   int rc = SQLITE_OK;
49023   u32 nKey;
49024   int iIdx = 0;
49025   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
49026   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
49027
49028   assert( pPage );
49029   assert( pCur->eState==CURSOR_VALID );
49030   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
49031   assert( cursorHoldsMutex(pCur) );
49032
49033   getCellInfo(pCur);
49034   aPayload = pCur->info.pCell + pCur->info.nHeader;
49035   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
49036
49037   if( NEVER(offset+amt > nKey+pCur->info.nData) 
49038    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
49039   ){
49040     /* Trying to read or write past the end of the data is an error */
49041     return SQLITE_CORRUPT_BKPT;
49042   }
49043
49044   /* Check if data must be read/written to/from the btree page itself. */
49045   if( offset<pCur->info.nLocal ){
49046     int a = amt;
49047     if( a+offset>pCur->info.nLocal ){
49048       a = pCur->info.nLocal - offset;
49049     }
49050     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
49051     offset = 0;
49052     pBuf += a;
49053     amt -= a;
49054   }else{
49055     offset -= pCur->info.nLocal;
49056   }
49057
49058   if( rc==SQLITE_OK && amt>0 ){
49059     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
49060     Pgno nextPage;
49061
49062     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
49063
49064 #ifndef SQLITE_OMIT_INCRBLOB
49065     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
49066     ** has not been allocated, allocate it now. The array is sized at
49067     ** one entry for each overflow page in the overflow chain. The
49068     ** page number of the first overflow page is stored in aOverflow[0],
49069     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
49070     ** (the cache is lazily populated).
49071     */
49072     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
49073       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
49074       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
49075       /* nOvfl is always positive.  If it were zero, fetchPayload would have
49076       ** been used instead of this routine. */
49077       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
49078         rc = SQLITE_NOMEM;
49079       }
49080     }
49081
49082     /* If the overflow page-list cache has been allocated and the
49083     ** entry for the first required overflow page is valid, skip
49084     ** directly to it.
49085     */
49086     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
49087       iIdx = (offset/ovflSize);
49088       nextPage = pCur->aOverflow[iIdx];
49089       offset = (offset%ovflSize);
49090     }
49091 #endif
49092
49093     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
49094
49095 #ifndef SQLITE_OMIT_INCRBLOB
49096       /* If required, populate the overflow page-list cache. */
49097       if( pCur->aOverflow ){
49098         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
49099         pCur->aOverflow[iIdx] = nextPage;
49100       }
49101 #endif
49102
49103       if( offset>=ovflSize ){
49104         /* The only reason to read this page is to obtain the page
49105         ** number for the next page in the overflow chain. The page
49106         ** data is not required. So first try to lookup the overflow
49107         ** page-list cache, if any, then fall back to the getOverflowPage()
49108         ** function.
49109         */
49110 #ifndef SQLITE_OMIT_INCRBLOB
49111         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
49112           nextPage = pCur->aOverflow[iIdx+1];
49113         } else 
49114 #endif
49115           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
49116         offset -= ovflSize;
49117       }else{
49118         /* Need to read this page properly. It contains some of the
49119         ** range of data that is being read (eOp==0) or written (eOp!=0).
49120         */
49121         DbPage *pDbPage;
49122         int a = amt;
49123         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
49124         if( rc==SQLITE_OK ){
49125           aPayload = sqlite3PagerGetData(pDbPage);
49126           nextPage = get4byte(aPayload);
49127           if( a + offset > ovflSize ){
49128             a = ovflSize - offset;
49129           }
49130           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
49131           sqlite3PagerUnref(pDbPage);
49132           offset = 0;
49133           amt -= a;
49134           pBuf += a;
49135         }
49136       }
49137     }
49138   }
49139
49140   if( rc==SQLITE_OK && amt>0 ){
49141     return SQLITE_CORRUPT_BKPT;
49142   }
49143   return rc;
49144 }
49145
49146 /*
49147 ** Read part of the key associated with cursor pCur.  Exactly
49148 ** "amt" bytes will be transfered into pBuf[].  The transfer
49149 ** begins at "offset".
49150 **
49151 ** The caller must ensure that pCur is pointing to a valid row
49152 ** in the table.
49153 **
49154 ** Return SQLITE_OK on success or an error code if anything goes
49155 ** wrong.  An error is returned if "offset+amt" is larger than
49156 ** the available payload.
49157 */
49158 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
49159   assert( cursorHoldsMutex(pCur) );
49160   assert( pCur->eState==CURSOR_VALID );
49161   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
49162   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
49163   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
49164 }
49165
49166 /*
49167 ** Read part of the data associated with cursor pCur.  Exactly
49168 ** "amt" bytes will be transfered into pBuf[].  The transfer
49169 ** begins at "offset".
49170 **
49171 ** Return SQLITE_OK on success or an error code if anything goes
49172 ** wrong.  An error is returned if "offset+amt" is larger than
49173 ** the available payload.
49174 */
49175 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
49176   int rc;
49177
49178 #ifndef SQLITE_OMIT_INCRBLOB
49179   if ( pCur->eState==CURSOR_INVALID ){
49180     return SQLITE_ABORT;
49181   }
49182 #endif
49183
49184   assert( cursorHoldsMutex(pCur) );
49185   rc = restoreCursorPosition(pCur);
49186   if( rc==SQLITE_OK ){
49187     assert( pCur->eState==CURSOR_VALID );
49188     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
49189     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
49190     rc = accessPayload(pCur, offset, amt, pBuf, 0);
49191   }
49192   return rc;
49193 }
49194
49195 /*
49196 ** Return a pointer to payload information from the entry that the 
49197 ** pCur cursor is pointing to.  The pointer is to the beginning of
49198 ** the key if skipKey==0 and it points to the beginning of data if
49199 ** skipKey==1.  The number of bytes of available key/data is written
49200 ** into *pAmt.  If *pAmt==0, then the value returned will not be
49201 ** a valid pointer.
49202 **
49203 ** This routine is an optimization.  It is common for the entire key
49204 ** and data to fit on the local page and for there to be no overflow
49205 ** pages.  When that is so, this routine can be used to access the
49206 ** key and data without making a copy.  If the key and/or data spills
49207 ** onto overflow pages, then accessPayload() must be used to reassemble
49208 ** the key/data and copy it into a preallocated buffer.
49209 **
49210 ** The pointer returned by this routine looks directly into the cached
49211 ** page of the database.  The data might change or move the next time
49212 ** any btree routine is called.
49213 */
49214 static const unsigned char *fetchPayload(
49215   BtCursor *pCur,      /* Cursor pointing to entry to read from */
49216   int *pAmt,           /* Write the number of available bytes here */
49217   int skipKey          /* read beginning at data if this is true */
49218 ){
49219   unsigned char *aPayload;
49220   MemPage *pPage;
49221   u32 nKey;
49222   u32 nLocal;
49223
49224   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
49225   assert( pCur->eState==CURSOR_VALID );
49226   assert( cursorHoldsMutex(pCur) );
49227   pPage = pCur->apPage[pCur->iPage];
49228   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
49229   if( NEVER(pCur->info.nSize==0) ){
49230     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
49231                    &pCur->info);
49232   }
49233   aPayload = pCur->info.pCell;
49234   aPayload += pCur->info.nHeader;
49235   if( pPage->intKey ){
49236     nKey = 0;
49237   }else{
49238     nKey = (int)pCur->info.nKey;
49239   }
49240   if( skipKey ){
49241     aPayload += nKey;
49242     nLocal = pCur->info.nLocal - nKey;
49243   }else{
49244     nLocal = pCur->info.nLocal;
49245     assert( nLocal<=nKey );
49246   }
49247   *pAmt = nLocal;
49248   return aPayload;
49249 }
49250
49251
49252 /*
49253 ** For the entry that cursor pCur is point to, return as
49254 ** many bytes of the key or data as are available on the local
49255 ** b-tree page.  Write the number of available bytes into *pAmt.
49256 **
49257 ** The pointer returned is ephemeral.  The key/data may move
49258 ** or be destroyed on the next call to any Btree routine,
49259 ** including calls from other threads against the same cache.
49260 ** Hence, a mutex on the BtShared should be held prior to calling
49261 ** this routine.
49262 **
49263 ** These routines is used to get quick access to key and data
49264 ** in the common case where no overflow pages are used.
49265 */
49266 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
49267   const void *p = 0;
49268   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49269   assert( cursorHoldsMutex(pCur) );
49270   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
49271     p = (const void*)fetchPayload(pCur, pAmt, 0);
49272   }
49273   return p;
49274 }
49275 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
49276   const void *p = 0;
49277   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49278   assert( cursorHoldsMutex(pCur) );
49279   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
49280     p = (const void*)fetchPayload(pCur, pAmt, 1);
49281   }
49282   return p;
49283 }
49284
49285
49286 /*
49287 ** Move the cursor down to a new child page.  The newPgno argument is the
49288 ** page number of the child page to move to.
49289 **
49290 ** This function returns SQLITE_CORRUPT if the page-header flags field of
49291 ** the new child page does not match the flags field of the parent (i.e.
49292 ** if an intkey page appears to be the parent of a non-intkey page, or
49293 ** vice-versa).
49294 */
49295 static int moveToChild(BtCursor *pCur, u32 newPgno){
49296   int rc;
49297   int i = pCur->iPage;
49298   MemPage *pNewPage;
49299   BtShared *pBt = pCur->pBt;
49300
49301   assert( cursorHoldsMutex(pCur) );
49302   assert( pCur->eState==CURSOR_VALID );
49303   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
49304   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
49305     return SQLITE_CORRUPT_BKPT;
49306   }
49307   rc = getAndInitPage(pBt, newPgno, &pNewPage);
49308   if( rc ) return rc;
49309   pCur->apPage[i+1] = pNewPage;
49310   pCur->aiIdx[i+1] = 0;
49311   pCur->iPage++;
49312
49313   pCur->info.nSize = 0;
49314   pCur->validNKey = 0;
49315   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
49316     return SQLITE_CORRUPT_BKPT;
49317   }
49318   return SQLITE_OK;
49319 }
49320
49321 #ifndef NDEBUG
49322 /*
49323 ** Page pParent is an internal (non-leaf) tree page. This function 
49324 ** asserts that page number iChild is the left-child if the iIdx'th
49325 ** cell in page pParent. Or, if iIdx is equal to the total number of
49326 ** cells in pParent, that page number iChild is the right-child of
49327 ** the page.
49328 */
49329 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
49330   assert( iIdx<=pParent->nCell );
49331   if( iIdx==pParent->nCell ){
49332     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
49333   }else{
49334     assert( get4byte(findCell(pParent, iIdx))==iChild );
49335   }
49336 }
49337 #else
49338 #  define assertParentIndex(x,y,z) 
49339 #endif
49340
49341 /*
49342 ** Move the cursor up to the parent page.
49343 **
49344 ** pCur->idx is set to the cell index that contains the pointer
49345 ** to the page we are coming from.  If we are coming from the
49346 ** right-most child page then pCur->idx is set to one more than
49347 ** the largest cell index.
49348 */
49349 static void moveToParent(BtCursor *pCur){
49350   assert( cursorHoldsMutex(pCur) );
49351   assert( pCur->eState==CURSOR_VALID );
49352   assert( pCur->iPage>0 );
49353   assert( pCur->apPage[pCur->iPage] );
49354   assertParentIndex(
49355     pCur->apPage[pCur->iPage-1], 
49356     pCur->aiIdx[pCur->iPage-1], 
49357     pCur->apPage[pCur->iPage]->pgno
49358   );
49359   releasePage(pCur->apPage[pCur->iPage]);
49360   pCur->iPage--;
49361   pCur->info.nSize = 0;
49362   pCur->validNKey = 0;
49363 }
49364
49365 /*
49366 ** Move the cursor to point to the root page of its b-tree structure.
49367 **
49368 ** If the table has a virtual root page, then the cursor is moved to point
49369 ** to the virtual root page instead of the actual root page. A table has a
49370 ** virtual root page when the actual root page contains no cells and a 
49371 ** single child page. This can only happen with the table rooted at page 1.
49372 **
49373 ** If the b-tree structure is empty, the cursor state is set to 
49374 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
49375 ** cell located on the root (or virtual root) page and the cursor state
49376 ** is set to CURSOR_VALID.
49377 **
49378 ** If this function returns successfully, it may be assumed that the
49379 ** page-header flags indicate that the [virtual] root-page is the expected 
49380 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
49381 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
49382 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
49383 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
49384 ** b-tree).
49385 */
49386 static int moveToRoot(BtCursor *pCur){
49387   MemPage *pRoot;
49388   int rc = SQLITE_OK;
49389   Btree *p = pCur->pBtree;
49390   BtShared *pBt = p->pBt;
49391
49392   assert( cursorHoldsMutex(pCur) );
49393   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
49394   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
49395   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
49396   if( pCur->eState>=CURSOR_REQUIRESEEK ){
49397     if( pCur->eState==CURSOR_FAULT ){
49398       assert( pCur->skipNext!=SQLITE_OK );
49399       return pCur->skipNext;
49400     }
49401     sqlite3BtreeClearCursor(pCur);
49402   }
49403
49404   if( pCur->iPage>=0 ){
49405     int i;
49406     for(i=1; i<=pCur->iPage; i++){
49407       releasePage(pCur->apPage[i]);
49408     }
49409     pCur->iPage = 0;
49410   }else{
49411     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
49412     if( rc!=SQLITE_OK ){
49413       pCur->eState = CURSOR_INVALID;
49414       return rc;
49415     }
49416     pCur->iPage = 0;
49417
49418     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
49419     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
49420     ** NULL, the caller expects a table b-tree. If this is not the case,
49421     ** return an SQLITE_CORRUPT error.  */
49422     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
49423     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
49424       return SQLITE_CORRUPT_BKPT;
49425     }
49426   }
49427
49428   /* Assert that the root page is of the correct type. This must be the
49429   ** case as the call to this function that loaded the root-page (either
49430   ** this call or a previous invocation) would have detected corruption 
49431   ** if the assumption were not true, and it is not possible for the flags 
49432   ** byte to have been modified while this cursor is holding a reference
49433   ** to the page.  */
49434   pRoot = pCur->apPage[0];
49435   assert( pRoot->pgno==pCur->pgnoRoot );
49436   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
49437
49438   pCur->aiIdx[0] = 0;
49439   pCur->info.nSize = 0;
49440   pCur->atLast = 0;
49441   pCur->validNKey = 0;
49442
49443   if( pRoot->nCell==0 && !pRoot->leaf ){
49444     Pgno subpage;
49445     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
49446     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
49447     pCur->eState = CURSOR_VALID;
49448     rc = moveToChild(pCur, subpage);
49449   }else{
49450     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
49451   }
49452   return rc;
49453 }
49454
49455 /*
49456 ** Move the cursor down to the left-most leaf entry beneath the
49457 ** entry to which it is currently pointing.
49458 **
49459 ** The left-most leaf is the one with the smallest key - the first
49460 ** in ascending order.
49461 */
49462 static int moveToLeftmost(BtCursor *pCur){
49463   Pgno pgno;
49464   int rc = SQLITE_OK;
49465   MemPage *pPage;
49466
49467   assert( cursorHoldsMutex(pCur) );
49468   assert( pCur->eState==CURSOR_VALID );
49469   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
49470     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
49471     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
49472     rc = moveToChild(pCur, pgno);
49473   }
49474   return rc;
49475 }
49476
49477 /*
49478 ** Move the cursor down to the right-most leaf entry beneath the
49479 ** page to which it is currently pointing.  Notice the difference
49480 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
49481 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
49482 ** finds the right-most entry beneath the *page*.
49483 **
49484 ** The right-most entry is the one with the largest key - the last
49485 ** key in ascending order.
49486 */
49487 static int moveToRightmost(BtCursor *pCur){
49488   Pgno pgno;
49489   int rc = SQLITE_OK;
49490   MemPage *pPage = 0;
49491
49492   assert( cursorHoldsMutex(pCur) );
49493   assert( pCur->eState==CURSOR_VALID );
49494   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
49495     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49496     pCur->aiIdx[pCur->iPage] = pPage->nCell;
49497     rc = moveToChild(pCur, pgno);
49498   }
49499   if( rc==SQLITE_OK ){
49500     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
49501     pCur->info.nSize = 0;
49502     pCur->validNKey = 0;
49503   }
49504   return rc;
49505 }
49506
49507 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
49508 ** on success.  Set *pRes to 0 if the cursor actually points to something
49509 ** or set *pRes to 1 if the table is empty.
49510 */
49511 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
49512   int rc;
49513
49514   assert( cursorHoldsMutex(pCur) );
49515   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49516   rc = moveToRoot(pCur);
49517   if( rc==SQLITE_OK ){
49518     if( pCur->eState==CURSOR_INVALID ){
49519       assert( pCur->apPage[pCur->iPage]->nCell==0 );
49520       *pRes = 1;
49521     }else{
49522       assert( pCur->apPage[pCur->iPage]->nCell>0 );
49523       *pRes = 0;
49524       rc = moveToLeftmost(pCur);
49525     }
49526   }
49527   return rc;
49528 }
49529
49530 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
49531 ** on success.  Set *pRes to 0 if the cursor actually points to something
49532 ** or set *pRes to 1 if the table is empty.
49533 */
49534 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
49535   int rc;
49536  
49537   assert( cursorHoldsMutex(pCur) );
49538   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49539
49540   /* If the cursor already points to the last entry, this is a no-op. */
49541   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
49542 #ifdef SQLITE_DEBUG
49543     /* This block serves to assert() that the cursor really does point 
49544     ** to the last entry in the b-tree. */
49545     int ii;
49546     for(ii=0; ii<pCur->iPage; ii++){
49547       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
49548     }
49549     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
49550     assert( pCur->apPage[pCur->iPage]->leaf );
49551 #endif
49552     return SQLITE_OK;
49553   }
49554
49555   rc = moveToRoot(pCur);
49556   if( rc==SQLITE_OK ){
49557     if( CURSOR_INVALID==pCur->eState ){
49558       assert( pCur->apPage[pCur->iPage]->nCell==0 );
49559       *pRes = 1;
49560     }else{
49561       assert( pCur->eState==CURSOR_VALID );
49562       *pRes = 0;
49563       rc = moveToRightmost(pCur);
49564       pCur->atLast = rc==SQLITE_OK ?1:0;
49565     }
49566   }
49567   return rc;
49568 }
49569
49570 /* Move the cursor so that it points to an entry near the key 
49571 ** specified by pIdxKey or intKey.   Return a success code.
49572 **
49573 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
49574 ** must be NULL.  For index tables, pIdxKey is used and intKey
49575 ** is ignored.
49576 **
49577 ** If an exact match is not found, then the cursor is always
49578 ** left pointing at a leaf page which would hold the entry if it
49579 ** were present.  The cursor might point to an entry that comes
49580 ** before or after the key.
49581 **
49582 ** An integer is written into *pRes which is the result of
49583 ** comparing the key with the entry to which the cursor is 
49584 ** pointing.  The meaning of the integer written into
49585 ** *pRes is as follows:
49586 **
49587 **     *pRes<0      The cursor is left pointing at an entry that
49588 **                  is smaller than intKey/pIdxKey or if the table is empty
49589 **                  and the cursor is therefore left point to nothing.
49590 **
49591 **     *pRes==0     The cursor is left pointing at an entry that
49592 **                  exactly matches intKey/pIdxKey.
49593 **
49594 **     *pRes>0      The cursor is left pointing at an entry that
49595 **                  is larger than intKey/pIdxKey.
49596 **
49597 */
49598 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
49599   BtCursor *pCur,          /* The cursor to be moved */
49600   UnpackedRecord *pIdxKey, /* Unpacked index key */
49601   i64 intKey,              /* The table key */
49602   int biasRight,           /* If true, bias the search to the high end */
49603   int *pRes                /* Write search results here */
49604 ){
49605   int rc;
49606
49607   assert( cursorHoldsMutex(pCur) );
49608   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
49609   assert( pRes );
49610   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
49611
49612   /* If the cursor is already positioned at the point we are trying
49613   ** to move to, then just return without doing any work */
49614   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
49615    && pCur->apPage[0]->intKey 
49616   ){
49617     if( pCur->info.nKey==intKey ){
49618       *pRes = 0;
49619       return SQLITE_OK;
49620     }
49621     if( pCur->atLast && pCur->info.nKey<intKey ){
49622       *pRes = -1;
49623       return SQLITE_OK;
49624     }
49625   }
49626
49627   rc = moveToRoot(pCur);
49628   if( rc ){
49629     return rc;
49630   }
49631   assert( pCur->apPage[pCur->iPage] );
49632   assert( pCur->apPage[pCur->iPage]->isInit );
49633   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
49634   if( pCur->eState==CURSOR_INVALID ){
49635     *pRes = -1;
49636     assert( pCur->apPage[pCur->iPage]->nCell==0 );
49637     return SQLITE_OK;
49638   }
49639   assert( pCur->apPage[0]->intKey || pIdxKey );
49640   for(;;){
49641     int lwr, upr;
49642     Pgno chldPg;
49643     MemPage *pPage = pCur->apPage[pCur->iPage];
49644     int c;
49645
49646     /* pPage->nCell must be greater than zero. If this is the root-page
49647     ** the cursor would have been INVALID above and this for(;;) loop
49648     ** not run. If this is not the root-page, then the moveToChild() routine
49649     ** would have already detected db corruption. Similarly, pPage must
49650     ** be the right kind (index or table) of b-tree page. Otherwise
49651     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
49652     assert( pPage->nCell>0 );
49653     assert( pPage->intKey==(pIdxKey==0) );
49654     lwr = 0;
49655     upr = pPage->nCell-1;
49656     if( biasRight ){
49657       pCur->aiIdx[pCur->iPage] = (u16)upr;
49658     }else{
49659       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
49660     }
49661     for(;;){
49662       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
49663       u8 *pCell;                          /* Pointer to current cell in pPage */
49664
49665       pCur->info.nSize = 0;
49666       pCell = findCell(pPage, idx) + pPage->childPtrSize;
49667       if( pPage->intKey ){
49668         i64 nCellKey;
49669         if( pPage->hasData ){
49670           u32 dummy;
49671           pCell += getVarint32(pCell, dummy);
49672         }
49673         getVarint(pCell, (u64*)&nCellKey);
49674         if( nCellKey==intKey ){
49675           c = 0;
49676         }else if( nCellKey<intKey ){
49677           c = -1;
49678         }else{
49679           assert( nCellKey>intKey );
49680           c = +1;
49681         }
49682         pCur->validNKey = 1;
49683         pCur->info.nKey = nCellKey;
49684       }else{
49685         /* The maximum supported page-size is 65536 bytes. This means that
49686         ** the maximum number of record bytes stored on an index B-Tree
49687         ** page is less than 16384 bytes and may be stored as a 2-byte
49688         ** varint. This information is used to attempt to avoid parsing 
49689         ** the entire cell by checking for the cases where the record is 
49690         ** stored entirely within the b-tree page by inspecting the first 
49691         ** 2 bytes of the cell.
49692         */
49693         int nCell = pCell[0];
49694         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
49695           /* This branch runs if the record-size field of the cell is a
49696           ** single byte varint and the record fits entirely on the main
49697           ** b-tree page.  */
49698           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
49699         }else if( !(pCell[1] & 0x80) 
49700           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
49701         ){
49702           /* The record-size field is a 2 byte varint and the record 
49703           ** fits entirely on the main b-tree page.  */
49704           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
49705         }else{
49706           /* The record flows over onto one or more overflow pages. In
49707           ** this case the whole cell needs to be parsed, a buffer allocated
49708           ** and accessPayload() used to retrieve the record into the
49709           ** buffer before VdbeRecordCompare() can be called. */
49710           void *pCellKey;
49711           u8 * const pCellBody = pCell - pPage->childPtrSize;
49712           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
49713           nCell = (int)pCur->info.nKey;
49714           pCellKey = sqlite3Malloc( nCell );
49715           if( pCellKey==0 ){
49716             rc = SQLITE_NOMEM;
49717             goto moveto_finish;
49718           }
49719           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
49720           if( rc ){
49721             sqlite3_free(pCellKey);
49722             goto moveto_finish;
49723           }
49724           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
49725           sqlite3_free(pCellKey);
49726         }
49727       }
49728       if( c==0 ){
49729         if( pPage->intKey && !pPage->leaf ){
49730           lwr = idx;
49731           upr = lwr - 1;
49732           break;
49733         }else{
49734           *pRes = 0;
49735           rc = SQLITE_OK;
49736           goto moveto_finish;
49737         }
49738       }
49739       if( c<0 ){
49740         lwr = idx+1;
49741       }else{
49742         upr = idx-1;
49743       }
49744       if( lwr>upr ){
49745         break;
49746       }
49747       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
49748     }
49749     assert( lwr==upr+1 );
49750     assert( pPage->isInit );
49751     if( pPage->leaf ){
49752       chldPg = 0;
49753     }else if( lwr>=pPage->nCell ){
49754       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
49755     }else{
49756       chldPg = get4byte(findCell(pPage, lwr));
49757     }
49758     if( chldPg==0 ){
49759       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
49760       *pRes = c;
49761       rc = SQLITE_OK;
49762       goto moveto_finish;
49763     }
49764     pCur->aiIdx[pCur->iPage] = (u16)lwr;
49765     pCur->info.nSize = 0;
49766     pCur->validNKey = 0;
49767     rc = moveToChild(pCur, chldPg);
49768     if( rc ) goto moveto_finish;
49769   }
49770 moveto_finish:
49771   return rc;
49772 }
49773
49774
49775 /*
49776 ** Return TRUE if the cursor is not pointing at an entry of the table.
49777 **
49778 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
49779 ** past the last entry in the table or sqlite3BtreePrev() moves past
49780 ** the first entry.  TRUE is also returned if the table is empty.
49781 */
49782 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
49783   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
49784   ** have been deleted? This API will need to change to return an error code
49785   ** as well as the boolean result value.
49786   */
49787   return (CURSOR_VALID!=pCur->eState);
49788 }
49789
49790 /*
49791 ** Advance the cursor to the next entry in the database.  If
49792 ** successful then set *pRes=0.  If the cursor
49793 ** was already pointing to the last entry in the database before
49794 ** this routine was called, then set *pRes=1.
49795 */
49796 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
49797   int rc;
49798   int idx;
49799   MemPage *pPage;
49800
49801   assert( cursorHoldsMutex(pCur) );
49802   rc = restoreCursorPosition(pCur);
49803   if( rc!=SQLITE_OK ){
49804     return rc;
49805   }
49806   assert( pRes!=0 );
49807   if( CURSOR_INVALID==pCur->eState ){
49808     *pRes = 1;
49809     return SQLITE_OK;
49810   }
49811   if( pCur->skipNext>0 ){
49812     pCur->skipNext = 0;
49813     *pRes = 0;
49814     return SQLITE_OK;
49815   }
49816   pCur->skipNext = 0;
49817
49818   pPage = pCur->apPage[pCur->iPage];
49819   idx = ++pCur->aiIdx[pCur->iPage];
49820   assert( pPage->isInit );
49821   assert( idx<=pPage->nCell );
49822
49823   pCur->info.nSize = 0;
49824   pCur->validNKey = 0;
49825   if( idx>=pPage->nCell ){
49826     if( !pPage->leaf ){
49827       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
49828       if( rc ) return rc;
49829       rc = moveToLeftmost(pCur);
49830       *pRes = 0;
49831       return rc;
49832     }
49833     do{
49834       if( pCur->iPage==0 ){
49835         *pRes = 1;
49836         pCur->eState = CURSOR_INVALID;
49837         return SQLITE_OK;
49838       }
49839       moveToParent(pCur);
49840       pPage = pCur->apPage[pCur->iPage];
49841     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
49842     *pRes = 0;
49843     if( pPage->intKey ){
49844       rc = sqlite3BtreeNext(pCur, pRes);
49845     }else{
49846       rc = SQLITE_OK;
49847     }
49848     return rc;
49849   }
49850   *pRes = 0;
49851   if( pPage->leaf ){
49852     return SQLITE_OK;
49853   }
49854   rc = moveToLeftmost(pCur);
49855   return rc;
49856 }
49857
49858
49859 /*
49860 ** Step the cursor to the back to the previous entry in the database.  If
49861 ** successful then set *pRes=0.  If the cursor
49862 ** was already pointing to the first entry in the database before
49863 ** this routine was called, then set *pRes=1.
49864 */
49865 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
49866   int rc;
49867   MemPage *pPage;
49868
49869   assert( cursorHoldsMutex(pCur) );
49870   rc = restoreCursorPosition(pCur);
49871   if( rc!=SQLITE_OK ){
49872     return rc;
49873   }
49874   pCur->atLast = 0;
49875   if( CURSOR_INVALID==pCur->eState ){
49876     *pRes = 1;
49877     return SQLITE_OK;
49878   }
49879   if( pCur->skipNext<0 ){
49880     pCur->skipNext = 0;
49881     *pRes = 0;
49882     return SQLITE_OK;
49883   }
49884   pCur->skipNext = 0;
49885
49886   pPage = pCur->apPage[pCur->iPage];
49887   assert( pPage->isInit );
49888   if( !pPage->leaf ){
49889     int idx = pCur->aiIdx[pCur->iPage];
49890     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
49891     if( rc ){
49892       return rc;
49893     }
49894     rc = moveToRightmost(pCur);
49895   }else{
49896     while( pCur->aiIdx[pCur->iPage]==0 ){
49897       if( pCur->iPage==0 ){
49898         pCur->eState = CURSOR_INVALID;
49899         *pRes = 1;
49900         return SQLITE_OK;
49901       }
49902       moveToParent(pCur);
49903     }
49904     pCur->info.nSize = 0;
49905     pCur->validNKey = 0;
49906
49907     pCur->aiIdx[pCur->iPage]--;
49908     pPage = pCur->apPage[pCur->iPage];
49909     if( pPage->intKey && !pPage->leaf ){
49910       rc = sqlite3BtreePrevious(pCur, pRes);
49911     }else{
49912       rc = SQLITE_OK;
49913     }
49914   }
49915   *pRes = 0;
49916   return rc;
49917 }
49918
49919 /*
49920 ** Allocate a new page from the database file.
49921 **
49922 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
49923 ** has already been called on the new page.)  The new page has also
49924 ** been referenced and the calling routine is responsible for calling
49925 ** sqlite3PagerUnref() on the new page when it is done.
49926 **
49927 ** SQLITE_OK is returned on success.  Any other return value indicates
49928 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
49929 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
49930 **
49931 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
49932 ** locate a page close to the page number "nearby".  This can be used in an
49933 ** attempt to keep related pages close to each other in the database file,
49934 ** which in turn can make database access faster.
49935 **
49936 ** If the "exact" parameter is not 0, and the page-number nearby exists 
49937 ** anywhere on the free-list, then it is guarenteed to be returned. This
49938 ** is only used by auto-vacuum databases when allocating a new table.
49939 */
49940 static int allocateBtreePage(
49941   BtShared *pBt, 
49942   MemPage **ppPage, 
49943   Pgno *pPgno, 
49944   Pgno nearby,
49945   u8 exact
49946 ){
49947   MemPage *pPage1;
49948   int rc;
49949   u32 n;     /* Number of pages on the freelist */
49950   u32 k;     /* Number of leaves on the trunk of the freelist */
49951   MemPage *pTrunk = 0;
49952   MemPage *pPrevTrunk = 0;
49953   Pgno mxPage;     /* Total size of the database file */
49954
49955   assert( sqlite3_mutex_held(pBt->mutex) );
49956   pPage1 = pBt->pPage1;
49957   mxPage = btreePagecount(pBt);
49958   n = get4byte(&pPage1->aData[36]);
49959   testcase( n==mxPage-1 );
49960   if( n>=mxPage ){
49961     return SQLITE_CORRUPT_BKPT;
49962   }
49963   if( n>0 ){
49964     /* There are pages on the freelist.  Reuse one of those pages. */
49965     Pgno iTrunk;
49966     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
49967     
49968     /* If the 'exact' parameter was true and a query of the pointer-map
49969     ** shows that the page 'nearby' is somewhere on the free-list, then
49970     ** the entire-list will be searched for that page.
49971     */
49972 #ifndef SQLITE_OMIT_AUTOVACUUM
49973     if( exact && nearby<=mxPage ){
49974       u8 eType;
49975       assert( nearby>0 );
49976       assert( pBt->autoVacuum );
49977       rc = ptrmapGet(pBt, nearby, &eType, 0);
49978       if( rc ) return rc;
49979       if( eType==PTRMAP_FREEPAGE ){
49980         searchList = 1;
49981       }
49982       *pPgno = nearby;
49983     }
49984 #endif
49985
49986     /* Decrement the free-list count by 1. Set iTrunk to the index of the
49987     ** first free-list trunk page. iPrevTrunk is initially 1.
49988     */
49989     rc = sqlite3PagerWrite(pPage1->pDbPage);
49990     if( rc ) return rc;
49991     put4byte(&pPage1->aData[36], n-1);
49992
49993     /* The code within this loop is run only once if the 'searchList' variable
49994     ** is not true. Otherwise, it runs once for each trunk-page on the
49995     ** free-list until the page 'nearby' is located.
49996     */
49997     do {
49998       pPrevTrunk = pTrunk;
49999       if( pPrevTrunk ){
50000         iTrunk = get4byte(&pPrevTrunk->aData[0]);
50001       }else{
50002         iTrunk = get4byte(&pPage1->aData[32]);
50003       }
50004       testcase( iTrunk==mxPage );
50005       if( iTrunk>mxPage ){
50006         rc = SQLITE_CORRUPT_BKPT;
50007       }else{
50008         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
50009       }
50010       if( rc ){
50011         pTrunk = 0;
50012         goto end_allocate_page;
50013       }
50014
50015       k = get4byte(&pTrunk->aData[4]);
50016       if( k==0 && !searchList ){
50017         /* The trunk has no leaves and the list is not being searched. 
50018         ** So extract the trunk page itself and use it as the newly 
50019         ** allocated page */
50020         assert( pPrevTrunk==0 );
50021         rc = sqlite3PagerWrite(pTrunk->pDbPage);
50022         if( rc ){
50023           goto end_allocate_page;
50024         }
50025         *pPgno = iTrunk;
50026         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
50027         *ppPage = pTrunk;
50028         pTrunk = 0;
50029         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
50030       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
50031         /* Value of k is out of range.  Database corruption */
50032         rc = SQLITE_CORRUPT_BKPT;
50033         goto end_allocate_page;
50034 #ifndef SQLITE_OMIT_AUTOVACUUM
50035       }else if( searchList && nearby==iTrunk ){
50036         /* The list is being searched and this trunk page is the page
50037         ** to allocate, regardless of whether it has leaves.
50038         */
50039         assert( *pPgno==iTrunk );
50040         *ppPage = pTrunk;
50041         searchList = 0;
50042         rc = sqlite3PagerWrite(pTrunk->pDbPage);
50043         if( rc ){
50044           goto end_allocate_page;
50045         }
50046         if( k==0 ){
50047           if( !pPrevTrunk ){
50048             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
50049           }else{
50050             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
50051             if( rc!=SQLITE_OK ){
50052               goto end_allocate_page;
50053             }
50054             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
50055           }
50056         }else{
50057           /* The trunk page is required by the caller but it contains 
50058           ** pointers to free-list leaves. The first leaf becomes a trunk
50059           ** page in this case.
50060           */
50061           MemPage *pNewTrunk;
50062           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
50063           if( iNewTrunk>mxPage ){ 
50064             rc = SQLITE_CORRUPT_BKPT;
50065             goto end_allocate_page;
50066           }
50067           testcase( iNewTrunk==mxPage );
50068           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
50069           if( rc!=SQLITE_OK ){
50070             goto end_allocate_page;
50071           }
50072           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
50073           if( rc!=SQLITE_OK ){
50074             releasePage(pNewTrunk);
50075             goto end_allocate_page;
50076           }
50077           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
50078           put4byte(&pNewTrunk->aData[4], k-1);
50079           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
50080           releasePage(pNewTrunk);
50081           if( !pPrevTrunk ){
50082             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
50083             put4byte(&pPage1->aData[32], iNewTrunk);
50084           }else{
50085             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
50086             if( rc ){
50087               goto end_allocate_page;
50088             }
50089             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
50090           }
50091         }
50092         pTrunk = 0;
50093         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
50094 #endif
50095       }else if( k>0 ){
50096         /* Extract a leaf from the trunk */
50097         u32 closest;
50098         Pgno iPage;
50099         unsigned char *aData = pTrunk->aData;
50100         rc = sqlite3PagerWrite(pTrunk->pDbPage);
50101         if( rc ){
50102           goto end_allocate_page;
50103         }
50104         if( nearby>0 ){
50105           u32 i;
50106           int dist;
50107           closest = 0;
50108           dist = get4byte(&aData[8]) - nearby;
50109           if( dist<0 ) dist = -dist;
50110           for(i=1; i<k; i++){
50111             int d2 = get4byte(&aData[8+i*4]) - nearby;
50112             if( d2<0 ) d2 = -d2;
50113             if( d2<dist ){
50114               closest = i;
50115               dist = d2;
50116             }
50117           }
50118         }else{
50119           closest = 0;
50120         }
50121
50122         iPage = get4byte(&aData[8+closest*4]);
50123         testcase( iPage==mxPage );
50124         if( iPage>mxPage ){
50125           rc = SQLITE_CORRUPT_BKPT;
50126           goto end_allocate_page;
50127         }
50128         testcase( iPage==mxPage );
50129         if( !searchList || iPage==nearby ){
50130           int noContent;
50131           *pPgno = iPage;
50132           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
50133                  ": %d more free pages\n",
50134                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
50135           if( closest<k-1 ){
50136             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
50137           }
50138           put4byte(&aData[4], k-1);
50139           assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
50140           noContent = !btreeGetHasContent(pBt, *pPgno);
50141           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
50142           if( rc==SQLITE_OK ){
50143             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
50144             if( rc!=SQLITE_OK ){
50145               releasePage(*ppPage);
50146             }
50147           }
50148           searchList = 0;
50149         }
50150       }
50151       releasePage(pPrevTrunk);
50152       pPrevTrunk = 0;
50153     }while( searchList );
50154   }else{
50155     /* There are no pages on the freelist, so create a new page at the
50156     ** end of the file */
50157     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
50158     if( rc ) return rc;
50159     pBt->nPage++;
50160     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
50161
50162 #ifndef SQLITE_OMIT_AUTOVACUUM
50163     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
50164       /* If *pPgno refers to a pointer-map page, allocate two new pages
50165       ** at the end of the file instead of one. The first allocated page
50166       ** becomes a new pointer-map page, the second is used by the caller.
50167       */
50168       MemPage *pPg = 0;
50169       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
50170       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
50171       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
50172       if( rc==SQLITE_OK ){
50173         rc = sqlite3PagerWrite(pPg->pDbPage);
50174         releasePage(pPg);
50175       }
50176       if( rc ) return rc;
50177       pBt->nPage++;
50178       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
50179     }
50180 #endif
50181     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
50182     *pPgno = pBt->nPage;
50183
50184     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
50185     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
50186     if( rc ) return rc;
50187     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
50188     if( rc!=SQLITE_OK ){
50189       releasePage(*ppPage);
50190     }
50191     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
50192   }
50193
50194   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
50195
50196 end_allocate_page:
50197   releasePage(pTrunk);
50198   releasePage(pPrevTrunk);
50199   if( rc==SQLITE_OK ){
50200     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
50201       releasePage(*ppPage);
50202       return SQLITE_CORRUPT_BKPT;
50203     }
50204     (*ppPage)->isInit = 0;
50205   }else{
50206     *ppPage = 0;
50207   }
50208   return rc;
50209 }
50210
50211 /*
50212 ** This function is used to add page iPage to the database file free-list. 
50213 ** It is assumed that the page is not already a part of the free-list.
50214 **
50215 ** The value passed as the second argument to this function is optional.
50216 ** If the caller happens to have a pointer to the MemPage object 
50217 ** corresponding to page iPage handy, it may pass it as the second value. 
50218 ** Otherwise, it may pass NULL.
50219 **
50220 ** If a pointer to a MemPage object is passed as the second argument,
50221 ** its reference count is not altered by this function.
50222 */
50223 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
50224   MemPage *pTrunk = 0;                /* Free-list trunk page */
50225   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
50226   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
50227   MemPage *pPage;                     /* Page being freed. May be NULL. */
50228   int rc;                             /* Return Code */
50229   int nFree;                          /* Initial number of pages on free-list */
50230
50231   assert( sqlite3_mutex_held(pBt->mutex) );
50232   assert( iPage>1 );
50233   assert( !pMemPage || pMemPage->pgno==iPage );
50234
50235   if( pMemPage ){
50236     pPage = pMemPage;
50237     sqlite3PagerRef(pPage->pDbPage);
50238   }else{
50239     pPage = btreePageLookup(pBt, iPage);
50240   }
50241
50242   /* Increment the free page count on pPage1 */
50243   rc = sqlite3PagerWrite(pPage1->pDbPage);
50244   if( rc ) goto freepage_out;
50245   nFree = get4byte(&pPage1->aData[36]);
50246   put4byte(&pPage1->aData[36], nFree+1);
50247
50248   if( pBt->secureDelete ){
50249     /* If the secure_delete option is enabled, then
50250     ** always fully overwrite deleted information with zeros.
50251     */
50252     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
50253      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
50254     ){
50255       goto freepage_out;
50256     }
50257     memset(pPage->aData, 0, pPage->pBt->pageSize);
50258   }
50259
50260   /* If the database supports auto-vacuum, write an entry in the pointer-map
50261   ** to indicate that the page is free.
50262   */
50263   if( ISAUTOVACUUM ){
50264     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
50265     if( rc ) goto freepage_out;
50266   }
50267
50268   /* Now manipulate the actual database free-list structure. There are two
50269   ** possibilities. If the free-list is currently empty, or if the first
50270   ** trunk page in the free-list is full, then this page will become a
50271   ** new free-list trunk page. Otherwise, it will become a leaf of the
50272   ** first trunk page in the current free-list. This block tests if it
50273   ** is possible to add the page as a new free-list leaf.
50274   */
50275   if( nFree!=0 ){
50276     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
50277
50278     iTrunk = get4byte(&pPage1->aData[32]);
50279     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
50280     if( rc!=SQLITE_OK ){
50281       goto freepage_out;
50282     }
50283
50284     nLeaf = get4byte(&pTrunk->aData[4]);
50285     assert( pBt->usableSize>32 );
50286     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
50287       rc = SQLITE_CORRUPT_BKPT;
50288       goto freepage_out;
50289     }
50290     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
50291       /* In this case there is room on the trunk page to insert the page
50292       ** being freed as a new leaf.
50293       **
50294       ** Note that the trunk page is not really full until it contains
50295       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
50296       ** coded.  But due to a coding error in versions of SQLite prior to
50297       ** 3.6.0, databases with freelist trunk pages holding more than
50298       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
50299       ** to maintain backwards compatibility with older versions of SQLite,
50300       ** we will continue to restrict the number of entries to usableSize/4 - 8
50301       ** for now.  At some point in the future (once everyone has upgraded
50302       ** to 3.6.0 or later) we should consider fixing the conditional above
50303       ** to read "usableSize/4-2" instead of "usableSize/4-8".
50304       */
50305       rc = sqlite3PagerWrite(pTrunk->pDbPage);
50306       if( rc==SQLITE_OK ){
50307         put4byte(&pTrunk->aData[4], nLeaf+1);
50308         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
50309         if( pPage && !pBt->secureDelete ){
50310           sqlite3PagerDontWrite(pPage->pDbPage);
50311         }
50312         rc = btreeSetHasContent(pBt, iPage);
50313       }
50314       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
50315       goto freepage_out;
50316     }
50317   }
50318
50319   /* If control flows to this point, then it was not possible to add the
50320   ** the page being freed as a leaf page of the first trunk in the free-list.
50321   ** Possibly because the free-list is empty, or possibly because the 
50322   ** first trunk in the free-list is full. Either way, the page being freed
50323   ** will become the new first trunk page in the free-list.
50324   */
50325   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
50326     goto freepage_out;
50327   }
50328   rc = sqlite3PagerWrite(pPage->pDbPage);
50329   if( rc!=SQLITE_OK ){
50330     goto freepage_out;
50331   }
50332   put4byte(pPage->aData, iTrunk);
50333   put4byte(&pPage->aData[4], 0);
50334   put4byte(&pPage1->aData[32], iPage);
50335   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
50336
50337 freepage_out:
50338   if( pPage ){
50339     pPage->isInit = 0;
50340   }
50341   releasePage(pPage);
50342   releasePage(pTrunk);
50343   return rc;
50344 }
50345 static void freePage(MemPage *pPage, int *pRC){
50346   if( (*pRC)==SQLITE_OK ){
50347     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
50348   }
50349 }
50350
50351 /*
50352 ** Free any overflow pages associated with the given Cell.
50353 */
50354 static int clearCell(MemPage *pPage, unsigned char *pCell){
50355   BtShared *pBt = pPage->pBt;
50356   CellInfo info;
50357   Pgno ovflPgno;
50358   int rc;
50359   int nOvfl;
50360   u32 ovflPageSize;
50361
50362   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50363   btreeParseCellPtr(pPage, pCell, &info);
50364   if( info.iOverflow==0 ){
50365     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
50366   }
50367   ovflPgno = get4byte(&pCell[info.iOverflow]);
50368   assert( pBt->usableSize > 4 );
50369   ovflPageSize = pBt->usableSize - 4;
50370   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
50371   assert( ovflPgno==0 || nOvfl>0 );
50372   while( nOvfl-- ){
50373     Pgno iNext = 0;
50374     MemPage *pOvfl = 0;
50375     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
50376       /* 0 is not a legal page number and page 1 cannot be an 
50377       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
50378       ** file the database must be corrupt. */
50379       return SQLITE_CORRUPT_BKPT;
50380     }
50381     if( nOvfl ){
50382       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
50383       if( rc ) return rc;
50384     }
50385
50386     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
50387      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
50388     ){
50389       /* There is no reason any cursor should have an outstanding reference 
50390       ** to an overflow page belonging to a cell that is being deleted/updated.
50391       ** So if there exists more than one reference to this page, then it 
50392       ** must not really be an overflow page and the database must be corrupt. 
50393       ** It is helpful to detect this before calling freePage2(), as 
50394       ** freePage2() may zero the page contents if secure-delete mode is
50395       ** enabled. If this 'overflow' page happens to be a page that the
50396       ** caller is iterating through or using in some other way, this
50397       ** can be problematic.
50398       */
50399       rc = SQLITE_CORRUPT_BKPT;
50400     }else{
50401       rc = freePage2(pBt, pOvfl, ovflPgno);
50402     }
50403
50404     if( pOvfl ){
50405       sqlite3PagerUnref(pOvfl->pDbPage);
50406     }
50407     if( rc ) return rc;
50408     ovflPgno = iNext;
50409   }
50410   return SQLITE_OK;
50411 }
50412
50413 /*
50414 ** Create the byte sequence used to represent a cell on page pPage
50415 ** and write that byte sequence into pCell[].  Overflow pages are
50416 ** allocated and filled in as necessary.  The calling procedure
50417 ** is responsible for making sure sufficient space has been allocated
50418 ** for pCell[].
50419 **
50420 ** Note that pCell does not necessary need to point to the pPage->aData
50421 ** area.  pCell might point to some temporary storage.  The cell will
50422 ** be constructed in this temporary area then copied into pPage->aData
50423 ** later.
50424 */
50425 static int fillInCell(
50426   MemPage *pPage,                /* The page that contains the cell */
50427   unsigned char *pCell,          /* Complete text of the cell */
50428   const void *pKey, i64 nKey,    /* The key */
50429   const void *pData,int nData,   /* The data */
50430   int nZero,                     /* Extra zero bytes to append to pData */
50431   int *pnSize                    /* Write cell size here */
50432 ){
50433   int nPayload;
50434   const u8 *pSrc;
50435   int nSrc, n, rc;
50436   int spaceLeft;
50437   MemPage *pOvfl = 0;
50438   MemPage *pToRelease = 0;
50439   unsigned char *pPrior;
50440   unsigned char *pPayload;
50441   BtShared *pBt = pPage->pBt;
50442   Pgno pgnoOvfl = 0;
50443   int nHeader;
50444   CellInfo info;
50445
50446   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50447
50448   /* pPage is not necessarily writeable since pCell might be auxiliary
50449   ** buffer space that is separate from the pPage buffer area */
50450   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
50451             || sqlite3PagerIswriteable(pPage->pDbPage) );
50452
50453   /* Fill in the header. */
50454   nHeader = 0;
50455   if( !pPage->leaf ){
50456     nHeader += 4;
50457   }
50458   if( pPage->hasData ){
50459     nHeader += putVarint(&pCell[nHeader], nData+nZero);
50460   }else{
50461     nData = nZero = 0;
50462   }
50463   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
50464   btreeParseCellPtr(pPage, pCell, &info);
50465   assert( info.nHeader==nHeader );
50466   assert( info.nKey==nKey );
50467   assert( info.nData==(u32)(nData+nZero) );
50468   
50469   /* Fill in the payload */
50470   nPayload = nData + nZero;
50471   if( pPage->intKey ){
50472     pSrc = pData;
50473     nSrc = nData;
50474     nData = 0;
50475   }else{ 
50476     if( NEVER(nKey>0x7fffffff || pKey==0) ){
50477       return SQLITE_CORRUPT_BKPT;
50478     }
50479     nPayload += (int)nKey;
50480     pSrc = pKey;
50481     nSrc = (int)nKey;
50482   }
50483   *pnSize = info.nSize;
50484   spaceLeft = info.nLocal;
50485   pPayload = &pCell[nHeader];
50486   pPrior = &pCell[info.iOverflow];
50487
50488   while( nPayload>0 ){
50489     if( spaceLeft==0 ){
50490 #ifndef SQLITE_OMIT_AUTOVACUUM
50491       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
50492       if( pBt->autoVacuum ){
50493         do{
50494           pgnoOvfl++;
50495         } while( 
50496           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
50497         );
50498       }
50499 #endif
50500       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
50501 #ifndef SQLITE_OMIT_AUTOVACUUM
50502       /* If the database supports auto-vacuum, and the second or subsequent
50503       ** overflow page is being allocated, add an entry to the pointer-map
50504       ** for that page now. 
50505       **
50506       ** If this is the first overflow page, then write a partial entry 
50507       ** to the pointer-map. If we write nothing to this pointer-map slot,
50508       ** then the optimistic overflow chain processing in clearCell()
50509       ** may misinterpret the uninitialised values and delete the
50510       ** wrong pages from the database.
50511       */
50512       if( pBt->autoVacuum && rc==SQLITE_OK ){
50513         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
50514         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
50515         if( rc ){
50516           releasePage(pOvfl);
50517         }
50518       }
50519 #endif
50520       if( rc ){
50521         releasePage(pToRelease);
50522         return rc;
50523       }
50524
50525       /* If pToRelease is not zero than pPrior points into the data area
50526       ** of pToRelease.  Make sure pToRelease is still writeable. */
50527       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
50528
50529       /* If pPrior is part of the data area of pPage, then make sure pPage
50530       ** is still writeable */
50531       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
50532             || sqlite3PagerIswriteable(pPage->pDbPage) );
50533
50534       put4byte(pPrior, pgnoOvfl);
50535       releasePage(pToRelease);
50536       pToRelease = pOvfl;
50537       pPrior = pOvfl->aData;
50538       put4byte(pPrior, 0);
50539       pPayload = &pOvfl->aData[4];
50540       spaceLeft = pBt->usableSize - 4;
50541     }
50542     n = nPayload;
50543     if( n>spaceLeft ) n = spaceLeft;
50544
50545     /* If pToRelease is not zero than pPayload points into the data area
50546     ** of pToRelease.  Make sure pToRelease is still writeable. */
50547     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
50548
50549     /* If pPayload is part of the data area of pPage, then make sure pPage
50550     ** is still writeable */
50551     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
50552             || sqlite3PagerIswriteable(pPage->pDbPage) );
50553
50554     if( nSrc>0 ){
50555       if( n>nSrc ) n = nSrc;
50556       assert( pSrc );
50557       memcpy(pPayload, pSrc, n);
50558     }else{
50559       memset(pPayload, 0, n);
50560     }
50561     nPayload -= n;
50562     pPayload += n;
50563     pSrc += n;
50564     nSrc -= n;
50565     spaceLeft -= n;
50566     if( nSrc==0 ){
50567       nSrc = nData;
50568       pSrc = pData;
50569     }
50570   }
50571   releasePage(pToRelease);
50572   return SQLITE_OK;
50573 }
50574
50575 /*
50576 ** Remove the i-th cell from pPage.  This routine effects pPage only.
50577 ** The cell content is not freed or deallocated.  It is assumed that
50578 ** the cell content has been copied someplace else.  This routine just
50579 ** removes the reference to the cell from pPage.
50580 **
50581 ** "sz" must be the number of bytes in the cell.
50582 */
50583 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
50584   int i;          /* Loop counter */
50585   u32 pc;         /* Offset to cell content of cell being deleted */
50586   u8 *data;       /* pPage->aData */
50587   u8 *ptr;        /* Used to move bytes around within data[] */
50588   int rc;         /* The return code */
50589   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
50590
50591   if( *pRC ) return;
50592
50593   assert( idx>=0 && idx<pPage->nCell );
50594   assert( sz==cellSize(pPage, idx) );
50595   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50596   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50597   data = pPage->aData;
50598   ptr = &data[pPage->cellOffset + 2*idx];
50599   pc = get2byte(ptr);
50600   hdr = pPage->hdrOffset;
50601   testcase( pc==get2byte(&data[hdr+5]) );
50602   testcase( pc+sz==pPage->pBt->usableSize );
50603   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
50604     *pRC = SQLITE_CORRUPT_BKPT;
50605     return;
50606   }
50607   rc = freeSpace(pPage, pc, sz);
50608   if( rc ){
50609     *pRC = rc;
50610     return;
50611   }
50612   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
50613     ptr[0] = ptr[2];
50614     ptr[1] = ptr[3];
50615   }
50616   pPage->nCell--;
50617   put2byte(&data[hdr+3], pPage->nCell);
50618   pPage->nFree += 2;
50619 }
50620
50621 /*
50622 ** Insert a new cell on pPage at cell index "i".  pCell points to the
50623 ** content of the cell.
50624 **
50625 ** If the cell content will fit on the page, then put it there.  If it
50626 ** will not fit, then make a copy of the cell content into pTemp if
50627 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
50628 ** in pPage->aOvfl[] and make it point to the cell content (either
50629 ** in pTemp or the original pCell) and also record its index. 
50630 ** Allocating a new entry in pPage->aCell[] implies that 
50631 ** pPage->nOverflow is incremented.
50632 **
50633 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
50634 ** cell. The caller will overwrite them after this function returns. If
50635 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
50636 ** (but pCell+nSkip is always valid).
50637 */
50638 static void insertCell(
50639   MemPage *pPage,   /* Page into which we are copying */
50640   int i,            /* New cell becomes the i-th cell of the page */
50641   u8 *pCell,        /* Content of the new cell */
50642   int sz,           /* Bytes of content in pCell */
50643   u8 *pTemp,        /* Temp storage space for pCell, if needed */
50644   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
50645   int *pRC          /* Read and write return code from here */
50646 ){
50647   int idx = 0;      /* Where to write new cell content in data[] */
50648   int j;            /* Loop counter */
50649   int end;          /* First byte past the last cell pointer in data[] */
50650   int ins;          /* Index in data[] where new cell pointer is inserted */
50651   int cellOffset;   /* Address of first cell pointer in data[] */
50652   u8 *data;         /* The content of the whole page */
50653   u8 *ptr;          /* Used for moving information around in data[] */
50654
50655   int nSkip = (iChild ? 4 : 0);
50656
50657   if( *pRC ) return;
50658
50659   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
50660   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
50661   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
50662   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50663   /* The cell should normally be sized correctly.  However, when moving a
50664   ** malformed cell from a leaf page to an interior page, if the cell size
50665   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
50666   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
50667   ** the term after the || in the following assert(). */
50668   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
50669   if( pPage->nOverflow || sz+2>pPage->nFree ){
50670     if( pTemp ){
50671       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
50672       pCell = pTemp;
50673     }
50674     if( iChild ){
50675       put4byte(pCell, iChild);
50676     }
50677     j = pPage->nOverflow++;
50678     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
50679     pPage->aOvfl[j].pCell = pCell;
50680     pPage->aOvfl[j].idx = (u16)i;
50681   }else{
50682     int rc = sqlite3PagerWrite(pPage->pDbPage);
50683     if( rc!=SQLITE_OK ){
50684       *pRC = rc;
50685       return;
50686     }
50687     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50688     data = pPage->aData;
50689     cellOffset = pPage->cellOffset;
50690     end = cellOffset + 2*pPage->nCell;
50691     ins = cellOffset + 2*i;
50692     rc = allocateSpace(pPage, sz, &idx);
50693     if( rc ){ *pRC = rc; return; }
50694     /* The allocateSpace() routine guarantees the following two properties
50695     ** if it returns success */
50696     assert( idx >= end+2 );
50697     assert( idx+sz <= pPage->pBt->usableSize );
50698     pPage->nCell++;
50699     pPage->nFree -= (u16)(2 + sz);
50700     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
50701     if( iChild ){
50702       put4byte(&data[idx], iChild);
50703     }
50704     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
50705       ptr[0] = ptr[-2];
50706       ptr[1] = ptr[-1];
50707     }
50708     put2byte(&data[ins], idx);
50709     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
50710 #ifndef SQLITE_OMIT_AUTOVACUUM
50711     if( pPage->pBt->autoVacuum ){
50712       /* The cell may contain a pointer to an overflow page. If so, write
50713       ** the entry for the overflow page into the pointer map.
50714       */
50715       ptrmapPutOvflPtr(pPage, pCell, pRC);
50716     }
50717 #endif
50718   }
50719 }
50720
50721 /*
50722 ** Add a list of cells to a page.  The page should be initially empty.
50723 ** The cells are guaranteed to fit on the page.
50724 */
50725 static void assemblePage(
50726   MemPage *pPage,   /* The page to be assemblied */
50727   int nCell,        /* The number of cells to add to this page */
50728   u8 **apCell,      /* Pointers to cell bodies */
50729   u16 *aSize        /* Sizes of the cells */
50730 ){
50731   int i;            /* Loop counter */
50732   u8 *pCellptr;     /* Address of next cell pointer */
50733   int cellbody;     /* Address of next cell body */
50734   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
50735   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
50736   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
50737
50738   assert( pPage->nOverflow==0 );
50739   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50740   assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921);
50741   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50742
50743   /* Check that the page has just been zeroed by zeroPage() */
50744   assert( pPage->nCell==0 );
50745   assert( get2byteNotZero(&data[hdr+5])==nUsable );
50746
50747   pCellptr = &data[pPage->cellOffset + nCell*2];
50748   cellbody = nUsable;
50749   for(i=nCell-1; i>=0; i--){
50750     pCellptr -= 2;
50751     cellbody -= aSize[i];
50752     put2byte(pCellptr, cellbody);
50753     memcpy(&data[cellbody], apCell[i], aSize[i]);
50754   }
50755   put2byte(&data[hdr+3], nCell);
50756   put2byte(&data[hdr+5], cellbody);
50757   pPage->nFree -= (nCell*2 + nUsable - cellbody);
50758   pPage->nCell = (u16)nCell;
50759 }
50760
50761 /*
50762 ** The following parameters determine how many adjacent pages get involved
50763 ** in a balancing operation.  NN is the number of neighbors on either side
50764 ** of the page that participate in the balancing operation.  NB is the
50765 ** total number of pages that participate, including the target page and
50766 ** NN neighbors on either side.
50767 **
50768 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
50769 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
50770 ** in exchange for a larger degradation in INSERT and UPDATE performance.
50771 ** The value of NN appears to give the best results overall.
50772 */
50773 #define NN 1             /* Number of neighbors on either side of pPage */
50774 #define NB (NN*2+1)      /* Total pages involved in the balance */
50775
50776
50777 #ifndef SQLITE_OMIT_QUICKBALANCE
50778 /*
50779 ** This version of balance() handles the common special case where
50780 ** a new entry is being inserted on the extreme right-end of the
50781 ** tree, in other words, when the new entry will become the largest
50782 ** entry in the tree.
50783 **
50784 ** Instead of trying to balance the 3 right-most leaf pages, just add
50785 ** a new page to the right-hand side and put the one new entry in
50786 ** that page.  This leaves the right side of the tree somewhat
50787 ** unbalanced.  But odds are that we will be inserting new entries
50788 ** at the end soon afterwards so the nearly empty page will quickly
50789 ** fill up.  On average.
50790 **
50791 ** pPage is the leaf page which is the right-most page in the tree.
50792 ** pParent is its parent.  pPage must have a single overflow entry
50793 ** which is also the right-most entry on the page.
50794 **
50795 ** The pSpace buffer is used to store a temporary copy of the divider
50796 ** cell that will be inserted into pParent. Such a cell consists of a 4
50797 ** byte page number followed by a variable length integer. In other
50798 ** words, at most 13 bytes. Hence the pSpace buffer must be at
50799 ** least 13 bytes in size.
50800 */
50801 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
50802   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
50803   MemPage *pNew;                       /* Newly allocated page */
50804   int rc;                              /* Return Code */
50805   Pgno pgnoNew;                        /* Page number of pNew */
50806
50807   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50808   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
50809   assert( pPage->nOverflow==1 );
50810
50811   /* This error condition is now caught prior to reaching this function */
50812   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
50813
50814   /* Allocate a new page. This page will become the right-sibling of 
50815   ** pPage. Make the parent page writable, so that the new divider cell
50816   ** may be inserted. If both these operations are successful, proceed.
50817   */
50818   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
50819
50820   if( rc==SQLITE_OK ){
50821
50822     u8 *pOut = &pSpace[4];
50823     u8 *pCell = pPage->aOvfl[0].pCell;
50824     u16 szCell = cellSizePtr(pPage, pCell);
50825     u8 *pStop;
50826
50827     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
50828     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
50829     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
50830     assemblePage(pNew, 1, &pCell, &szCell);
50831
50832     /* If this is an auto-vacuum database, update the pointer map
50833     ** with entries for the new page, and any pointer from the 
50834     ** cell on the page to an overflow page. If either of these
50835     ** operations fails, the return code is set, but the contents
50836     ** of the parent page are still manipulated by thh code below.
50837     ** That is Ok, at this point the parent page is guaranteed to
50838     ** be marked as dirty. Returning an error code will cause a
50839     ** rollback, undoing any changes made to the parent page.
50840     */
50841     if( ISAUTOVACUUM ){
50842       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
50843       if( szCell>pNew->minLocal ){
50844         ptrmapPutOvflPtr(pNew, pCell, &rc);
50845       }
50846     }
50847   
50848     /* Create a divider cell to insert into pParent. The divider cell
50849     ** consists of a 4-byte page number (the page number of pPage) and
50850     ** a variable length key value (which must be the same value as the
50851     ** largest key on pPage).
50852     **
50853     ** To find the largest key value on pPage, first find the right-most 
50854     ** cell on pPage. The first two fields of this cell are the 
50855     ** record-length (a variable length integer at most 32-bits in size)
50856     ** and the key value (a variable length integer, may have any value).
50857     ** The first of the while(...) loops below skips over the record-length
50858     ** field. The second while(...) loop copies the key value from the
50859     ** cell on pPage into the pSpace buffer.
50860     */
50861     pCell = findCell(pPage, pPage->nCell-1);
50862     pStop = &pCell[9];
50863     while( (*(pCell++)&0x80) && pCell<pStop );
50864     pStop = &pCell[9];
50865     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
50866
50867     /* Insert the new divider cell into pParent. */
50868     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
50869                0, pPage->pgno, &rc);
50870
50871     /* Set the right-child pointer of pParent to point to the new page. */
50872     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
50873   
50874     /* Release the reference to the new page. */
50875     releasePage(pNew);
50876   }
50877
50878   return rc;
50879 }
50880 #endif /* SQLITE_OMIT_QUICKBALANCE */
50881
50882 #if 0
50883 /*
50884 ** This function does not contribute anything to the operation of SQLite.
50885 ** it is sometimes activated temporarily while debugging code responsible 
50886 ** for setting pointer-map entries.
50887 */
50888 static int ptrmapCheckPages(MemPage **apPage, int nPage){
50889   int i, j;
50890   for(i=0; i<nPage; i++){
50891     Pgno n;
50892     u8 e;
50893     MemPage *pPage = apPage[i];
50894     BtShared *pBt = pPage->pBt;
50895     assert( pPage->isInit );
50896
50897     for(j=0; j<pPage->nCell; j++){
50898       CellInfo info;
50899       u8 *z;
50900      
50901       z = findCell(pPage, j);
50902       btreeParseCellPtr(pPage, z, &info);
50903       if( info.iOverflow ){
50904         Pgno ovfl = get4byte(&z[info.iOverflow]);
50905         ptrmapGet(pBt, ovfl, &e, &n);
50906         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
50907       }
50908       if( !pPage->leaf ){
50909         Pgno child = get4byte(z);
50910         ptrmapGet(pBt, child, &e, &n);
50911         assert( n==pPage->pgno && e==PTRMAP_BTREE );
50912       }
50913     }
50914     if( !pPage->leaf ){
50915       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
50916       ptrmapGet(pBt, child, &e, &n);
50917       assert( n==pPage->pgno && e==PTRMAP_BTREE );
50918     }
50919   }
50920   return 1;
50921 }
50922 #endif
50923
50924 /*
50925 ** This function is used to copy the contents of the b-tree node stored 
50926 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
50927 ** the pointer-map entries for each child page are updated so that the
50928 ** parent page stored in the pointer map is page pTo. If pFrom contained
50929 ** any cells with overflow page pointers, then the corresponding pointer
50930 ** map entries are also updated so that the parent page is page pTo.
50931 **
50932 ** If pFrom is currently carrying any overflow cells (entries in the
50933 ** MemPage.aOvfl[] array), they are not copied to pTo. 
50934 **
50935 ** Before returning, page pTo is reinitialized using btreeInitPage().
50936 **
50937 ** The performance of this function is not critical. It is only used by 
50938 ** the balance_shallower() and balance_deeper() procedures, neither of
50939 ** which are called often under normal circumstances.
50940 */
50941 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
50942   if( (*pRC)==SQLITE_OK ){
50943     BtShared * const pBt = pFrom->pBt;
50944     u8 * const aFrom = pFrom->aData;
50945     u8 * const aTo = pTo->aData;
50946     int const iFromHdr = pFrom->hdrOffset;
50947     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
50948     int rc;
50949     int iData;
50950   
50951   
50952     assert( pFrom->isInit );
50953     assert( pFrom->nFree>=iToHdr );
50954     assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
50955   
50956     /* Copy the b-tree node content from page pFrom to page pTo. */
50957     iData = get2byte(&aFrom[iFromHdr+5]);
50958     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
50959     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
50960   
50961     /* Reinitialize page pTo so that the contents of the MemPage structure
50962     ** match the new data. The initialization of pTo can actually fail under
50963     ** fairly obscure circumstances, even though it is a copy of initialized 
50964     ** page pFrom.
50965     */
50966     pTo->isInit = 0;
50967     rc = btreeInitPage(pTo);
50968     if( rc!=SQLITE_OK ){
50969       *pRC = rc;
50970       return;
50971     }
50972   
50973     /* If this is an auto-vacuum database, update the pointer-map entries
50974     ** for any b-tree or overflow pages that pTo now contains the pointers to.
50975     */
50976     if( ISAUTOVACUUM ){
50977       *pRC = setChildPtrmaps(pTo);
50978     }
50979   }
50980 }
50981
50982 /*
50983 ** This routine redistributes cells on the iParentIdx'th child of pParent
50984 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
50985 ** same amount of free space. Usually a single sibling on either side of the
50986 ** page are used in the balancing, though both siblings might come from one
50987 ** side if the page is the first or last child of its parent. If the page 
50988 ** has fewer than 2 siblings (something which can only happen if the page
50989 ** is a root page or a child of a root page) then all available siblings
50990 ** participate in the balancing.
50991 **
50992 ** The number of siblings of the page might be increased or decreased by 
50993 ** one or two in an effort to keep pages nearly full but not over full. 
50994 **
50995 ** Note that when this routine is called, some of the cells on the page
50996 ** might not actually be stored in MemPage.aData[]. This can happen
50997 ** if the page is overfull. This routine ensures that all cells allocated
50998 ** to the page and its siblings fit into MemPage.aData[] before returning.
50999 **
51000 ** In the course of balancing the page and its siblings, cells may be
51001 ** inserted into or removed from the parent page (pParent). Doing so
51002 ** may cause the parent page to become overfull or underfull. If this
51003 ** happens, it is the responsibility of the caller to invoke the correct
51004 ** balancing routine to fix this problem (see the balance() routine). 
51005 **
51006 ** If this routine fails for any reason, it might leave the database
51007 ** in a corrupted state. So if this routine fails, the database should
51008 ** be rolled back.
51009 **
51010 ** The third argument to this function, aOvflSpace, is a pointer to a
51011 ** buffer big enough to hold one page. If while inserting cells into the parent
51012 ** page (pParent) the parent page becomes overfull, this buffer is
51013 ** used to store the parent's overflow cells. Because this function inserts
51014 ** a maximum of four divider cells into the parent page, and the maximum
51015 ** size of a cell stored within an internal node is always less than 1/4
51016 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
51017 ** enough for all overflow cells.
51018 **
51019 ** If aOvflSpace is set to a null pointer, this function returns 
51020 ** SQLITE_NOMEM.
51021 */
51022 static int balance_nonroot(
51023   MemPage *pParent,               /* Parent page of siblings being balanced */
51024   int iParentIdx,                 /* Index of "the page" in pParent */
51025   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
51026   int isRoot                      /* True if pParent is a root-page */
51027 ){
51028   BtShared *pBt;               /* The whole database */
51029   int nCell = 0;               /* Number of cells in apCell[] */
51030   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
51031   int nNew = 0;                /* Number of pages in apNew[] */
51032   int nOld;                    /* Number of pages in apOld[] */
51033   int i, j, k;                 /* Loop counters */
51034   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
51035   int rc = SQLITE_OK;          /* The return code */
51036   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
51037   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
51038   int usableSpace;             /* Bytes in pPage beyond the header */
51039   int pageFlags;               /* Value of pPage->aData[0] */
51040   int subtotal;                /* Subtotal of bytes in cells on one page */
51041   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
51042   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
51043   int szScratch;               /* Size of scratch memory requested */
51044   MemPage *apOld[NB];          /* pPage and up to two siblings */
51045   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
51046   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
51047   u8 *pRight;                  /* Location in parent of right-sibling pointer */
51048   u8 *apDiv[NB-1];             /* Divider cells in pParent */
51049   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
51050   int szNew[NB+2];             /* Combined size of cells place on i-th page */
51051   u8 **apCell = 0;             /* All cells begin balanced */
51052   u16 *szCell;                 /* Local size of all cells in apCell[] */
51053   u8 *aSpace1;                 /* Space for copies of dividers cells */
51054   Pgno pgno;                   /* Temp var to store a page number in */
51055
51056   pBt = pParent->pBt;
51057   assert( sqlite3_mutex_held(pBt->mutex) );
51058   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
51059
51060 #if 0
51061   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
51062 #endif
51063
51064   /* At this point pParent may have at most one overflow cell. And if
51065   ** this overflow cell is present, it must be the cell with 
51066   ** index iParentIdx. This scenario comes about when this function
51067   ** is called (indirectly) from sqlite3BtreeDelete().
51068   */
51069   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
51070   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
51071
51072   if( !aOvflSpace ){
51073     return SQLITE_NOMEM;
51074   }
51075
51076   /* Find the sibling pages to balance. Also locate the cells in pParent 
51077   ** that divide the siblings. An attempt is made to find NN siblings on 
51078   ** either side of pPage. More siblings are taken from one side, however, 
51079   ** if there are fewer than NN siblings on the other side. If pParent
51080   ** has NB or fewer children then all children of pParent are taken.  
51081   **
51082   ** This loop also drops the divider cells from the parent page. This
51083   ** way, the remainder of the function does not have to deal with any
51084   ** overflow cells in the parent page, since if any existed they will
51085   ** have already been removed.
51086   */
51087   i = pParent->nOverflow + pParent->nCell;
51088   if( i<2 ){
51089     nxDiv = 0;
51090     nOld = i+1;
51091   }else{
51092     nOld = 3;
51093     if( iParentIdx==0 ){                 
51094       nxDiv = 0;
51095     }else if( iParentIdx==i ){
51096       nxDiv = i-2;
51097     }else{
51098       nxDiv = iParentIdx-1;
51099     }
51100     i = 2;
51101   }
51102   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
51103     pRight = &pParent->aData[pParent->hdrOffset+8];
51104   }else{
51105     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
51106   }
51107   pgno = get4byte(pRight);
51108   while( 1 ){
51109     rc = getAndInitPage(pBt, pgno, &apOld[i]);
51110     if( rc ){
51111       memset(apOld, 0, (i+1)*sizeof(MemPage*));
51112       goto balance_cleanup;
51113     }
51114     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
51115     if( (i--)==0 ) break;
51116
51117     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
51118       apDiv[i] = pParent->aOvfl[0].pCell;
51119       pgno = get4byte(apDiv[i]);
51120       szNew[i] = cellSizePtr(pParent, apDiv[i]);
51121       pParent->nOverflow = 0;
51122     }else{
51123       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
51124       pgno = get4byte(apDiv[i]);
51125       szNew[i] = cellSizePtr(pParent, apDiv[i]);
51126
51127       /* Drop the cell from the parent page. apDiv[i] still points to
51128       ** the cell within the parent, even though it has been dropped.
51129       ** This is safe because dropping a cell only overwrites the first
51130       ** four bytes of it, and this function does not need the first
51131       ** four bytes of the divider cell. So the pointer is safe to use
51132       ** later on.  
51133       **
51134       ** Unless SQLite is compiled in secure-delete mode. In this case,
51135       ** the dropCell() routine will overwrite the entire cell with zeroes.
51136       ** In this case, temporarily copy the cell into the aOvflSpace[]
51137       ** buffer. It will be copied out again as soon as the aSpace[] buffer
51138       ** is allocated.  */
51139       if( pBt->secureDelete ){
51140         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
51141         if( (iOff+szNew[i])>(int)pBt->usableSize ){
51142           rc = SQLITE_CORRUPT_BKPT;
51143           memset(apOld, 0, (i+1)*sizeof(MemPage*));
51144           goto balance_cleanup;
51145         }else{
51146           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
51147           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
51148         }
51149       }
51150       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
51151     }
51152   }
51153
51154   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
51155   ** alignment */
51156   nMaxCells = (nMaxCells + 3)&~3;
51157
51158   /*
51159   ** Allocate space for memory structures
51160   */
51161   k = pBt->pageSize + ROUND8(sizeof(MemPage));
51162   szScratch =
51163        nMaxCells*sizeof(u8*)                       /* apCell */
51164      + nMaxCells*sizeof(u16)                       /* szCell */
51165      + pBt->pageSize                               /* aSpace1 */
51166      + k*nOld;                                     /* Page copies (apCopy) */
51167   apCell = sqlite3ScratchMalloc( szScratch ); 
51168   if( apCell==0 ){
51169     rc = SQLITE_NOMEM;
51170     goto balance_cleanup;
51171   }
51172   szCell = (u16*)&apCell[nMaxCells];
51173   aSpace1 = (u8*)&szCell[nMaxCells];
51174   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
51175
51176   /*
51177   ** Load pointers to all cells on sibling pages and the divider cells
51178   ** into the local apCell[] array.  Make copies of the divider cells
51179   ** into space obtained from aSpace1[] and remove the the divider Cells
51180   ** from pParent.
51181   **
51182   ** If the siblings are on leaf pages, then the child pointers of the
51183   ** divider cells are stripped from the cells before they are copied
51184   ** into aSpace1[].  In this way, all cells in apCell[] are without
51185   ** child pointers.  If siblings are not leaves, then all cell in
51186   ** apCell[] include child pointers.  Either way, all cells in apCell[]
51187   ** are alike.
51188   **
51189   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
51190   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
51191   */
51192   leafCorrection = apOld[0]->leaf*4;
51193   leafData = apOld[0]->hasData;
51194   for(i=0; i<nOld; i++){
51195     int limit;
51196     
51197     /* Before doing anything else, take a copy of the i'th original sibling
51198     ** The rest of this function will use data from the copies rather
51199     ** that the original pages since the original pages will be in the
51200     ** process of being overwritten.  */
51201     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
51202     memcpy(pOld, apOld[i], sizeof(MemPage));
51203     pOld->aData = (void*)&pOld[1];
51204     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
51205
51206     limit = pOld->nCell+pOld->nOverflow;
51207     for(j=0; j<limit; j++){
51208       assert( nCell<nMaxCells );
51209       apCell[nCell] = findOverflowCell(pOld, j);
51210       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
51211       nCell++;
51212     }
51213     if( i<nOld-1 && !leafData){
51214       u16 sz = (u16)szNew[i];
51215       u8 *pTemp;
51216       assert( nCell<nMaxCells );
51217       szCell[nCell] = sz;
51218       pTemp = &aSpace1[iSpace1];
51219       iSpace1 += sz;
51220       assert( sz<=pBt->maxLocal+23 );
51221       assert( iSpace1<=pBt->pageSize );
51222       memcpy(pTemp, apDiv[i], sz);
51223       apCell[nCell] = pTemp+leafCorrection;
51224       assert( leafCorrection==0 || leafCorrection==4 );
51225       szCell[nCell] = szCell[nCell] - leafCorrection;
51226       if( !pOld->leaf ){
51227         assert( leafCorrection==0 );
51228         assert( pOld->hdrOffset==0 );
51229         /* The right pointer of the child page pOld becomes the left
51230         ** pointer of the divider cell */
51231         memcpy(apCell[nCell], &pOld->aData[8], 4);
51232       }else{
51233         assert( leafCorrection==4 );
51234         if( szCell[nCell]<4 ){
51235           /* Do not allow any cells smaller than 4 bytes. */
51236           szCell[nCell] = 4;
51237         }
51238       }
51239       nCell++;
51240     }
51241   }
51242
51243   /*
51244   ** Figure out the number of pages needed to hold all nCell cells.
51245   ** Store this number in "k".  Also compute szNew[] which is the total
51246   ** size of all cells on the i-th page and cntNew[] which is the index
51247   ** in apCell[] of the cell that divides page i from page i+1.  
51248   ** cntNew[k] should equal nCell.
51249   **
51250   ** Values computed by this block:
51251   **
51252   **           k: The total number of sibling pages
51253   **    szNew[i]: Spaced used on the i-th sibling page.
51254   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
51255   **              the right of the i-th sibling page.
51256   ** usableSpace: Number of bytes of space available on each sibling.
51257   ** 
51258   */
51259   usableSpace = pBt->usableSize - 12 + leafCorrection;
51260   for(subtotal=k=i=0; i<nCell; i++){
51261     assert( i<nMaxCells );
51262     subtotal += szCell[i] + 2;
51263     if( subtotal > usableSpace ){
51264       szNew[k] = subtotal - szCell[i];
51265       cntNew[k] = i;
51266       if( leafData ){ i--; }
51267       subtotal = 0;
51268       k++;
51269       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
51270     }
51271   }
51272   szNew[k] = subtotal;
51273   cntNew[k] = nCell;
51274   k++;
51275
51276   /*
51277   ** The packing computed by the previous block is biased toward the siblings
51278   ** on the left side.  The left siblings are always nearly full, while the
51279   ** right-most sibling might be nearly empty.  This block of code attempts
51280   ** to adjust the packing of siblings to get a better balance.
51281   **
51282   ** This adjustment is more than an optimization.  The packing above might
51283   ** be so out of balance as to be illegal.  For example, the right-most
51284   ** sibling might be completely empty.  This adjustment is not optional.
51285   */
51286   for(i=k-1; i>0; i--){
51287     int szRight = szNew[i];  /* Size of sibling on the right */
51288     int szLeft = szNew[i-1]; /* Size of sibling on the left */
51289     int r;              /* Index of right-most cell in left sibling */
51290     int d;              /* Index of first cell to the left of right sibling */
51291
51292     r = cntNew[i-1] - 1;
51293     d = r + 1 - leafData;
51294     assert( d<nMaxCells );
51295     assert( r<nMaxCells );
51296     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
51297       szRight += szCell[d] + 2;
51298       szLeft -= szCell[r] + 2;
51299       cntNew[i-1]--;
51300       r = cntNew[i-1] - 1;
51301       d = r + 1 - leafData;
51302     }
51303     szNew[i] = szRight;
51304     szNew[i-1] = szLeft;
51305   }
51306
51307   /* Either we found one or more cells (cntnew[0])>0) or pPage is
51308   ** a virtual root page.  A virtual root page is when the real root
51309   ** page is page 1 and we are the only child of that page.
51310   */
51311   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
51312
51313   TRACE(("BALANCE: old: %d %d %d  ",
51314     apOld[0]->pgno, 
51315     nOld>=2 ? apOld[1]->pgno : 0,
51316     nOld>=3 ? apOld[2]->pgno : 0
51317   ));
51318
51319   /*
51320   ** Allocate k new pages.  Reuse old pages where possible.
51321   */
51322   if( apOld[0]->pgno<=1 ){
51323     rc = SQLITE_CORRUPT_BKPT;
51324     goto balance_cleanup;
51325   }
51326   pageFlags = apOld[0]->aData[0];
51327   for(i=0; i<k; i++){
51328     MemPage *pNew;
51329     if( i<nOld ){
51330       pNew = apNew[i] = apOld[i];
51331       apOld[i] = 0;
51332       rc = sqlite3PagerWrite(pNew->pDbPage);
51333       nNew++;
51334       if( rc ) goto balance_cleanup;
51335     }else{
51336       assert( i>0 );
51337       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
51338       if( rc ) goto balance_cleanup;
51339       apNew[i] = pNew;
51340       nNew++;
51341
51342       /* Set the pointer-map entry for the new sibling page. */
51343       if( ISAUTOVACUUM ){
51344         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
51345         if( rc!=SQLITE_OK ){
51346           goto balance_cleanup;
51347         }
51348       }
51349     }
51350   }
51351
51352   /* Free any old pages that were not reused as new pages.
51353   */
51354   while( i<nOld ){
51355     freePage(apOld[i], &rc);
51356     if( rc ) goto balance_cleanup;
51357     releasePage(apOld[i]);
51358     apOld[i] = 0;
51359     i++;
51360   }
51361
51362   /*
51363   ** Put the new pages in accending order.  This helps to
51364   ** keep entries in the disk file in order so that a scan
51365   ** of the table is a linear scan through the file.  That
51366   ** in turn helps the operating system to deliver pages
51367   ** from the disk more rapidly.
51368   **
51369   ** An O(n^2) insertion sort algorithm is used, but since
51370   ** n is never more than NB (a small constant), that should
51371   ** not be a problem.
51372   **
51373   ** When NB==3, this one optimization makes the database
51374   ** about 25% faster for large insertions and deletions.
51375   */
51376   for(i=0; i<k-1; i++){
51377     int minV = apNew[i]->pgno;
51378     int minI = i;
51379     for(j=i+1; j<k; j++){
51380       if( apNew[j]->pgno<(unsigned)minV ){
51381         minI = j;
51382         minV = apNew[j]->pgno;
51383       }
51384     }
51385     if( minI>i ){
51386       int t;
51387       MemPage *pT;
51388       t = apNew[i]->pgno;
51389       pT = apNew[i];
51390       apNew[i] = apNew[minI];
51391       apNew[minI] = pT;
51392     }
51393   }
51394   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
51395     apNew[0]->pgno, szNew[0],
51396     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
51397     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
51398     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
51399     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
51400
51401   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
51402   put4byte(pRight, apNew[nNew-1]->pgno);
51403
51404   /*
51405   ** Evenly distribute the data in apCell[] across the new pages.
51406   ** Insert divider cells into pParent as necessary.
51407   */
51408   j = 0;
51409   for(i=0; i<nNew; i++){
51410     /* Assemble the new sibling page. */
51411     MemPage *pNew = apNew[i];
51412     assert( j<nMaxCells );
51413     zeroPage(pNew, pageFlags);
51414     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
51415     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
51416     assert( pNew->nOverflow==0 );
51417
51418     j = cntNew[i];
51419
51420     /* If the sibling page assembled above was not the right-most sibling,
51421     ** insert a divider cell into the parent page.
51422     */
51423     assert( i<nNew-1 || j==nCell );
51424     if( j<nCell ){
51425       u8 *pCell;
51426       u8 *pTemp;
51427       int sz;
51428
51429       assert( j<nMaxCells );
51430       pCell = apCell[j];
51431       sz = szCell[j] + leafCorrection;
51432       pTemp = &aOvflSpace[iOvflSpace];
51433       if( !pNew->leaf ){
51434         memcpy(&pNew->aData[8], pCell, 4);
51435       }else if( leafData ){
51436         /* If the tree is a leaf-data tree, and the siblings are leaves, 
51437         ** then there is no divider cell in apCell[]. Instead, the divider 
51438         ** cell consists of the integer key for the right-most cell of 
51439         ** the sibling-page assembled above only.
51440         */
51441         CellInfo info;
51442         j--;
51443         btreeParseCellPtr(pNew, apCell[j], &info);
51444         pCell = pTemp;
51445         sz = 4 + putVarint(&pCell[4], info.nKey);
51446         pTemp = 0;
51447       }else{
51448         pCell -= 4;
51449         /* Obscure case for non-leaf-data trees: If the cell at pCell was
51450         ** previously stored on a leaf node, and its reported size was 4
51451         ** bytes, then it may actually be smaller than this 
51452         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
51453         ** any cell). But it is important to pass the correct size to 
51454         ** insertCell(), so reparse the cell now.
51455         **
51456         ** Note that this can never happen in an SQLite data file, as all
51457         ** cells are at least 4 bytes. It only happens in b-trees used
51458         ** to evaluate "IN (SELECT ...)" and similar clauses.
51459         */
51460         if( szCell[j]==4 ){
51461           assert(leafCorrection==4);
51462           sz = cellSizePtr(pParent, pCell);
51463         }
51464       }
51465       iOvflSpace += sz;
51466       assert( sz<=pBt->maxLocal+23 );
51467       assert( iOvflSpace<=pBt->pageSize );
51468       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
51469       if( rc!=SQLITE_OK ) goto balance_cleanup;
51470       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
51471
51472       j++;
51473       nxDiv++;
51474     }
51475   }
51476   assert( j==nCell );
51477   assert( nOld>0 );
51478   assert( nNew>0 );
51479   if( (pageFlags & PTF_LEAF)==0 ){
51480     u8 *zChild = &apCopy[nOld-1]->aData[8];
51481     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
51482   }
51483
51484   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
51485     /* The root page of the b-tree now contains no cells. The only sibling
51486     ** page is the right-child of the parent. Copy the contents of the
51487     ** child page into the parent, decreasing the overall height of the
51488     ** b-tree structure by one. This is described as the "balance-shallower"
51489     ** sub-algorithm in some documentation.
51490     **
51491     ** If this is an auto-vacuum database, the call to copyNodeContent() 
51492     ** sets all pointer-map entries corresponding to database image pages 
51493     ** for which the pointer is stored within the content being copied.
51494     **
51495     ** The second assert below verifies that the child page is defragmented
51496     ** (it must be, as it was just reconstructed using assemblePage()). This
51497     ** is important if the parent page happens to be page 1 of the database
51498     ** image.  */
51499     assert( nNew==1 );
51500     assert( apNew[0]->nFree == 
51501         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
51502     );
51503     copyNodeContent(apNew[0], pParent, &rc);
51504     freePage(apNew[0], &rc);
51505   }else if( ISAUTOVACUUM ){
51506     /* Fix the pointer-map entries for all the cells that were shifted around. 
51507     ** There are several different types of pointer-map entries that need to
51508     ** be dealt with by this routine. Some of these have been set already, but
51509     ** many have not. The following is a summary:
51510     **
51511     **   1) The entries associated with new sibling pages that were not
51512     **      siblings when this function was called. These have already
51513     **      been set. We don't need to worry about old siblings that were
51514     **      moved to the free-list - the freePage() code has taken care
51515     **      of those.
51516     **
51517     **   2) The pointer-map entries associated with the first overflow
51518     **      page in any overflow chains used by new divider cells. These 
51519     **      have also already been taken care of by the insertCell() code.
51520     **
51521     **   3) If the sibling pages are not leaves, then the child pages of
51522     **      cells stored on the sibling pages may need to be updated.
51523     **
51524     **   4) If the sibling pages are not internal intkey nodes, then any
51525     **      overflow pages used by these cells may need to be updated
51526     **      (internal intkey nodes never contain pointers to overflow pages).
51527     **
51528     **   5) If the sibling pages are not leaves, then the pointer-map
51529     **      entries for the right-child pages of each sibling may need
51530     **      to be updated.
51531     **
51532     ** Cases 1 and 2 are dealt with above by other code. The next
51533     ** block deals with cases 3 and 4 and the one after that, case 5. Since
51534     ** setting a pointer map entry is a relatively expensive operation, this
51535     ** code only sets pointer map entries for child or overflow pages that have
51536     ** actually moved between pages.  */
51537     MemPage *pNew = apNew[0];
51538     MemPage *pOld = apCopy[0];
51539     int nOverflow = pOld->nOverflow;
51540     int iNextOld = pOld->nCell + nOverflow;
51541     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
51542     j = 0;                             /* Current 'old' sibling page */
51543     k = 0;                             /* Current 'new' sibling page */
51544     for(i=0; i<nCell; i++){
51545       int isDivider = 0;
51546       while( i==iNextOld ){
51547         /* Cell i is the cell immediately following the last cell on old
51548         ** sibling page j. If the siblings are not leaf pages of an
51549         ** intkey b-tree, then cell i was a divider cell. */
51550         pOld = apCopy[++j];
51551         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
51552         if( pOld->nOverflow ){
51553           nOverflow = pOld->nOverflow;
51554           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
51555         }
51556         isDivider = !leafData;  
51557       }
51558
51559       assert(nOverflow>0 || iOverflow<i );
51560       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
51561       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
51562       if( i==iOverflow ){
51563         isDivider = 1;
51564         if( (--nOverflow)>0 ){
51565           iOverflow++;
51566         }
51567       }
51568
51569       if( i==cntNew[k] ){
51570         /* Cell i is the cell immediately following the last cell on new
51571         ** sibling page k. If the siblings are not leaf pages of an
51572         ** intkey b-tree, then cell i is a divider cell.  */
51573         pNew = apNew[++k];
51574         if( !leafData ) continue;
51575       }
51576       assert( j<nOld );
51577       assert( k<nNew );
51578
51579       /* If the cell was originally divider cell (and is not now) or
51580       ** an overflow cell, or if the cell was located on a different sibling
51581       ** page before the balancing, then the pointer map entries associated
51582       ** with any child or overflow pages need to be updated.  */
51583       if( isDivider || pOld->pgno!=pNew->pgno ){
51584         if( !leafCorrection ){
51585           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
51586         }
51587         if( szCell[i]>pNew->minLocal ){
51588           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
51589         }
51590       }
51591     }
51592
51593     if( !leafCorrection ){
51594       for(i=0; i<nNew; i++){
51595         u32 key = get4byte(&apNew[i]->aData[8]);
51596         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
51597       }
51598     }
51599
51600 #if 0
51601     /* The ptrmapCheckPages() contains assert() statements that verify that
51602     ** all pointer map pages are set correctly. This is helpful while 
51603     ** debugging. This is usually disabled because a corrupt database may
51604     ** cause an assert() statement to fail.  */
51605     ptrmapCheckPages(apNew, nNew);
51606     ptrmapCheckPages(&pParent, 1);
51607 #endif
51608   }
51609
51610   assert( pParent->isInit );
51611   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
51612           nOld, nNew, nCell));
51613
51614   /*
51615   ** Cleanup before returning.
51616   */
51617 balance_cleanup:
51618   sqlite3ScratchFree(apCell);
51619   for(i=0; i<nOld; i++){
51620     releasePage(apOld[i]);
51621   }
51622   for(i=0; i<nNew; i++){
51623     releasePage(apNew[i]);
51624   }
51625
51626   return rc;
51627 }
51628
51629
51630 /*
51631 ** This function is called when the root page of a b-tree structure is
51632 ** overfull (has one or more overflow pages).
51633 **
51634 ** A new child page is allocated and the contents of the current root
51635 ** page, including overflow cells, are copied into the child. The root
51636 ** page is then overwritten to make it an empty page with the right-child 
51637 ** pointer pointing to the new page.
51638 **
51639 ** Before returning, all pointer-map entries corresponding to pages 
51640 ** that the new child-page now contains pointers to are updated. The
51641 ** entry corresponding to the new right-child pointer of the root
51642 ** page is also updated.
51643 **
51644 ** If successful, *ppChild is set to contain a reference to the child 
51645 ** page and SQLITE_OK is returned. In this case the caller is required
51646 ** to call releasePage() on *ppChild exactly once. If an error occurs,
51647 ** an error code is returned and *ppChild is set to 0.
51648 */
51649 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
51650   int rc;                        /* Return value from subprocedures */
51651   MemPage *pChild = 0;           /* Pointer to a new child page */
51652   Pgno pgnoChild = 0;            /* Page number of the new child page */
51653   BtShared *pBt = pRoot->pBt;    /* The BTree */
51654
51655   assert( pRoot->nOverflow>0 );
51656   assert( sqlite3_mutex_held(pBt->mutex) );
51657
51658   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
51659   ** page that will become the new right-child of pPage. Copy the contents
51660   ** of the node stored on pRoot into the new child page.
51661   */
51662   rc = sqlite3PagerWrite(pRoot->pDbPage);
51663   if( rc==SQLITE_OK ){
51664     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
51665     copyNodeContent(pRoot, pChild, &rc);
51666     if( ISAUTOVACUUM ){
51667       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
51668     }
51669   }
51670   if( rc ){
51671     *ppChild = 0;
51672     releasePage(pChild);
51673     return rc;
51674   }
51675   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
51676   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
51677   assert( pChild->nCell==pRoot->nCell );
51678
51679   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
51680
51681   /* Copy the overflow cells from pRoot to pChild */
51682   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
51683   pChild->nOverflow = pRoot->nOverflow;
51684
51685   /* Zero the contents of pRoot. Then install pChild as the right-child. */
51686   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
51687   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
51688
51689   *ppChild = pChild;
51690   return SQLITE_OK;
51691 }
51692
51693 /*
51694 ** The page that pCur currently points to has just been modified in
51695 ** some way. This function figures out if this modification means the
51696 ** tree needs to be balanced, and if so calls the appropriate balancing 
51697 ** routine. Balancing routines are:
51698 **
51699 **   balance_quick()
51700 **   balance_deeper()
51701 **   balance_nonroot()
51702 */
51703 static int balance(BtCursor *pCur){
51704   int rc = SQLITE_OK;
51705   const int nMin = pCur->pBt->usableSize * 2 / 3;
51706   u8 aBalanceQuickSpace[13];
51707   u8 *pFree = 0;
51708
51709   TESTONLY( int balance_quick_called = 0 );
51710   TESTONLY( int balance_deeper_called = 0 );
51711
51712   do {
51713     int iPage = pCur->iPage;
51714     MemPage *pPage = pCur->apPage[iPage];
51715
51716     if( iPage==0 ){
51717       if( pPage->nOverflow ){
51718         /* The root page of the b-tree is overfull. In this case call the
51719         ** balance_deeper() function to create a new child for the root-page
51720         ** and copy the current contents of the root-page to it. The
51721         ** next iteration of the do-loop will balance the child page.
51722         */ 
51723         assert( (balance_deeper_called++)==0 );
51724         rc = balance_deeper(pPage, &pCur->apPage[1]);
51725         if( rc==SQLITE_OK ){
51726           pCur->iPage = 1;
51727           pCur->aiIdx[0] = 0;
51728           pCur->aiIdx[1] = 0;
51729           assert( pCur->apPage[1]->nOverflow );
51730         }
51731       }else{
51732         break;
51733       }
51734     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
51735       break;
51736     }else{
51737       MemPage * const pParent = pCur->apPage[iPage-1];
51738       int const iIdx = pCur->aiIdx[iPage-1];
51739
51740       rc = sqlite3PagerWrite(pParent->pDbPage);
51741       if( rc==SQLITE_OK ){
51742 #ifndef SQLITE_OMIT_QUICKBALANCE
51743         if( pPage->hasData
51744          && pPage->nOverflow==1
51745          && pPage->aOvfl[0].idx==pPage->nCell
51746          && pParent->pgno!=1
51747          && pParent->nCell==iIdx
51748         ){
51749           /* Call balance_quick() to create a new sibling of pPage on which
51750           ** to store the overflow cell. balance_quick() inserts a new cell
51751           ** into pParent, which may cause pParent overflow. If this
51752           ** happens, the next interation of the do-loop will balance pParent 
51753           ** use either balance_nonroot() or balance_deeper(). Until this
51754           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
51755           ** buffer. 
51756           **
51757           ** The purpose of the following assert() is to check that only a
51758           ** single call to balance_quick() is made for each call to this
51759           ** function. If this were not verified, a subtle bug involving reuse
51760           ** of the aBalanceQuickSpace[] might sneak in.
51761           */
51762           assert( (balance_quick_called++)==0 );
51763           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
51764         }else
51765 #endif
51766         {
51767           /* In this case, call balance_nonroot() to redistribute cells
51768           ** between pPage and up to 2 of its sibling pages. This involves
51769           ** modifying the contents of pParent, which may cause pParent to
51770           ** become overfull or underfull. The next iteration of the do-loop
51771           ** will balance the parent page to correct this.
51772           ** 
51773           ** If the parent page becomes overfull, the overflow cell or cells
51774           ** are stored in the pSpace buffer allocated immediately below. 
51775           ** A subsequent iteration of the do-loop will deal with this by
51776           ** calling balance_nonroot() (balance_deeper() may be called first,
51777           ** but it doesn't deal with overflow cells - just moves them to a
51778           ** different page). Once this subsequent call to balance_nonroot() 
51779           ** has completed, it is safe to release the pSpace buffer used by
51780           ** the previous call, as the overflow cell data will have been 
51781           ** copied either into the body of a database page or into the new
51782           ** pSpace buffer passed to the latter call to balance_nonroot().
51783           */
51784           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
51785           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
51786           if( pFree ){
51787             /* If pFree is not NULL, it points to the pSpace buffer used 
51788             ** by a previous call to balance_nonroot(). Its contents are
51789             ** now stored either on real database pages or within the 
51790             ** new pSpace buffer, so it may be safely freed here. */
51791             sqlite3PageFree(pFree);
51792           }
51793
51794           /* The pSpace buffer will be freed after the next call to
51795           ** balance_nonroot(), or just before this function returns, whichever
51796           ** comes first. */
51797           pFree = pSpace;
51798         }
51799       }
51800
51801       pPage->nOverflow = 0;
51802
51803       /* The next iteration of the do-loop balances the parent page. */
51804       releasePage(pPage);
51805       pCur->iPage--;
51806     }
51807   }while( rc==SQLITE_OK );
51808
51809   if( pFree ){
51810     sqlite3PageFree(pFree);
51811   }
51812   return rc;
51813 }
51814
51815
51816 /*
51817 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
51818 ** and the data is given by (pData,nData).  The cursor is used only to
51819 ** define what table the record should be inserted into.  The cursor
51820 ** is left pointing at a random location.
51821 **
51822 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
51823 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
51824 **
51825 ** If the seekResult parameter is non-zero, then a successful call to
51826 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
51827 ** been performed. seekResult is the search result returned (a negative
51828 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
51829 ** a positive value if pCur points at an etry that is larger than 
51830 ** (pKey, nKey)). 
51831 **
51832 ** If the seekResult parameter is non-zero, then the caller guarantees that
51833 ** cursor pCur is pointing at the existing copy of a row that is to be
51834 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
51835 ** point to any entry or to no entry at all and so this function has to seek
51836 ** the cursor before the new key can be inserted.
51837 */
51838 SQLITE_PRIVATE int sqlite3BtreeInsert(
51839   BtCursor *pCur,                /* Insert data into the table of this cursor */
51840   const void *pKey, i64 nKey,    /* The key of the new record */
51841   const void *pData, int nData,  /* The data of the new record */
51842   int nZero,                     /* Number of extra 0 bytes to append to data */
51843   int appendBias,                /* True if this is likely an append */
51844   int seekResult                 /* Result of prior MovetoUnpacked() call */
51845 ){
51846   int rc;
51847   int loc = seekResult;          /* -1: before desired location  +1: after */
51848   int szNew = 0;
51849   int idx;
51850   MemPage *pPage;
51851   Btree *p = pCur->pBtree;
51852   BtShared *pBt = p->pBt;
51853   unsigned char *oldCell;
51854   unsigned char *newCell = 0;
51855
51856   if( pCur->eState==CURSOR_FAULT ){
51857     assert( pCur->skipNext!=SQLITE_OK );
51858     return pCur->skipNext;
51859   }
51860
51861   assert( cursorHoldsMutex(pCur) );
51862   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
51863   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
51864
51865   /* Assert that the caller has been consistent. If this cursor was opened
51866   ** expecting an index b-tree, then the caller should be inserting blob
51867   ** keys with no associated data. If the cursor was opened expecting an
51868   ** intkey table, the caller should be inserting integer keys with a
51869   ** blob of associated data.  */
51870   assert( (pKey==0)==(pCur->pKeyInfo==0) );
51871
51872   /* If this is an insert into a table b-tree, invalidate any incrblob 
51873   ** cursors open on the row being replaced (assuming this is a replace
51874   ** operation - if it is not, the following is a no-op).  */
51875   if( pCur->pKeyInfo==0 ){
51876     invalidateIncrblobCursors(p, nKey, 0);
51877   }
51878
51879   /* Save the positions of any other cursors open on this table.
51880   **
51881   ** In some cases, the call to btreeMoveto() below is a no-op. For
51882   ** example, when inserting data into a table with auto-generated integer
51883   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
51884   ** integer key to use. It then calls this function to actually insert the 
51885   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
51886   ** that the cursor is already where it needs to be and returns without
51887   ** doing any work. To avoid thwarting these optimizations, it is important
51888   ** not to clear the cursor here.
51889   */
51890   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
51891   if( rc ) return rc;
51892   if( !loc ){
51893     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
51894     if( rc ) return rc;
51895   }
51896   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
51897
51898   pPage = pCur->apPage[pCur->iPage];
51899   assert( pPage->intKey || nKey>=0 );
51900   assert( pPage->leaf || !pPage->intKey );
51901
51902   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
51903           pCur->pgnoRoot, nKey, nData, pPage->pgno,
51904           loc==0 ? "overwrite" : "new entry"));
51905   assert( pPage->isInit );
51906   allocateTempSpace(pBt);
51907   newCell = pBt->pTmpSpace;
51908   if( newCell==0 ) return SQLITE_NOMEM;
51909   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
51910   if( rc ) goto end_insert;
51911   assert( szNew==cellSizePtr(pPage, newCell) );
51912   assert( szNew<=MX_CELL_SIZE(pBt) );
51913   idx = pCur->aiIdx[pCur->iPage];
51914   if( loc==0 ){
51915     u16 szOld;
51916     assert( idx<pPage->nCell );
51917     rc = sqlite3PagerWrite(pPage->pDbPage);
51918     if( rc ){
51919       goto end_insert;
51920     }
51921     oldCell = findCell(pPage, idx);
51922     if( !pPage->leaf ){
51923       memcpy(newCell, oldCell, 4);
51924     }
51925     szOld = cellSizePtr(pPage, oldCell);
51926     rc = clearCell(pPage, oldCell);
51927     dropCell(pPage, idx, szOld, &rc);
51928     if( rc ) goto end_insert;
51929   }else if( loc<0 && pPage->nCell>0 ){
51930     assert( pPage->leaf );
51931     idx = ++pCur->aiIdx[pCur->iPage];
51932   }else{
51933     assert( pPage->leaf );
51934   }
51935   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
51936   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
51937
51938   /* If no error has occured and pPage has an overflow cell, call balance() 
51939   ** to redistribute the cells within the tree. Since balance() may move
51940   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
51941   ** variables.
51942   **
51943   ** Previous versions of SQLite called moveToRoot() to move the cursor
51944   ** back to the root page as balance() used to invalidate the contents
51945   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
51946   ** set the cursor state to "invalid". This makes common insert operations
51947   ** slightly faster.
51948   **
51949   ** There is a subtle but important optimization here too. When inserting
51950   ** multiple records into an intkey b-tree using a single cursor (as can
51951   ** happen while processing an "INSERT INTO ... SELECT" statement), it
51952   ** is advantageous to leave the cursor pointing to the last entry in
51953   ** the b-tree if possible. If the cursor is left pointing to the last
51954   ** entry in the table, and the next row inserted has an integer key
51955   ** larger than the largest existing key, it is possible to insert the
51956   ** row without seeking the cursor. This can be a big performance boost.
51957   */
51958   pCur->info.nSize = 0;
51959   pCur->validNKey = 0;
51960   if( rc==SQLITE_OK && pPage->nOverflow ){
51961     rc = balance(pCur);
51962
51963     /* Must make sure nOverflow is reset to zero even if the balance()
51964     ** fails. Internal data structure corruption will result otherwise. 
51965     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
51966     ** from trying to save the current position of the cursor.  */
51967     pCur->apPage[pCur->iPage]->nOverflow = 0;
51968     pCur->eState = CURSOR_INVALID;
51969   }
51970   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
51971
51972 end_insert:
51973   return rc;
51974 }
51975
51976 /*
51977 ** Delete the entry that the cursor is pointing to.  The cursor
51978 ** is left pointing at a arbitrary location.
51979 */
51980 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
51981   Btree *p = pCur->pBtree;
51982   BtShared *pBt = p->pBt;              
51983   int rc;                              /* Return code */
51984   MemPage *pPage;                      /* Page to delete cell from */
51985   unsigned char *pCell;                /* Pointer to cell to delete */
51986   int iCellIdx;                        /* Index of cell to delete */
51987   int iCellDepth;                      /* Depth of node containing pCell */ 
51988
51989   assert( cursorHoldsMutex(pCur) );
51990   assert( pBt->inTransaction==TRANS_WRITE );
51991   assert( !pBt->readOnly );
51992   assert( pCur->wrFlag );
51993   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
51994   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
51995
51996   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
51997    || NEVER(pCur->eState!=CURSOR_VALID)
51998   ){
51999     return SQLITE_ERROR;  /* Something has gone awry. */
52000   }
52001
52002   /* If this is a delete operation to remove a row from a table b-tree,
52003   ** invalidate any incrblob cursors open on the row being deleted.  */
52004   if( pCur->pKeyInfo==0 ){
52005     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
52006   }
52007
52008   iCellDepth = pCur->iPage;
52009   iCellIdx = pCur->aiIdx[iCellDepth];
52010   pPage = pCur->apPage[iCellDepth];
52011   pCell = findCell(pPage, iCellIdx);
52012
52013   /* If the page containing the entry to delete is not a leaf page, move
52014   ** the cursor to the largest entry in the tree that is smaller than
52015   ** the entry being deleted. This cell will replace the cell being deleted
52016   ** from the internal node. The 'previous' entry is used for this instead
52017   ** of the 'next' entry, as the previous entry is always a part of the
52018   ** sub-tree headed by the child page of the cell being deleted. This makes
52019   ** balancing the tree following the delete operation easier.  */
52020   if( !pPage->leaf ){
52021     int notUsed;
52022     rc = sqlite3BtreePrevious(pCur, &notUsed);
52023     if( rc ) return rc;
52024   }
52025
52026   /* Save the positions of any other cursors open on this table before
52027   ** making any modifications. Make the page containing the entry to be 
52028   ** deleted writable. Then free any overflow pages associated with the 
52029   ** entry and finally remove the cell itself from within the page.  
52030   */
52031   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
52032   if( rc ) return rc;
52033   rc = sqlite3PagerWrite(pPage->pDbPage);
52034   if( rc ) return rc;
52035   rc = clearCell(pPage, pCell);
52036   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
52037   if( rc ) return rc;
52038
52039   /* If the cell deleted was not located on a leaf page, then the cursor
52040   ** is currently pointing to the largest entry in the sub-tree headed
52041   ** by the child-page of the cell that was just deleted from an internal
52042   ** node. The cell from the leaf node needs to be moved to the internal
52043   ** node to replace the deleted cell.  */
52044   if( !pPage->leaf ){
52045     MemPage *pLeaf = pCur->apPage[pCur->iPage];
52046     int nCell;
52047     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
52048     unsigned char *pTmp;
52049
52050     pCell = findCell(pLeaf, pLeaf->nCell-1);
52051     nCell = cellSizePtr(pLeaf, pCell);
52052     assert( MX_CELL_SIZE(pBt)>=nCell );
52053
52054     allocateTempSpace(pBt);
52055     pTmp = pBt->pTmpSpace;
52056
52057     rc = sqlite3PagerWrite(pLeaf->pDbPage);
52058     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
52059     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
52060     if( rc ) return rc;
52061   }
52062
52063   /* Balance the tree. If the entry deleted was located on a leaf page,
52064   ** then the cursor still points to that page. In this case the first
52065   ** call to balance() repairs the tree, and the if(...) condition is
52066   ** never true.
52067   **
52068   ** Otherwise, if the entry deleted was on an internal node page, then
52069   ** pCur is pointing to the leaf page from which a cell was removed to
52070   ** replace the cell deleted from the internal node. This is slightly
52071   ** tricky as the leaf node may be underfull, and the internal node may
52072   ** be either under or overfull. In this case run the balancing algorithm
52073   ** on the leaf node first. If the balance proceeds far enough up the
52074   ** tree that we can be sure that any problem in the internal node has
52075   ** been corrected, so be it. Otherwise, after balancing the leaf node,
52076   ** walk the cursor up the tree to the internal node and balance it as 
52077   ** well.  */
52078   rc = balance(pCur);
52079   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
52080     while( pCur->iPage>iCellDepth ){
52081       releasePage(pCur->apPage[pCur->iPage--]);
52082     }
52083     rc = balance(pCur);
52084   }
52085
52086   if( rc==SQLITE_OK ){
52087     moveToRoot(pCur);
52088   }
52089   return rc;
52090 }
52091
52092 /*
52093 ** Create a new BTree table.  Write into *piTable the page
52094 ** number for the root page of the new table.
52095 **
52096 ** The type of type is determined by the flags parameter.  Only the
52097 ** following values of flags are currently in use.  Other values for
52098 ** flags might not work:
52099 **
52100 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
52101 **     BTREE_ZERODATA                  Used for SQL indices
52102 */
52103 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
52104   BtShared *pBt = p->pBt;
52105   MemPage *pRoot;
52106   Pgno pgnoRoot;
52107   int rc;
52108   int ptfFlags;          /* Page-type flage for the root page of new table */
52109
52110   assert( sqlite3BtreeHoldsMutex(p) );
52111   assert( pBt->inTransaction==TRANS_WRITE );
52112   assert( !pBt->readOnly );
52113
52114 #ifdef SQLITE_OMIT_AUTOVACUUM
52115   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
52116   if( rc ){
52117     return rc;
52118   }
52119 #else
52120   if( pBt->autoVacuum ){
52121     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
52122     MemPage *pPageMove; /* The page to move to. */
52123
52124     /* Creating a new table may probably require moving an existing database
52125     ** to make room for the new tables root page. In case this page turns
52126     ** out to be an overflow page, delete all overflow page-map caches
52127     ** held by open cursors.
52128     */
52129     invalidateAllOverflowCache(pBt);
52130
52131     /* Read the value of meta[3] from the database to determine where the
52132     ** root page of the new table should go. meta[3] is the largest root-page
52133     ** created so far, so the new root-page is (meta[3]+1).
52134     */
52135     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
52136     pgnoRoot++;
52137
52138     /* The new root-page may not be allocated on a pointer-map page, or the
52139     ** PENDING_BYTE page.
52140     */
52141     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
52142         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
52143       pgnoRoot++;
52144     }
52145     assert( pgnoRoot>=3 );
52146
52147     /* Allocate a page. The page that currently resides at pgnoRoot will
52148     ** be moved to the allocated page (unless the allocated page happens
52149     ** to reside at pgnoRoot).
52150     */
52151     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
52152     if( rc!=SQLITE_OK ){
52153       return rc;
52154     }
52155
52156     if( pgnoMove!=pgnoRoot ){
52157       /* pgnoRoot is the page that will be used for the root-page of
52158       ** the new table (assuming an error did not occur). But we were
52159       ** allocated pgnoMove. If required (i.e. if it was not allocated
52160       ** by extending the file), the current page at position pgnoMove
52161       ** is already journaled.
52162       */
52163       u8 eType = 0;
52164       Pgno iPtrPage = 0;
52165
52166       releasePage(pPageMove);
52167
52168       /* Move the page currently at pgnoRoot to pgnoMove. */
52169       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
52170       if( rc!=SQLITE_OK ){
52171         return rc;
52172       }
52173       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
52174       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
52175         rc = SQLITE_CORRUPT_BKPT;
52176       }
52177       if( rc!=SQLITE_OK ){
52178         releasePage(pRoot);
52179         return rc;
52180       }
52181       assert( eType!=PTRMAP_ROOTPAGE );
52182       assert( eType!=PTRMAP_FREEPAGE );
52183       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
52184       releasePage(pRoot);
52185
52186       /* Obtain the page at pgnoRoot */
52187       if( rc!=SQLITE_OK ){
52188         return rc;
52189       }
52190       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
52191       if( rc!=SQLITE_OK ){
52192         return rc;
52193       }
52194       rc = sqlite3PagerWrite(pRoot->pDbPage);
52195       if( rc!=SQLITE_OK ){
52196         releasePage(pRoot);
52197         return rc;
52198       }
52199     }else{
52200       pRoot = pPageMove;
52201     } 
52202
52203     /* Update the pointer-map and meta-data with the new root-page number. */
52204     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
52205     if( rc ){
52206       releasePage(pRoot);
52207       return rc;
52208     }
52209
52210     /* When the new root page was allocated, page 1 was made writable in
52211     ** order either to increase the database filesize, or to decrement the
52212     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
52213     */
52214     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
52215     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
52216     if( NEVER(rc) ){
52217       releasePage(pRoot);
52218       return rc;
52219     }
52220
52221   }else{
52222     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
52223     if( rc ) return rc;
52224   }
52225 #endif
52226   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
52227   if( createTabFlags & BTREE_INTKEY ){
52228     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
52229   }else{
52230     ptfFlags = PTF_ZERODATA | PTF_LEAF;
52231   }
52232   zeroPage(pRoot, ptfFlags);
52233   sqlite3PagerUnref(pRoot->pDbPage);
52234   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
52235   *piTable = (int)pgnoRoot;
52236   return SQLITE_OK;
52237 }
52238 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
52239   int rc;
52240   sqlite3BtreeEnter(p);
52241   rc = btreeCreateTable(p, piTable, flags);
52242   sqlite3BtreeLeave(p);
52243   return rc;
52244 }
52245
52246 /*
52247 ** Erase the given database page and all its children.  Return
52248 ** the page to the freelist.
52249 */
52250 static int clearDatabasePage(
52251   BtShared *pBt,           /* The BTree that contains the table */
52252   Pgno pgno,               /* Page number to clear */
52253   int freePageFlag,        /* Deallocate page if true */
52254   int *pnChange            /* Add number of Cells freed to this counter */
52255 ){
52256   MemPage *pPage;
52257   int rc;
52258   unsigned char *pCell;
52259   int i;
52260
52261   assert( sqlite3_mutex_held(pBt->mutex) );
52262   if( pgno>btreePagecount(pBt) ){
52263     return SQLITE_CORRUPT_BKPT;
52264   }
52265
52266   rc = getAndInitPage(pBt, pgno, &pPage);
52267   if( rc ) return rc;
52268   for(i=0; i<pPage->nCell; i++){
52269     pCell = findCell(pPage, i);
52270     if( !pPage->leaf ){
52271       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
52272       if( rc ) goto cleardatabasepage_out;
52273     }
52274     rc = clearCell(pPage, pCell);
52275     if( rc ) goto cleardatabasepage_out;
52276   }
52277   if( !pPage->leaf ){
52278     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
52279     if( rc ) goto cleardatabasepage_out;
52280   }else if( pnChange ){
52281     assert( pPage->intKey );
52282     *pnChange += pPage->nCell;
52283   }
52284   if( freePageFlag ){
52285     freePage(pPage, &rc);
52286   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
52287     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
52288   }
52289
52290 cleardatabasepage_out:
52291   releasePage(pPage);
52292   return rc;
52293 }
52294
52295 /*
52296 ** Delete all information from a single table in the database.  iTable is
52297 ** the page number of the root of the table.  After this routine returns,
52298 ** the root page is empty, but still exists.
52299 **
52300 ** This routine will fail with SQLITE_LOCKED if there are any open
52301 ** read cursors on the table.  Open write cursors are moved to the
52302 ** root of the table.
52303 **
52304 ** If pnChange is not NULL, then table iTable must be an intkey table. The
52305 ** integer value pointed to by pnChange is incremented by the number of
52306 ** entries in the table.
52307 */
52308 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
52309   int rc;
52310   BtShared *pBt = p->pBt;
52311   sqlite3BtreeEnter(p);
52312   assert( p->inTrans==TRANS_WRITE );
52313
52314   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
52315   ** is the root of a table b-tree - if it is not, the following call is
52316   ** a no-op).  */
52317   invalidateIncrblobCursors(p, 0, 1);
52318
52319   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
52320   if( SQLITE_OK==rc ){
52321     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
52322   }
52323   sqlite3BtreeLeave(p);
52324   return rc;
52325 }
52326
52327 /*
52328 ** Erase all information in a table and add the root of the table to
52329 ** the freelist.  Except, the root of the principle table (the one on
52330 ** page 1) is never added to the freelist.
52331 **
52332 ** This routine will fail with SQLITE_LOCKED if there are any open
52333 ** cursors on the table.
52334 **
52335 ** If AUTOVACUUM is enabled and the page at iTable is not the last
52336 ** root page in the database file, then the last root page 
52337 ** in the database file is moved into the slot formerly occupied by
52338 ** iTable and that last slot formerly occupied by the last root page
52339 ** is added to the freelist instead of iTable.  In this say, all
52340 ** root pages are kept at the beginning of the database file, which
52341 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
52342 ** page number that used to be the last root page in the file before
52343 ** the move.  If no page gets moved, *piMoved is set to 0.
52344 ** The last root page is recorded in meta[3] and the value of
52345 ** meta[3] is updated by this procedure.
52346 */
52347 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
52348   int rc;
52349   MemPage *pPage = 0;
52350   BtShared *pBt = p->pBt;
52351
52352   assert( sqlite3BtreeHoldsMutex(p) );
52353   assert( p->inTrans==TRANS_WRITE );
52354
52355   /* It is illegal to drop a table if any cursors are open on the
52356   ** database. This is because in auto-vacuum mode the backend may
52357   ** need to move another root-page to fill a gap left by the deleted
52358   ** root page. If an open cursor was using this page a problem would 
52359   ** occur.
52360   **
52361   ** This error is caught long before control reaches this point.
52362   */
52363   if( NEVER(pBt->pCursor) ){
52364     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
52365     return SQLITE_LOCKED_SHAREDCACHE;
52366   }
52367
52368   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
52369   if( rc ) return rc;
52370   rc = sqlite3BtreeClearTable(p, iTable, 0);
52371   if( rc ){
52372     releasePage(pPage);
52373     return rc;
52374   }
52375
52376   *piMoved = 0;
52377
52378   if( iTable>1 ){
52379 #ifdef SQLITE_OMIT_AUTOVACUUM
52380     freePage(pPage, &rc);
52381     releasePage(pPage);
52382 #else
52383     if( pBt->autoVacuum ){
52384       Pgno maxRootPgno;
52385       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
52386
52387       if( iTable==maxRootPgno ){
52388         /* If the table being dropped is the table with the largest root-page
52389         ** number in the database, put the root page on the free list. 
52390         */
52391         freePage(pPage, &rc);
52392         releasePage(pPage);
52393         if( rc!=SQLITE_OK ){
52394           return rc;
52395         }
52396       }else{
52397         /* The table being dropped does not have the largest root-page
52398         ** number in the database. So move the page that does into the 
52399         ** gap left by the deleted root-page.
52400         */
52401         MemPage *pMove;
52402         releasePage(pPage);
52403         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
52404         if( rc!=SQLITE_OK ){
52405           return rc;
52406         }
52407         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
52408         releasePage(pMove);
52409         if( rc!=SQLITE_OK ){
52410           return rc;
52411         }
52412         pMove = 0;
52413         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
52414         freePage(pMove, &rc);
52415         releasePage(pMove);
52416         if( rc!=SQLITE_OK ){
52417           return rc;
52418         }
52419         *piMoved = maxRootPgno;
52420       }
52421
52422       /* Set the new 'max-root-page' value in the database header. This
52423       ** is the old value less one, less one more if that happens to
52424       ** be a root-page number, less one again if that is the
52425       ** PENDING_BYTE_PAGE.
52426       */
52427       maxRootPgno--;
52428       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
52429              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
52430         maxRootPgno--;
52431       }
52432       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
52433
52434       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
52435     }else{
52436       freePage(pPage, &rc);
52437       releasePage(pPage);
52438     }
52439 #endif
52440   }else{
52441     /* If sqlite3BtreeDropTable was called on page 1.
52442     ** This really never should happen except in a corrupt
52443     ** database. 
52444     */
52445     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
52446     releasePage(pPage);
52447   }
52448   return rc;  
52449 }
52450 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
52451   int rc;
52452   sqlite3BtreeEnter(p);
52453   rc = btreeDropTable(p, iTable, piMoved);
52454   sqlite3BtreeLeave(p);
52455   return rc;
52456 }
52457
52458
52459 /*
52460 ** This function may only be called if the b-tree connection already
52461 ** has a read or write transaction open on the database.
52462 **
52463 ** Read the meta-information out of a database file.  Meta[0]
52464 ** is the number of free pages currently in the database.  Meta[1]
52465 ** through meta[15] are available for use by higher layers.  Meta[0]
52466 ** is read-only, the others are read/write.
52467 ** 
52468 ** The schema layer numbers meta values differently.  At the schema
52469 ** layer (and the SetCookie and ReadCookie opcodes) the number of
52470 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
52471 */
52472 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
52473   BtShared *pBt = p->pBt;
52474
52475   sqlite3BtreeEnter(p);
52476   assert( p->inTrans>TRANS_NONE );
52477   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
52478   assert( pBt->pPage1 );
52479   assert( idx>=0 && idx<=15 );
52480
52481   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
52482
52483   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
52484   ** database, mark the database as read-only.  */
52485 #ifdef SQLITE_OMIT_AUTOVACUUM
52486   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
52487 #endif
52488
52489   sqlite3BtreeLeave(p);
52490 }
52491
52492 /*
52493 ** Write meta-information back into the database.  Meta[0] is
52494 ** read-only and may not be written.
52495 */
52496 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
52497   BtShared *pBt = p->pBt;
52498   unsigned char *pP1;
52499   int rc;
52500   assert( idx>=1 && idx<=15 );
52501   sqlite3BtreeEnter(p);
52502   assert( p->inTrans==TRANS_WRITE );
52503   assert( pBt->pPage1!=0 );
52504   pP1 = pBt->pPage1->aData;
52505   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52506   if( rc==SQLITE_OK ){
52507     put4byte(&pP1[36 + idx*4], iMeta);
52508 #ifndef SQLITE_OMIT_AUTOVACUUM
52509     if( idx==BTREE_INCR_VACUUM ){
52510       assert( pBt->autoVacuum || iMeta==0 );
52511       assert( iMeta==0 || iMeta==1 );
52512       pBt->incrVacuum = (u8)iMeta;
52513     }
52514 #endif
52515   }
52516   sqlite3BtreeLeave(p);
52517   return rc;
52518 }
52519
52520 #ifndef SQLITE_OMIT_BTREECOUNT
52521 /*
52522 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
52523 ** number of entries in the b-tree and write the result to *pnEntry.
52524 **
52525 ** SQLITE_OK is returned if the operation is successfully executed. 
52526 ** Otherwise, if an error is encountered (i.e. an IO error or database
52527 ** corruption) an SQLite error code is returned.
52528 */
52529 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
52530   i64 nEntry = 0;                      /* Value to return in *pnEntry */
52531   int rc;                              /* Return code */
52532   rc = moveToRoot(pCur);
52533
52534   /* Unless an error occurs, the following loop runs one iteration for each
52535   ** page in the B-Tree structure (not including overflow pages). 
52536   */
52537   while( rc==SQLITE_OK ){
52538     int iIdx;                          /* Index of child node in parent */
52539     MemPage *pPage;                    /* Current page of the b-tree */
52540
52541     /* If this is a leaf page or the tree is not an int-key tree, then 
52542     ** this page contains countable entries. Increment the entry counter
52543     ** accordingly.
52544     */
52545     pPage = pCur->apPage[pCur->iPage];
52546     if( pPage->leaf || !pPage->intKey ){
52547       nEntry += pPage->nCell;
52548     }
52549
52550     /* pPage is a leaf node. This loop navigates the cursor so that it 
52551     ** points to the first interior cell that it points to the parent of
52552     ** the next page in the tree that has not yet been visited. The
52553     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
52554     ** of the page, or to the number of cells in the page if the next page
52555     ** to visit is the right-child of its parent.
52556     **
52557     ** If all pages in the tree have been visited, return SQLITE_OK to the
52558     ** caller.
52559     */
52560     if( pPage->leaf ){
52561       do {
52562         if( pCur->iPage==0 ){
52563           /* All pages of the b-tree have been visited. Return successfully. */
52564           *pnEntry = nEntry;
52565           return SQLITE_OK;
52566         }
52567         moveToParent(pCur);
52568       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
52569
52570       pCur->aiIdx[pCur->iPage]++;
52571       pPage = pCur->apPage[pCur->iPage];
52572     }
52573
52574     /* Descend to the child node of the cell that the cursor currently 
52575     ** points at. This is the right-child if (iIdx==pPage->nCell).
52576     */
52577     iIdx = pCur->aiIdx[pCur->iPage];
52578     if( iIdx==pPage->nCell ){
52579       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
52580     }else{
52581       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
52582     }
52583   }
52584
52585   /* An error has occurred. Return an error code. */
52586   return rc;
52587 }
52588 #endif
52589
52590 /*
52591 ** Return the pager associated with a BTree.  This routine is used for
52592 ** testing and debugging only.
52593 */
52594 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
52595   return p->pBt->pPager;
52596 }
52597
52598 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52599 /*
52600 ** Append a message to the error message string.
52601 */
52602 static void checkAppendMsg(
52603   IntegrityCk *pCheck,
52604   char *zMsg1,
52605   const char *zFormat,
52606   ...
52607 ){
52608   va_list ap;
52609   if( !pCheck->mxErr ) return;
52610   pCheck->mxErr--;
52611   pCheck->nErr++;
52612   va_start(ap, zFormat);
52613   if( pCheck->errMsg.nChar ){
52614     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
52615   }
52616   if( zMsg1 ){
52617     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
52618   }
52619   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
52620   va_end(ap);
52621   if( pCheck->errMsg.mallocFailed ){
52622     pCheck->mallocFailed = 1;
52623   }
52624 }
52625 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52626
52627 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52628 /*
52629 ** Add 1 to the reference count for page iPage.  If this is the second
52630 ** reference to the page, add an error message to pCheck->zErrMsg.
52631 ** Return 1 if there are 2 ore more references to the page and 0 if
52632 ** if this is the first reference to the page.
52633 **
52634 ** Also check that the page number is in bounds.
52635 */
52636 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
52637   if( iPage==0 ) return 1;
52638   if( iPage>pCheck->nPage ){
52639     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
52640     return 1;
52641   }
52642   if( pCheck->anRef[iPage]==1 ){
52643     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
52644     return 1;
52645   }
52646   return  (pCheck->anRef[iPage]++)>1;
52647 }
52648
52649 #ifndef SQLITE_OMIT_AUTOVACUUM
52650 /*
52651 ** Check that the entry in the pointer-map for page iChild maps to 
52652 ** page iParent, pointer type ptrType. If not, append an error message
52653 ** to pCheck.
52654 */
52655 static void checkPtrmap(
52656   IntegrityCk *pCheck,   /* Integrity check context */
52657   Pgno iChild,           /* Child page number */
52658   u8 eType,              /* Expected pointer map type */
52659   Pgno iParent,          /* Expected pointer map parent page number */
52660   char *zContext         /* Context description (used for error msg) */
52661 ){
52662   int rc;
52663   u8 ePtrmapType;
52664   Pgno iPtrmapParent;
52665
52666   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
52667   if( rc!=SQLITE_OK ){
52668     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
52669     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
52670     return;
52671   }
52672
52673   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
52674     checkAppendMsg(pCheck, zContext, 
52675       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
52676       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
52677   }
52678 }
52679 #endif
52680
52681 /*
52682 ** Check the integrity of the freelist or of an overflow page list.
52683 ** Verify that the number of pages on the list is N.
52684 */
52685 static void checkList(
52686   IntegrityCk *pCheck,  /* Integrity checking context */
52687   int isFreeList,       /* True for a freelist.  False for overflow page list */
52688   int iPage,            /* Page number for first page in the list */
52689   int N,                /* Expected number of pages in the list */
52690   char *zContext        /* Context for error messages */
52691 ){
52692   int i;
52693   int expected = N;
52694   int iFirst = iPage;
52695   while( N-- > 0 && pCheck->mxErr ){
52696     DbPage *pOvflPage;
52697     unsigned char *pOvflData;
52698     if( iPage<1 ){
52699       checkAppendMsg(pCheck, zContext,
52700          "%d of %d pages missing from overflow list starting at %d",
52701           N+1, expected, iFirst);
52702       break;
52703     }
52704     if( checkRef(pCheck, iPage, zContext) ) break;
52705     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
52706       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
52707       break;
52708     }
52709     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
52710     if( isFreeList ){
52711       int n = get4byte(&pOvflData[4]);
52712 #ifndef SQLITE_OMIT_AUTOVACUUM
52713       if( pCheck->pBt->autoVacuum ){
52714         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
52715       }
52716 #endif
52717       if( n>(int)pCheck->pBt->usableSize/4-2 ){
52718         checkAppendMsg(pCheck, zContext,
52719            "freelist leaf count too big on page %d", iPage);
52720         N--;
52721       }else{
52722         for(i=0; i<n; i++){
52723           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
52724 #ifndef SQLITE_OMIT_AUTOVACUUM
52725           if( pCheck->pBt->autoVacuum ){
52726             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
52727           }
52728 #endif
52729           checkRef(pCheck, iFreePage, zContext);
52730         }
52731         N -= n;
52732       }
52733     }
52734 #ifndef SQLITE_OMIT_AUTOVACUUM
52735     else{
52736       /* If this database supports auto-vacuum and iPage is not the last
52737       ** page in this overflow list, check that the pointer-map entry for
52738       ** the following page matches iPage.
52739       */
52740       if( pCheck->pBt->autoVacuum && N>0 ){
52741         i = get4byte(pOvflData);
52742         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
52743       }
52744     }
52745 #endif
52746     iPage = get4byte(pOvflData);
52747     sqlite3PagerUnref(pOvflPage);
52748   }
52749 }
52750 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52751
52752 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52753 /*
52754 ** Do various sanity checks on a single page of a tree.  Return
52755 ** the tree depth.  Root pages return 0.  Parents of root pages
52756 ** return 1, and so forth.
52757 ** 
52758 ** These checks are done:
52759 **
52760 **      1.  Make sure that cells and freeblocks do not overlap
52761 **          but combine to completely cover the page.
52762 **  NO  2.  Make sure cell keys are in order.
52763 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
52764 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
52765 **      5.  Check the integrity of overflow pages.
52766 **      6.  Recursively call checkTreePage on all children.
52767 **      7.  Verify that the depth of all children is the same.
52768 **      8.  Make sure this page is at least 33% full or else it is
52769 **          the root of the tree.
52770 */
52771 static int checkTreePage(
52772   IntegrityCk *pCheck,  /* Context for the sanity check */
52773   int iPage,            /* Page number of the page to check */
52774   char *zParentContext, /* Parent context */
52775   i64 *pnParentMinKey, 
52776   i64 *pnParentMaxKey
52777 ){
52778   MemPage *pPage;
52779   int i, rc, depth, d2, pgno, cnt;
52780   int hdr, cellStart;
52781   int nCell;
52782   u8 *data;
52783   BtShared *pBt;
52784   int usableSize;
52785   char zContext[100];
52786   char *hit = 0;
52787   i64 nMinKey = 0;
52788   i64 nMaxKey = 0;
52789
52790   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
52791
52792   /* Check that the page exists
52793   */
52794   pBt = pCheck->pBt;
52795   usableSize = pBt->usableSize;
52796   if( iPage==0 ) return 0;
52797   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
52798   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
52799     checkAppendMsg(pCheck, zContext,
52800        "unable to get the page. error code=%d", rc);
52801     return 0;
52802   }
52803
52804   /* Clear MemPage.isInit to make sure the corruption detection code in
52805   ** btreeInitPage() is executed.  */
52806   pPage->isInit = 0;
52807   if( (rc = btreeInitPage(pPage))!=0 ){
52808     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
52809     checkAppendMsg(pCheck, zContext, 
52810                    "btreeInitPage() returns error code %d", rc);
52811     releasePage(pPage);
52812     return 0;
52813   }
52814
52815   /* Check out all the cells.
52816   */
52817   depth = 0;
52818   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
52819     u8 *pCell;
52820     u32 sz;
52821     CellInfo info;
52822
52823     /* Check payload overflow pages
52824     */
52825     sqlite3_snprintf(sizeof(zContext), zContext,
52826              "On tree page %d cell %d: ", iPage, i);
52827     pCell = findCell(pPage,i);
52828     btreeParseCellPtr(pPage, pCell, &info);
52829     sz = info.nData;
52830     if( !pPage->intKey ) sz += (int)info.nKey;
52831     /* For intKey pages, check that the keys are in order.
52832     */
52833     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
52834     else{
52835       if( info.nKey <= nMaxKey ){
52836         checkAppendMsg(pCheck, zContext, 
52837             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
52838       }
52839       nMaxKey = info.nKey;
52840     }
52841     assert( sz==info.nPayload );
52842     if( (sz>info.nLocal) 
52843      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
52844     ){
52845       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
52846       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
52847 #ifndef SQLITE_OMIT_AUTOVACUUM
52848       if( pBt->autoVacuum ){
52849         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
52850       }
52851 #endif
52852       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
52853     }
52854
52855     /* Check sanity of left child page.
52856     */
52857     if( !pPage->leaf ){
52858       pgno = get4byte(pCell);
52859 #ifndef SQLITE_OMIT_AUTOVACUUM
52860       if( pBt->autoVacuum ){
52861         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
52862       }
52863 #endif
52864       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
52865       if( i>0 && d2!=depth ){
52866         checkAppendMsg(pCheck, zContext, "Child page depth differs");
52867       }
52868       depth = d2;
52869     }
52870   }
52871
52872   if( !pPage->leaf ){
52873     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52874     sqlite3_snprintf(sizeof(zContext), zContext, 
52875                      "On page %d at right child: ", iPage);
52876 #ifndef SQLITE_OMIT_AUTOVACUUM
52877     if( pBt->autoVacuum ){
52878       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
52879     }
52880 #endif
52881     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
52882   }
52883  
52884   /* For intKey leaf pages, check that the min/max keys are in order
52885   ** with any left/parent/right pages.
52886   */
52887   if( pPage->leaf && pPage->intKey ){
52888     /* if we are a left child page */
52889     if( pnParentMinKey ){
52890       /* if we are the left most child page */
52891       if( !pnParentMaxKey ){
52892         if( nMaxKey > *pnParentMinKey ){
52893           checkAppendMsg(pCheck, zContext, 
52894               "Rowid %lld out of order (max larger than parent min of %lld)",
52895               nMaxKey, *pnParentMinKey);
52896         }
52897       }else{
52898         if( nMinKey <= *pnParentMinKey ){
52899           checkAppendMsg(pCheck, zContext, 
52900               "Rowid %lld out of order (min less than parent min of %lld)",
52901               nMinKey, *pnParentMinKey);
52902         }
52903         if( nMaxKey > *pnParentMaxKey ){
52904           checkAppendMsg(pCheck, zContext, 
52905               "Rowid %lld out of order (max larger than parent max of %lld)",
52906               nMaxKey, *pnParentMaxKey);
52907         }
52908         *pnParentMinKey = nMaxKey;
52909       }
52910     /* else if we're a right child page */
52911     } else if( pnParentMaxKey ){
52912       if( nMinKey <= *pnParentMaxKey ){
52913         checkAppendMsg(pCheck, zContext, 
52914             "Rowid %lld out of order (min less than parent max of %lld)",
52915             nMinKey, *pnParentMaxKey);
52916       }
52917     }
52918   }
52919
52920   /* Check for complete coverage of the page
52921   */
52922   data = pPage->aData;
52923   hdr = pPage->hdrOffset;
52924   hit = sqlite3PageMalloc( pBt->pageSize );
52925   if( hit==0 ){
52926     pCheck->mallocFailed = 1;
52927   }else{
52928     int contentOffset = get2byteNotZero(&data[hdr+5]);
52929     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
52930     memset(hit+contentOffset, 0, usableSize-contentOffset);
52931     memset(hit, 1, contentOffset);
52932     nCell = get2byte(&data[hdr+3]);
52933     cellStart = hdr + 12 - 4*pPage->leaf;
52934     for(i=0; i<nCell; i++){
52935       int pc = get2byte(&data[cellStart+i*2]);
52936       u32 size = 65536;
52937       int j;
52938       if( pc<=usableSize-4 ){
52939         size = cellSizePtr(pPage, &data[pc]);
52940       }
52941       if( (int)(pc+size-1)>=usableSize ){
52942         checkAppendMsg(pCheck, 0, 
52943             "Corruption detected in cell %d on page %d",i,iPage);
52944       }else{
52945         for(j=pc+size-1; j>=pc; j--) hit[j]++;
52946       }
52947     }
52948     i = get2byte(&data[hdr+1]);
52949     while( i>0 ){
52950       int size, j;
52951       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
52952       size = get2byte(&data[i+2]);
52953       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
52954       for(j=i+size-1; j>=i; j--) hit[j]++;
52955       j = get2byte(&data[i]);
52956       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
52957       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
52958       i = j;
52959     }
52960     for(i=cnt=0; i<usableSize; i++){
52961       if( hit[i]==0 ){
52962         cnt++;
52963       }else if( hit[i]>1 ){
52964         checkAppendMsg(pCheck, 0,
52965           "Multiple uses for byte %d of page %d", i, iPage);
52966         break;
52967       }
52968     }
52969     if( cnt!=data[hdr+7] ){
52970       checkAppendMsg(pCheck, 0, 
52971           "Fragmentation of %d bytes reported as %d on page %d",
52972           cnt, data[hdr+7], iPage);
52973     }
52974   }
52975   sqlite3PageFree(hit);
52976   releasePage(pPage);
52977   return depth+1;
52978 }
52979 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
52980
52981 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
52982 /*
52983 ** This routine does a complete check of the given BTree file.  aRoot[] is
52984 ** an array of pages numbers were each page number is the root page of
52985 ** a table.  nRoot is the number of entries in aRoot.
52986 **
52987 ** A read-only or read-write transaction must be opened before calling
52988 ** this function.
52989 **
52990 ** Write the number of error seen in *pnErr.  Except for some memory
52991 ** allocation errors,  an error message held in memory obtained from
52992 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
52993 ** returned.  If a memory allocation error occurs, NULL is returned.
52994 */
52995 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
52996   Btree *p,     /* The btree to be checked */
52997   int *aRoot,   /* An array of root pages numbers for individual trees */
52998   int nRoot,    /* Number of entries in aRoot[] */
52999   int mxErr,    /* Stop reporting errors after this many */
53000   int *pnErr    /* Write number of errors seen to this variable */
53001 ){
53002   Pgno i;
53003   int nRef;
53004   IntegrityCk sCheck;
53005   BtShared *pBt = p->pBt;
53006   char zErr[100];
53007
53008   sqlite3BtreeEnter(p);
53009   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
53010   nRef = sqlite3PagerRefcount(pBt->pPager);
53011   sCheck.pBt = pBt;
53012   sCheck.pPager = pBt->pPager;
53013   sCheck.nPage = btreePagecount(sCheck.pBt);
53014   sCheck.mxErr = mxErr;
53015   sCheck.nErr = 0;
53016   sCheck.mallocFailed = 0;
53017   *pnErr = 0;
53018   if( sCheck.nPage==0 ){
53019     sqlite3BtreeLeave(p);
53020     return 0;
53021   }
53022   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
53023   if( !sCheck.anRef ){
53024     *pnErr = 1;
53025     sqlite3BtreeLeave(p);
53026     return 0;
53027   }
53028   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
53029   i = PENDING_BYTE_PAGE(pBt);
53030   if( i<=sCheck.nPage ){
53031     sCheck.anRef[i] = 1;
53032   }
53033   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
53034   sCheck.errMsg.useMalloc = 2;
53035
53036   /* Check the integrity of the freelist
53037   */
53038   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
53039             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
53040
53041   /* Check all the tables.
53042   */
53043   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
53044     if( aRoot[i]==0 ) continue;
53045 #ifndef SQLITE_OMIT_AUTOVACUUM
53046     if( pBt->autoVacuum && aRoot[i]>1 ){
53047       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
53048     }
53049 #endif
53050     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
53051   }
53052
53053   /* Make sure every page in the file is referenced
53054   */
53055   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
53056 #ifdef SQLITE_OMIT_AUTOVACUUM
53057     if( sCheck.anRef[i]==0 ){
53058       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
53059     }
53060 #else
53061     /* If the database supports auto-vacuum, make sure no tables contain
53062     ** references to pointer-map pages.
53063     */
53064     if( sCheck.anRef[i]==0 && 
53065        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
53066       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
53067     }
53068     if( sCheck.anRef[i]!=0 && 
53069        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
53070       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
53071     }
53072 #endif
53073   }
53074
53075   /* Make sure this analysis did not leave any unref() pages.
53076   ** This is an internal consistency check; an integrity check
53077   ** of the integrity check.
53078   */
53079   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
53080     checkAppendMsg(&sCheck, 0, 
53081       "Outstanding page count goes from %d to %d during this analysis",
53082       nRef, sqlite3PagerRefcount(pBt->pPager)
53083     );
53084   }
53085
53086   /* Clean  up and report errors.
53087   */
53088   sqlite3BtreeLeave(p);
53089   sqlite3_free(sCheck.anRef);
53090   if( sCheck.mallocFailed ){
53091     sqlite3StrAccumReset(&sCheck.errMsg);
53092     *pnErr = sCheck.nErr+1;
53093     return 0;
53094   }
53095   *pnErr = sCheck.nErr;
53096   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
53097   return sqlite3StrAccumFinish(&sCheck.errMsg);
53098 }
53099 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
53100
53101 /*
53102 ** Return the full pathname of the underlying database file.
53103 **
53104 ** The pager filename is invariant as long as the pager is
53105 ** open so it is safe to access without the BtShared mutex.
53106 */
53107 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
53108   assert( p->pBt->pPager!=0 );
53109   return sqlite3PagerFilename(p->pBt->pPager);
53110 }
53111
53112 /*
53113 ** Return the pathname of the journal file for this database. The return
53114 ** value of this routine is the same regardless of whether the journal file
53115 ** has been created or not.
53116 **
53117 ** The pager journal filename is invariant as long as the pager is
53118 ** open so it is safe to access without the BtShared mutex.
53119 */
53120 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
53121   assert( p->pBt->pPager!=0 );
53122   return sqlite3PagerJournalname(p->pBt->pPager);
53123 }
53124
53125 /*
53126 ** Return non-zero if a transaction is active.
53127 */
53128 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
53129   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
53130   return (p && (p->inTrans==TRANS_WRITE));
53131 }
53132
53133 #ifndef SQLITE_OMIT_WAL
53134 /*
53135 ** Run a checkpoint on the Btree passed as the first argument.
53136 **
53137 ** Return SQLITE_LOCKED if this or any other connection has an open 
53138 ** transaction on the shared-cache the argument Btree is connected to.
53139 */
53140 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p){
53141   int rc = SQLITE_OK;
53142   if( p ){
53143     BtShared *pBt = p->pBt;
53144     sqlite3BtreeEnter(p);
53145     if( pBt->inTransaction!=TRANS_NONE ){
53146       rc = SQLITE_LOCKED;
53147     }else{
53148       rc = sqlite3PagerCheckpoint(pBt->pPager);
53149     }
53150     sqlite3BtreeLeave(p);
53151   }
53152   return rc;
53153 }
53154 #endif
53155
53156 /*
53157 ** Return non-zero if a read (or write) transaction is active.
53158 */
53159 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
53160   assert( p );
53161   assert( sqlite3_mutex_held(p->db->mutex) );
53162   return p->inTrans!=TRANS_NONE;
53163 }
53164
53165 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
53166   assert( p );
53167   assert( sqlite3_mutex_held(p->db->mutex) );
53168   return p->nBackup!=0;
53169 }
53170
53171 /*
53172 ** This function returns a pointer to a blob of memory associated with
53173 ** a single shared-btree. The memory is used by client code for its own
53174 ** purposes (for example, to store a high-level schema associated with 
53175 ** the shared-btree). The btree layer manages reference counting issues.
53176 **
53177 ** The first time this is called on a shared-btree, nBytes bytes of memory
53178 ** are allocated, zeroed, and returned to the caller. For each subsequent 
53179 ** call the nBytes parameter is ignored and a pointer to the same blob
53180 ** of memory returned. 
53181 **
53182 ** If the nBytes parameter is 0 and the blob of memory has not yet been
53183 ** allocated, a null pointer is returned. If the blob has already been
53184 ** allocated, it is returned as normal.
53185 **
53186 ** Just before the shared-btree is closed, the function passed as the 
53187 ** xFree argument when the memory allocation was made is invoked on the 
53188 ** blob of allocated memory. This function should not call sqlite3_free()
53189 ** on the memory, the btree layer does that.
53190 */
53191 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
53192   BtShared *pBt = p->pBt;
53193   sqlite3BtreeEnter(p);
53194   if( !pBt->pSchema && nBytes ){
53195     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
53196     pBt->xFreeSchema = xFree;
53197   }
53198   sqlite3BtreeLeave(p);
53199   return pBt->pSchema;
53200 }
53201
53202 /*
53203 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
53204 ** btree as the argument handle holds an exclusive lock on the 
53205 ** sqlite_master table. Otherwise SQLITE_OK.
53206 */
53207 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
53208   int rc;
53209   assert( sqlite3_mutex_held(p->db->mutex) );
53210   sqlite3BtreeEnter(p);
53211   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
53212   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
53213   sqlite3BtreeLeave(p);
53214   return rc;
53215 }
53216
53217
53218 #ifndef SQLITE_OMIT_SHARED_CACHE
53219 /*
53220 ** Obtain a lock on the table whose root page is iTab.  The
53221 ** lock is a write lock if isWritelock is true or a read lock
53222 ** if it is false.
53223 */
53224 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
53225   int rc = SQLITE_OK;
53226   assert( p->inTrans!=TRANS_NONE );
53227   if( p->sharable ){
53228     u8 lockType = READ_LOCK + isWriteLock;
53229     assert( READ_LOCK+1==WRITE_LOCK );
53230     assert( isWriteLock==0 || isWriteLock==1 );
53231
53232     sqlite3BtreeEnter(p);
53233     rc = querySharedCacheTableLock(p, iTab, lockType);
53234     if( rc==SQLITE_OK ){
53235       rc = setSharedCacheTableLock(p, iTab, lockType);
53236     }
53237     sqlite3BtreeLeave(p);
53238   }
53239   return rc;
53240 }
53241 #endif
53242
53243 #ifndef SQLITE_OMIT_INCRBLOB
53244 /*
53245 ** Argument pCsr must be a cursor opened for writing on an 
53246 ** INTKEY table currently pointing at a valid table entry. 
53247 ** This function modifies the data stored as part of that entry.
53248 **
53249 ** Only the data content may only be modified, it is not possible to 
53250 ** change the length of the data stored. If this function is called with
53251 ** parameters that attempt to write past the end of the existing data,
53252 ** no modifications are made and SQLITE_CORRUPT is returned.
53253 */
53254 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
53255   int rc;
53256   assert( cursorHoldsMutex(pCsr) );
53257   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
53258   assert( pCsr->isIncrblobHandle );
53259
53260   rc = restoreCursorPosition(pCsr);
53261   if( rc!=SQLITE_OK ){
53262     return rc;
53263   }
53264   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
53265   if( pCsr->eState!=CURSOR_VALID ){
53266     return SQLITE_ABORT;
53267   }
53268
53269   /* Check some assumptions: 
53270   **   (a) the cursor is open for writing,
53271   **   (b) there is a read/write transaction open,
53272   **   (c) the connection holds a write-lock on the table (if required),
53273   **   (d) there are no conflicting read-locks, and
53274   **   (e) the cursor points at a valid row of an intKey table.
53275   */
53276   if( !pCsr->wrFlag ){
53277     return SQLITE_READONLY;
53278   }
53279   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
53280   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
53281   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
53282   assert( pCsr->apPage[pCsr->iPage]->intKey );
53283
53284   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
53285 }
53286
53287 /* 
53288 ** Set a flag on this cursor to cache the locations of pages from the 
53289 ** overflow list for the current row. This is used by cursors opened
53290 ** for incremental blob IO only.
53291 **
53292 ** This function sets a flag only. The actual page location cache
53293 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
53294 ** accessPayload() (the worker function for sqlite3BtreeData() and
53295 ** sqlite3BtreePutData()).
53296 */
53297 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
53298   assert( cursorHoldsMutex(pCur) );
53299   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53300   invalidateOverflowCache(pCur);
53301   pCur->isIncrblobHandle = 1;
53302 }
53303 #endif
53304
53305 /*
53306 ** Set both the "read version" (single byte at byte offset 18) and 
53307 ** "write version" (single byte at byte offset 19) fields in the database
53308 ** header to iVersion.
53309 */
53310 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
53311   BtShared *pBt = pBtree->pBt;
53312   int rc;                         /* Return code */
53313  
53314   assert( pBtree->inTrans==TRANS_NONE );
53315   assert( iVersion==1 || iVersion==2 );
53316
53317   /* If setting the version fields to 1, do not automatically open the
53318   ** WAL connection, even if the version fields are currently set to 2.
53319   */
53320   pBt->doNotUseWAL = (u8)(iVersion==1);
53321
53322   rc = sqlite3BtreeBeginTrans(pBtree, 0);
53323   if( rc==SQLITE_OK ){
53324     u8 *aData = pBt->pPage1->aData;
53325     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
53326       rc = sqlite3BtreeBeginTrans(pBtree, 2);
53327       if( rc==SQLITE_OK ){
53328         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53329         if( rc==SQLITE_OK ){
53330           aData[18] = (u8)iVersion;
53331           aData[19] = (u8)iVersion;
53332         }
53333       }
53334     }
53335   }
53336
53337   pBt->doNotUseWAL = 0;
53338   return rc;
53339 }
53340
53341 /************** End of btree.c ***********************************************/
53342 /************** Begin file backup.c ******************************************/
53343 /*
53344 ** 2009 January 28
53345 **
53346 ** The author disclaims copyright to this source code.  In place of
53347 ** a legal notice, here is a blessing:
53348 **
53349 **    May you do good and not evil.
53350 **    May you find forgiveness for yourself and forgive others.
53351 **    May you share freely, never taking more than you give.
53352 **
53353 *************************************************************************
53354 ** This file contains the implementation of the sqlite3_backup_XXX() 
53355 ** API functions and the related features.
53356 */
53357
53358 /* Macro to find the minimum of two numeric values.
53359 */
53360 #ifndef MIN
53361 # define MIN(x,y) ((x)<(y)?(x):(y))
53362 #endif
53363
53364 /*
53365 ** Structure allocated for each backup operation.
53366 */
53367 struct sqlite3_backup {
53368   sqlite3* pDestDb;        /* Destination database handle */
53369   Btree *pDest;            /* Destination b-tree file */
53370   u32 iDestSchema;         /* Original schema cookie in destination */
53371   int bDestLocked;         /* True once a write-transaction is open on pDest */
53372
53373   Pgno iNext;              /* Page number of the next source page to copy */
53374   sqlite3* pSrcDb;         /* Source database handle */
53375   Btree *pSrc;             /* Source b-tree file */
53376
53377   int rc;                  /* Backup process error code */
53378
53379   /* These two variables are set by every call to backup_step(). They are
53380   ** read by calls to backup_remaining() and backup_pagecount().
53381   */
53382   Pgno nRemaining;         /* Number of pages left to copy */
53383   Pgno nPagecount;         /* Total number of pages to copy */
53384
53385   int isAttached;          /* True once backup has been registered with pager */
53386   sqlite3_backup *pNext;   /* Next backup associated with source pager */
53387 };
53388
53389 /*
53390 ** THREAD SAFETY NOTES:
53391 **
53392 **   Once it has been created using backup_init(), a single sqlite3_backup
53393 **   structure may be accessed via two groups of thread-safe entry points:
53394 **
53395 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
53396 **       backup_finish(). Both these functions obtain the source database
53397 **       handle mutex and the mutex associated with the source BtShared 
53398 **       structure, in that order.
53399 **
53400 **     * Via the BackupUpdate() and BackupRestart() functions, which are
53401 **       invoked by the pager layer to report various state changes in
53402 **       the page cache associated with the source database. The mutex
53403 **       associated with the source database BtShared structure will always 
53404 **       be held when either of these functions are invoked.
53405 **
53406 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
53407 **   backup_pagecount() are not thread-safe functions. If they are called
53408 **   while some other thread is calling backup_step() or backup_finish(),
53409 **   the values returned may be invalid. There is no way for a call to
53410 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
53411 **   or backup_pagecount().
53412 **
53413 **   Depending on the SQLite configuration, the database handles and/or
53414 **   the Btree objects may have their own mutexes that require locking.
53415 **   Non-sharable Btrees (in-memory databases for example), do not have
53416 **   associated mutexes.
53417 */
53418
53419 /*
53420 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
53421 ** in connection handle pDb. If such a database cannot be found, return
53422 ** a NULL pointer and write an error message to pErrorDb.
53423 **
53424 ** If the "temp" database is requested, it may need to be opened by this 
53425 ** function. If an error occurs while doing so, return 0 and write an 
53426 ** error message to pErrorDb.
53427 */
53428 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
53429   int i = sqlite3FindDbName(pDb, zDb);
53430
53431   if( i==1 ){
53432     Parse *pParse;
53433     int rc = 0;
53434     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
53435     if( pParse==0 ){
53436       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
53437       rc = SQLITE_NOMEM;
53438     }else{
53439       pParse->db = pDb;
53440       if( sqlite3OpenTempDatabase(pParse) ){
53441         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
53442         rc = SQLITE_ERROR;
53443       }
53444       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
53445       sqlite3StackFree(pErrorDb, pParse);
53446     }
53447     if( rc ){
53448       return 0;
53449     }
53450   }
53451
53452   if( i<0 ){
53453     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
53454     return 0;
53455   }
53456
53457   return pDb->aDb[i].pBt;
53458 }
53459
53460 /*
53461 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
53462 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
53463 ** a pointer to the new sqlite3_backup object.
53464 **
53465 ** If an error occurs, NULL is returned and an error code and error message
53466 ** stored in database handle pDestDb.
53467 */
53468 SQLITE_API sqlite3_backup *sqlite3_backup_init(
53469   sqlite3* pDestDb,                     /* Database to write to */
53470   const char *zDestDb,                  /* Name of database within pDestDb */
53471   sqlite3* pSrcDb,                      /* Database connection to read from */
53472   const char *zSrcDb                    /* Name of database within pSrcDb */
53473 ){
53474   sqlite3_backup *p;                    /* Value to return */
53475
53476   /* Lock the source database handle. The destination database
53477   ** handle is not locked in this routine, but it is locked in
53478   ** sqlite3_backup_step(). The user is required to ensure that no
53479   ** other thread accesses the destination handle for the duration
53480   ** of the backup operation.  Any attempt to use the destination
53481   ** database connection while a backup is in progress may cause
53482   ** a malfunction or a deadlock.
53483   */
53484   sqlite3_mutex_enter(pSrcDb->mutex);
53485   sqlite3_mutex_enter(pDestDb->mutex);
53486
53487   if( pSrcDb==pDestDb ){
53488     sqlite3Error(
53489         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
53490     );
53491     p = 0;
53492   }else {
53493     /* Allocate space for a new sqlite3_backup object...
53494     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
53495     ** call to sqlite3_backup_init() and is destroyed by a call to
53496     ** sqlite3_backup_finish(). */
53497     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
53498     if( !p ){
53499       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
53500     }
53501   }
53502
53503   /* If the allocation succeeded, populate the new object. */
53504   if( p ){
53505     memset(p, 0, sizeof(sqlite3_backup));
53506     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
53507     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
53508     p->pDestDb = pDestDb;
53509     p->pSrcDb = pSrcDb;
53510     p->iNext = 1;
53511     p->isAttached = 0;
53512
53513     if( 0==p->pSrc || 0==p->pDest ){
53514       /* One (or both) of the named databases did not exist. An error has
53515       ** already been written into the pDestDb handle. All that is left
53516       ** to do here is free the sqlite3_backup structure.
53517       */
53518       sqlite3_free(p);
53519       p = 0;
53520     }
53521   }
53522   if( p ){
53523     p->pSrc->nBackup++;
53524   }
53525
53526   sqlite3_mutex_leave(pDestDb->mutex);
53527   sqlite3_mutex_leave(pSrcDb->mutex);
53528   return p;
53529 }
53530
53531 /*
53532 ** Argument rc is an SQLite error code. Return true if this error is 
53533 ** considered fatal if encountered during a backup operation. All errors
53534 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
53535 */
53536 static int isFatalError(int rc){
53537   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
53538 }
53539
53540 /*
53541 ** Parameter zSrcData points to a buffer containing the data for 
53542 ** page iSrcPg from the source database. Copy this data into the 
53543 ** destination database.
53544 */
53545 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
53546   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
53547   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
53548   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
53549   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
53550   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
53551
53552   int rc = SQLITE_OK;
53553   i64 iOff;
53554
53555   assert( p->bDestLocked );
53556   assert( !isFatalError(p->rc) );
53557   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
53558   assert( zSrcData );
53559
53560   /* Catch the case where the destination is an in-memory database and the
53561   ** page sizes of the source and destination differ. 
53562   */
53563   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
53564     rc = SQLITE_READONLY;
53565   }
53566
53567 #ifdef SQLITE_HAS_CODEC
53568   /* Backup is not possible if the page size of the destination is changing
53569   ** a a codec is in use.
53570   */
53571   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
53572     rc = SQLITE_READONLY;
53573   }
53574 #endif
53575
53576   /* This loop runs once for each destination page spanned by the source 
53577   ** page. For each iteration, variable iOff is set to the byte offset
53578   ** of the destination page.
53579   */
53580   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
53581     DbPage *pDestPg = 0;
53582     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
53583     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
53584     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
53585      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
53586     ){
53587       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
53588       u8 *zDestData = sqlite3PagerGetData(pDestPg);
53589       u8 *zOut = &zDestData[iOff%nDestPgsz];
53590
53591       /* Copy the data from the source page into the destination page.
53592       ** Then clear the Btree layer MemPage.isInit flag. Both this module
53593       ** and the pager code use this trick (clearing the first byte
53594       ** of the page 'extra' space to invalidate the Btree layers
53595       ** cached parse of the page). MemPage.isInit is marked 
53596       ** "MUST BE FIRST" for this purpose.
53597       */
53598       memcpy(zOut, zIn, nCopy);
53599       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
53600     }
53601     sqlite3PagerUnref(pDestPg);
53602   }
53603
53604   return rc;
53605 }
53606
53607 /*
53608 ** If pFile is currently larger than iSize bytes, then truncate it to
53609 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
53610 ** this function is a no-op.
53611 **
53612 ** Return SQLITE_OK if everything is successful, or an SQLite error 
53613 ** code if an error occurs.
53614 */
53615 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
53616   i64 iCurrent;
53617   int rc = sqlite3OsFileSize(pFile, &iCurrent);
53618   if( rc==SQLITE_OK && iCurrent>iSize ){
53619     rc = sqlite3OsTruncate(pFile, iSize);
53620   }
53621   return rc;
53622 }
53623
53624 /*
53625 ** Register this backup object with the associated source pager for
53626 ** callbacks when pages are changed or the cache invalidated.
53627 */
53628 static void attachBackupObject(sqlite3_backup *p){
53629   sqlite3_backup **pp;
53630   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
53631   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
53632   p->pNext = *pp;
53633   *pp = p;
53634   p->isAttached = 1;
53635 }
53636
53637 /*
53638 ** Copy nPage pages from the source b-tree to the destination.
53639 */
53640 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
53641   int rc;
53642   int destMode;       /* Destination journal mode */
53643   int pgszSrc = 0;    /* Source page size */
53644   int pgszDest = 0;   /* Destination page size */
53645
53646   sqlite3_mutex_enter(p->pSrcDb->mutex);
53647   sqlite3BtreeEnter(p->pSrc);
53648   if( p->pDestDb ){
53649     sqlite3_mutex_enter(p->pDestDb->mutex);
53650   }
53651
53652   rc = p->rc;
53653   if( !isFatalError(rc) ){
53654     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
53655     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
53656     int ii;                            /* Iterator variable */
53657     int nSrcPage = -1;                 /* Size of source db in pages */
53658     int bCloseTrans = 0;               /* True if src db requires unlocking */
53659
53660     /* If the source pager is currently in a write-transaction, return
53661     ** SQLITE_BUSY immediately.
53662     */
53663     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
53664       rc = SQLITE_BUSY;
53665     }else{
53666       rc = SQLITE_OK;
53667     }
53668
53669     /* Lock the destination database, if it is not locked already. */
53670     if( SQLITE_OK==rc && p->bDestLocked==0
53671      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
53672     ){
53673       p->bDestLocked = 1;
53674       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
53675     }
53676
53677     /* If there is no open read-transaction on the source database, open
53678     ** one now. If a transaction is opened here, then it will be closed
53679     ** before this function exits.
53680     */
53681     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
53682       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
53683       bCloseTrans = 1;
53684     }
53685
53686     /* Do not allow backup if the destination database is in WAL mode
53687     ** and the page sizes are different between source and destination */
53688     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
53689     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
53690     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
53691     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
53692       rc = SQLITE_READONLY;
53693     }
53694   
53695     /* Now that there is a read-lock on the source database, query the
53696     ** source pager for the number of pages in the database.
53697     */
53698     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
53699     assert( nSrcPage>=0 );
53700     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
53701       const Pgno iSrcPg = p->iNext;                 /* Source page number */
53702       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
53703         DbPage *pSrcPg;                             /* Source page object */
53704         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
53705         if( rc==SQLITE_OK ){
53706           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
53707           sqlite3PagerUnref(pSrcPg);
53708         }
53709       }
53710       p->iNext++;
53711     }
53712     if( rc==SQLITE_OK ){
53713       p->nPagecount = nSrcPage;
53714       p->nRemaining = nSrcPage+1-p->iNext;
53715       if( p->iNext>(Pgno)nSrcPage ){
53716         rc = SQLITE_DONE;
53717       }else if( !p->isAttached ){
53718         attachBackupObject(p);
53719       }
53720     }
53721   
53722     /* Update the schema version field in the destination database. This
53723     ** is to make sure that the schema-version really does change in
53724     ** the case where the source and destination databases have the
53725     ** same schema version.
53726     */
53727     if( rc==SQLITE_DONE 
53728      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
53729     ){
53730       int nDestTruncate;
53731   
53732       if( p->pDestDb ){
53733         sqlite3ResetInternalSchema(p->pDestDb, 0);
53734       }
53735
53736       /* Set nDestTruncate to the final number of pages in the destination
53737       ** database. The complication here is that the destination page
53738       ** size may be different to the source page size. 
53739       **
53740       ** If the source page size is smaller than the destination page size, 
53741       ** round up. In this case the call to sqlite3OsTruncate() below will
53742       ** fix the size of the file. However it is important to call
53743       ** sqlite3PagerTruncateImage() here so that any pages in the 
53744       ** destination file that lie beyond the nDestTruncate page mark are
53745       ** journalled by PagerCommitPhaseOne() before they are destroyed
53746       ** by the file truncation.
53747       */
53748       assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
53749       assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
53750       if( pgszSrc<pgszDest ){
53751         int ratio = pgszDest/pgszSrc;
53752         nDestTruncate = (nSrcPage+ratio-1)/ratio;
53753         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
53754           nDestTruncate--;
53755         }
53756       }else{
53757         nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
53758       }
53759       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
53760
53761       if( pgszSrc<pgszDest ){
53762         /* If the source page-size is smaller than the destination page-size,
53763         ** two extra things may need to happen:
53764         **
53765         **   * The destination may need to be truncated, and
53766         **
53767         **   * Data stored on the pages immediately following the 
53768         **     pending-byte page in the source database may need to be
53769         **     copied into the destination database.
53770         */
53771         const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
53772         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
53773
53774         assert( pFile );
53775         assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
53776               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
53777            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
53778         ));
53779         if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
53780          && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
53781          && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
53782         ){
53783           i64 iOff;
53784           i64 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
53785           for(
53786             iOff=PENDING_BYTE+pgszSrc; 
53787             rc==SQLITE_OK && iOff<iEnd; 
53788             iOff+=pgszSrc
53789           ){
53790             PgHdr *pSrcPg = 0;
53791             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
53792             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
53793             if( rc==SQLITE_OK ){
53794               u8 *zData = sqlite3PagerGetData(pSrcPg);
53795               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
53796             }
53797             sqlite3PagerUnref(pSrcPg);
53798           }
53799         }
53800       }else{
53801         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
53802       }
53803   
53804       /* Finish committing the transaction to the destination database. */
53805       if( SQLITE_OK==rc
53806        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
53807       ){
53808         rc = SQLITE_DONE;
53809       }
53810     }
53811   
53812     /* If bCloseTrans is true, then this function opened a read transaction
53813     ** on the source database. Close the read transaction here. There is
53814     ** no need to check the return values of the btree methods here, as
53815     ** "committing" a read-only transaction cannot fail.
53816     */
53817     if( bCloseTrans ){
53818       TESTONLY( int rc2 );
53819       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
53820       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
53821       assert( rc2==SQLITE_OK );
53822     }
53823   
53824     if( rc==SQLITE_IOERR_NOMEM ){
53825       rc = SQLITE_NOMEM;
53826     }
53827     p->rc = rc;
53828   }
53829   if( p->pDestDb ){
53830     sqlite3_mutex_leave(p->pDestDb->mutex);
53831   }
53832   sqlite3BtreeLeave(p->pSrc);
53833   sqlite3_mutex_leave(p->pSrcDb->mutex);
53834   return rc;
53835 }
53836
53837 /*
53838 ** Release all resources associated with an sqlite3_backup* handle.
53839 */
53840 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
53841   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
53842   sqlite3_mutex *mutex;                /* Mutex to protect source database */
53843   int rc;                              /* Value to return */
53844
53845   /* Enter the mutexes */
53846   if( p==0 ) return SQLITE_OK;
53847   sqlite3_mutex_enter(p->pSrcDb->mutex);
53848   sqlite3BtreeEnter(p->pSrc);
53849   mutex = p->pSrcDb->mutex;
53850   if( p->pDestDb ){
53851     sqlite3_mutex_enter(p->pDestDb->mutex);
53852   }
53853
53854   /* Detach this backup from the source pager. */
53855   if( p->pDestDb ){
53856     p->pSrc->nBackup--;
53857   }
53858   if( p->isAttached ){
53859     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
53860     while( *pp!=p ){
53861       pp = &(*pp)->pNext;
53862     }
53863     *pp = p->pNext;
53864   }
53865
53866   /* If a transaction is still open on the Btree, roll it back. */
53867   sqlite3BtreeRollback(p->pDest);
53868
53869   /* Set the error code of the destination database handle. */
53870   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
53871   sqlite3Error(p->pDestDb, rc, 0);
53872
53873   /* Exit the mutexes and free the backup context structure. */
53874   if( p->pDestDb ){
53875     sqlite3_mutex_leave(p->pDestDb->mutex);
53876   }
53877   sqlite3BtreeLeave(p->pSrc);
53878   if( p->pDestDb ){
53879     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
53880     ** call to sqlite3_backup_init() and is destroyed by a call to
53881     ** sqlite3_backup_finish(). */
53882     sqlite3_free(p);
53883   }
53884   sqlite3_mutex_leave(mutex);
53885   return rc;
53886 }
53887
53888 /*
53889 ** Return the number of pages still to be backed up as of the most recent
53890 ** call to sqlite3_backup_step().
53891 */
53892 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
53893   return p->nRemaining;
53894 }
53895
53896 /*
53897 ** Return the total number of pages in the source database as of the most 
53898 ** recent call to sqlite3_backup_step().
53899 */
53900 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
53901   return p->nPagecount;
53902 }
53903
53904 /*
53905 ** This function is called after the contents of page iPage of the
53906 ** source database have been modified. If page iPage has already been 
53907 ** copied into the destination database, then the data written to the
53908 ** destination is now invalidated. The destination copy of iPage needs
53909 ** to be updated with the new data before the backup operation is
53910 ** complete.
53911 **
53912 ** It is assumed that the mutex associated with the BtShared object
53913 ** corresponding to the source database is held when this function is
53914 ** called.
53915 */
53916 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
53917   sqlite3_backup *p;                   /* Iterator variable */
53918   for(p=pBackup; p; p=p->pNext){
53919     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
53920     if( !isFatalError(p->rc) && iPage<p->iNext ){
53921       /* The backup process p has already copied page iPage. But now it
53922       ** has been modified by a transaction on the source pager. Copy
53923       ** the new data into the backup.
53924       */
53925       int rc = backupOnePage(p, iPage, aData);
53926       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
53927       if( rc!=SQLITE_OK ){
53928         p->rc = rc;
53929       }
53930     }
53931   }
53932 }
53933
53934 /*
53935 ** Restart the backup process. This is called when the pager layer
53936 ** detects that the database has been modified by an external database
53937 ** connection. In this case there is no way of knowing which of the
53938 ** pages that have been copied into the destination database are still 
53939 ** valid and which are not, so the entire process needs to be restarted.
53940 **
53941 ** It is assumed that the mutex associated with the BtShared object
53942 ** corresponding to the source database is held when this function is
53943 ** called.
53944 */
53945 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
53946   sqlite3_backup *p;                   /* Iterator variable */
53947   for(p=pBackup; p; p=p->pNext){
53948     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
53949     p->iNext = 1;
53950   }
53951 }
53952
53953 #ifndef SQLITE_OMIT_VACUUM
53954 /*
53955 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
53956 ** must be active for both files.
53957 **
53958 ** The size of file pTo may be reduced by this operation. If anything 
53959 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
53960 ** transaction is committed before returning.
53961 */
53962 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
53963   int rc;
53964   sqlite3_backup b;
53965   sqlite3BtreeEnter(pTo);
53966   sqlite3BtreeEnter(pFrom);
53967
53968   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
53969   ** to 0. This is used by the implementations of sqlite3_backup_step()
53970   ** and sqlite3_backup_finish() to detect that they are being called
53971   ** from this function, not directly by the user.
53972   */
53973   memset(&b, 0, sizeof(b));
53974   b.pSrcDb = pFrom->db;
53975   b.pSrc = pFrom;
53976   b.pDest = pTo;
53977   b.iNext = 1;
53978
53979   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
53980   ** file. By passing this as the number of pages to copy to
53981   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
53982   ** within a single call (unless an error occurs). The assert() statement
53983   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
53984   ** or an error code.
53985   */
53986   sqlite3_backup_step(&b, 0x7FFFFFFF);
53987   assert( b.rc!=SQLITE_OK );
53988   rc = sqlite3_backup_finish(&b);
53989   if( rc==SQLITE_OK ){
53990     pTo->pBt->pageSizeFixed = 0;
53991   }
53992
53993   sqlite3BtreeLeave(pFrom);
53994   sqlite3BtreeLeave(pTo);
53995   return rc;
53996 }
53997 #endif /* SQLITE_OMIT_VACUUM */
53998
53999 /************** End of backup.c **********************************************/
54000 /************** Begin file vdbemem.c *****************************************/
54001 /*
54002 ** 2004 May 26
54003 **
54004 ** The author disclaims copyright to this source code.  In place of
54005 ** a legal notice, here is a blessing:
54006 **
54007 **    May you do good and not evil.
54008 **    May you find forgiveness for yourself and forgive others.
54009 **    May you share freely, never taking more than you give.
54010 **
54011 *************************************************************************
54012 **
54013 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
54014 ** stores a single value in the VDBE.  Mem is an opaque structure visible
54015 ** only within the VDBE.  Interface routines refer to a Mem using the
54016 ** name sqlite_value
54017 */
54018
54019 /*
54020 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
54021 ** P if required.
54022 */
54023 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
54024
54025 /*
54026 ** If pMem is an object with a valid string representation, this routine
54027 ** ensures the internal encoding for the string representation is
54028 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
54029 **
54030 ** If pMem is not a string object, or the encoding of the string
54031 ** representation is already stored using the requested encoding, then this
54032 ** routine is a no-op.
54033 **
54034 ** SQLITE_OK is returned if the conversion is successful (or not required).
54035 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
54036 ** between formats.
54037 */
54038 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
54039   int rc;
54040   assert( (pMem->flags&MEM_RowSet)==0 );
54041   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
54042            || desiredEnc==SQLITE_UTF16BE );
54043   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
54044     return SQLITE_OK;
54045   }
54046   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54047 #ifdef SQLITE_OMIT_UTF16
54048   return SQLITE_ERROR;
54049 #else
54050
54051   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
54052   ** then the encoding of the value may not have changed.
54053   */
54054   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
54055   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
54056   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
54057   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
54058   return rc;
54059 #endif
54060 }
54061
54062 /*
54063 ** Make sure pMem->z points to a writable allocation of at least 
54064 ** n bytes.
54065 **
54066 ** If the memory cell currently contains string or blob data
54067 ** and the third argument passed to this function is true, the 
54068 ** current content of the cell is preserved. Otherwise, it may
54069 ** be discarded.  
54070 **
54071 ** This function sets the MEM_Dyn flag and clears any xDel callback.
54072 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
54073 ** not set, Mem.n is zeroed.
54074 */
54075 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
54076   assert( 1 >=
54077     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
54078     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
54079     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
54080     ((pMem->flags&MEM_Static) ? 1 : 0)
54081   );
54082   assert( (pMem->flags&MEM_RowSet)==0 );
54083
54084   if( n<32 ) n = 32;
54085   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
54086     if( preserve && pMem->z==pMem->zMalloc ){
54087       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
54088       preserve = 0;
54089     }else{
54090       sqlite3DbFree(pMem->db, pMem->zMalloc);
54091       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
54092     }
54093   }
54094
54095   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
54096     memcpy(pMem->zMalloc, pMem->z, pMem->n);
54097   }
54098   if( pMem->flags&MEM_Dyn && pMem->xDel ){
54099     pMem->xDel((void *)(pMem->z));
54100   }
54101
54102   pMem->z = pMem->zMalloc;
54103   if( pMem->z==0 ){
54104     pMem->flags = MEM_Null;
54105   }else{
54106     pMem->flags &= ~(MEM_Ephem|MEM_Static);
54107   }
54108   pMem->xDel = 0;
54109   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
54110 }
54111
54112 /*
54113 ** Make the given Mem object MEM_Dyn.  In other words, make it so
54114 ** that any TEXT or BLOB content is stored in memory obtained from
54115 ** malloc().  In this way, we know that the memory is safe to be
54116 ** overwritten or altered.
54117 **
54118 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
54119 */
54120 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
54121   int f;
54122   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54123   assert( (pMem->flags&MEM_RowSet)==0 );
54124   expandBlob(pMem);
54125   f = pMem->flags;
54126   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
54127     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
54128       return SQLITE_NOMEM;
54129     }
54130     pMem->z[pMem->n] = 0;
54131     pMem->z[pMem->n+1] = 0;
54132     pMem->flags |= MEM_Term;
54133 #ifdef SQLITE_DEBUG
54134     pMem->pScopyFrom = 0;
54135 #endif
54136   }
54137
54138   return SQLITE_OK;
54139 }
54140
54141 /*
54142 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
54143 ** blob stored in dynamically allocated space.
54144 */
54145 #ifndef SQLITE_OMIT_INCRBLOB
54146 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
54147   if( pMem->flags & MEM_Zero ){
54148     int nByte;
54149     assert( pMem->flags&MEM_Blob );
54150     assert( (pMem->flags&MEM_RowSet)==0 );
54151     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54152
54153     /* Set nByte to the number of bytes required to store the expanded blob. */
54154     nByte = pMem->n + pMem->u.nZero;
54155     if( nByte<=0 ){
54156       nByte = 1;
54157     }
54158     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
54159       return SQLITE_NOMEM;
54160     }
54161
54162     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
54163     pMem->n += pMem->u.nZero;
54164     pMem->flags &= ~(MEM_Zero|MEM_Term);
54165   }
54166   return SQLITE_OK;
54167 }
54168 #endif
54169
54170
54171 /*
54172 ** Make sure the given Mem is \u0000 terminated.
54173 */
54174 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
54175   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54176   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
54177     return SQLITE_OK;   /* Nothing to do */
54178   }
54179   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
54180     return SQLITE_NOMEM;
54181   }
54182   pMem->z[pMem->n] = 0;
54183   pMem->z[pMem->n+1] = 0;
54184   pMem->flags |= MEM_Term;
54185   return SQLITE_OK;
54186 }
54187
54188 /*
54189 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
54190 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
54191 ** is a no-op.
54192 **
54193 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
54194 **
54195 ** A MEM_Null value will never be passed to this function. This function is
54196 ** used for converting values to text for returning to the user (i.e. via
54197 ** sqlite3_value_text()), or for ensuring that values to be used as btree
54198 ** keys are strings. In the former case a NULL pointer is returned the
54199 ** user and the later is an internal programming error.
54200 */
54201 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
54202   int rc = SQLITE_OK;
54203   int fg = pMem->flags;
54204   const int nByte = 32;
54205
54206   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54207   assert( !(fg&MEM_Zero) );
54208   assert( !(fg&(MEM_Str|MEM_Blob)) );
54209   assert( fg&(MEM_Int|MEM_Real) );
54210   assert( (pMem->flags&MEM_RowSet)==0 );
54211   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54212
54213
54214   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
54215     return SQLITE_NOMEM;
54216   }
54217
54218   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
54219   ** string representation of the value. Then, if the required encoding
54220   ** is UTF-16le or UTF-16be do a translation.
54221   ** 
54222   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
54223   */
54224   if( fg & MEM_Int ){
54225     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
54226   }else{
54227     assert( fg & MEM_Real );
54228     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
54229   }
54230   pMem->n = sqlite3Strlen30(pMem->z);
54231   pMem->enc = SQLITE_UTF8;
54232   pMem->flags |= MEM_Str|MEM_Term;
54233   sqlite3VdbeChangeEncoding(pMem, enc);
54234   return rc;
54235 }
54236
54237 /*
54238 ** Memory cell pMem contains the context of an aggregate function.
54239 ** This routine calls the finalize method for that function.  The
54240 ** result of the aggregate is stored back into pMem.
54241 **
54242 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
54243 ** otherwise.
54244 */
54245 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
54246   int rc = SQLITE_OK;
54247   if( ALWAYS(pFunc && pFunc->xFinalize) ){
54248     sqlite3_context ctx;
54249     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
54250     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54251     memset(&ctx, 0, sizeof(ctx));
54252     ctx.s.flags = MEM_Null;
54253     ctx.s.db = pMem->db;
54254     ctx.pMem = pMem;
54255     ctx.pFunc = pFunc;
54256     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
54257     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
54258     sqlite3DbFree(pMem->db, pMem->zMalloc);
54259     memcpy(pMem, &ctx.s, sizeof(ctx.s));
54260     rc = ctx.isError;
54261   }
54262   return rc;
54263 }
54264
54265 /*
54266 ** If the memory cell contains a string value that must be freed by
54267 ** invoking an external callback, free it now. Calling this function
54268 ** does not free any Mem.zMalloc buffer.
54269 */
54270 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
54271   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
54272   testcase( p->flags & MEM_Agg );
54273   testcase( p->flags & MEM_Dyn );
54274   testcase( p->flags & MEM_RowSet );
54275   testcase( p->flags & MEM_Frame );
54276   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
54277     if( p->flags&MEM_Agg ){
54278       sqlite3VdbeMemFinalize(p, p->u.pDef);
54279       assert( (p->flags & MEM_Agg)==0 );
54280       sqlite3VdbeMemRelease(p);
54281     }else if( p->flags&MEM_Dyn && p->xDel ){
54282       assert( (p->flags&MEM_RowSet)==0 );
54283       p->xDel((void *)p->z);
54284       p->xDel = 0;
54285     }else if( p->flags&MEM_RowSet ){
54286       sqlite3RowSetClear(p->u.pRowSet);
54287     }else if( p->flags&MEM_Frame ){
54288       sqlite3VdbeMemSetNull(p);
54289     }
54290   }
54291 }
54292
54293 /*
54294 ** Release any memory held by the Mem. This may leave the Mem in an
54295 ** inconsistent state, for example with (Mem.z==0) and
54296 ** (Mem.type==SQLITE_TEXT).
54297 */
54298 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
54299   sqlite3VdbeMemReleaseExternal(p);
54300   sqlite3DbFree(p->db, p->zMalloc);
54301   p->z = 0;
54302   p->zMalloc = 0;
54303   p->xDel = 0;
54304 }
54305
54306 /*
54307 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
54308 ** If the double is too large, return 0x8000000000000000.
54309 **
54310 ** Most systems appear to do this simply by assigning
54311 ** variables and without the extra range tests.  But
54312 ** there are reports that windows throws an expection
54313 ** if the floating point value is out of range. (See ticket #2880.)
54314 ** Because we do not completely understand the problem, we will
54315 ** take the conservative approach and always do range tests
54316 ** before attempting the conversion.
54317 */
54318 static i64 doubleToInt64(double r){
54319 #ifdef SQLITE_OMIT_FLOATING_POINT
54320   /* When floating-point is omitted, double and int64 are the same thing */
54321   return r;
54322 #else
54323   /*
54324   ** Many compilers we encounter do not define constants for the
54325   ** minimum and maximum 64-bit integers, or they define them
54326   ** inconsistently.  And many do not understand the "LL" notation.
54327   ** So we define our own static constants here using nothing
54328   ** larger than a 32-bit integer constant.
54329   */
54330   static const i64 maxInt = LARGEST_INT64;
54331   static const i64 minInt = SMALLEST_INT64;
54332
54333   if( r<(double)minInt ){
54334     return minInt;
54335   }else if( r>(double)maxInt ){
54336     /* minInt is correct here - not maxInt.  It turns out that assigning
54337     ** a very large positive number to an integer results in a very large
54338     ** negative integer.  This makes no sense, but it is what x86 hardware
54339     ** does so for compatibility we will do the same in software. */
54340     return minInt;
54341   }else{
54342     return (i64)r;
54343   }
54344 #endif
54345 }
54346
54347 /*
54348 ** Return some kind of integer value which is the best we can do
54349 ** at representing the value that *pMem describes as an integer.
54350 ** If pMem is an integer, then the value is exact.  If pMem is
54351 ** a floating-point then the value returned is the integer part.
54352 ** If pMem is a string or blob, then we make an attempt to convert
54353 ** it into a integer and return that.  If pMem represents an
54354 ** an SQL-NULL value, return 0.
54355 **
54356 ** If pMem represents a string value, its encoding might be changed.
54357 */
54358 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
54359   int flags;
54360   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54361   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54362   flags = pMem->flags;
54363   if( flags & MEM_Int ){
54364     return pMem->u.i;
54365   }else if( flags & MEM_Real ){
54366     return doubleToInt64(pMem->r);
54367   }else if( flags & (MEM_Str|MEM_Blob) ){
54368     i64 value;
54369     assert( pMem->z || pMem->n==0 );
54370     testcase( pMem->z==0 );
54371     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
54372     return value;
54373   }else{
54374     return 0;
54375   }
54376 }
54377
54378 /*
54379 ** Return the best representation of pMem that we can get into a
54380 ** double.  If pMem is already a double or an integer, return its
54381 ** value.  If it is a string or blob, try to convert it to a double.
54382 ** If it is a NULL, return 0.0.
54383 */
54384 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
54385   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54386   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54387   if( pMem->flags & MEM_Real ){
54388     return pMem->r;
54389   }else if( pMem->flags & MEM_Int ){
54390     return (double)pMem->u.i;
54391   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
54392     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
54393     double val = (double)0;
54394     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
54395     return val;
54396   }else{
54397     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
54398     return (double)0;
54399   }
54400 }
54401
54402 /*
54403 ** The MEM structure is already a MEM_Real.  Try to also make it a
54404 ** MEM_Int if we can.
54405 */
54406 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
54407   assert( pMem->flags & MEM_Real );
54408   assert( (pMem->flags & MEM_RowSet)==0 );
54409   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54410   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54411
54412   pMem->u.i = doubleToInt64(pMem->r);
54413
54414   /* Only mark the value as an integer if
54415   **
54416   **    (1) the round-trip conversion real->int->real is a no-op, and
54417   **    (2) The integer is neither the largest nor the smallest
54418   **        possible integer (ticket #3922)
54419   **
54420   ** The second and third terms in the following conditional enforces
54421   ** the second condition under the assumption that addition overflow causes
54422   ** values to wrap around.  On x86 hardware, the third term is always
54423   ** true and could be omitted.  But we leave it in because other
54424   ** architectures might behave differently.
54425   */
54426   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
54427       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
54428     pMem->flags |= MEM_Int;
54429   }
54430 }
54431
54432 /*
54433 ** Convert pMem to type integer.  Invalidate any prior representations.
54434 */
54435 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
54436   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54437   assert( (pMem->flags & MEM_RowSet)==0 );
54438   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54439
54440   pMem->u.i = sqlite3VdbeIntValue(pMem);
54441   MemSetTypeFlag(pMem, MEM_Int);
54442   return SQLITE_OK;
54443 }
54444
54445 /*
54446 ** Convert pMem so that it is of type MEM_Real.
54447 ** Invalidate any prior representations.
54448 */
54449 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
54450   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54451   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
54452
54453   pMem->r = sqlite3VdbeRealValue(pMem);
54454   MemSetTypeFlag(pMem, MEM_Real);
54455   return SQLITE_OK;
54456 }
54457
54458 /*
54459 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
54460 ** Invalidate any prior representations.
54461 **
54462 ** Every effort is made to force the conversion, even if the input
54463 ** is a string that does not look completely like a number.  Convert
54464 ** as much of the string as we can and ignore the rest.
54465 */
54466 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
54467   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
54468     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
54469     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54470     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
54471       MemSetTypeFlag(pMem, MEM_Int);
54472     }else{
54473       pMem->r = sqlite3VdbeRealValue(pMem);
54474       MemSetTypeFlag(pMem, MEM_Real);
54475       sqlite3VdbeIntegerAffinity(pMem);
54476     }
54477   }
54478   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
54479   pMem->flags &= ~(MEM_Str|MEM_Blob);
54480   return SQLITE_OK;
54481 }
54482
54483 /*
54484 ** Delete any previous value and set the value stored in *pMem to NULL.
54485 */
54486 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
54487   if( pMem->flags & MEM_Frame ){
54488     VdbeFrame *pFrame = pMem->u.pFrame;
54489     pFrame->pParent = pFrame->v->pDelFrame;
54490     pFrame->v->pDelFrame = pFrame;
54491   }
54492   if( pMem->flags & MEM_RowSet ){
54493     sqlite3RowSetClear(pMem->u.pRowSet);
54494   }
54495   MemSetTypeFlag(pMem, MEM_Null);
54496   pMem->type = SQLITE_NULL;
54497 }
54498
54499 /*
54500 ** Delete any previous value and set the value to be a BLOB of length
54501 ** n containing all zeros.
54502 */
54503 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
54504   sqlite3VdbeMemRelease(pMem);
54505   pMem->flags = MEM_Blob|MEM_Zero;
54506   pMem->type = SQLITE_BLOB;
54507   pMem->n = 0;
54508   if( n<0 ) n = 0;
54509   pMem->u.nZero = n;
54510   pMem->enc = SQLITE_UTF8;
54511
54512 #ifdef SQLITE_OMIT_INCRBLOB
54513   sqlite3VdbeMemGrow(pMem, n, 0);
54514   if( pMem->z ){
54515     pMem->n = n;
54516     memset(pMem->z, 0, n);
54517   }
54518 #endif
54519 }
54520
54521 /*
54522 ** Delete any previous value and set the value stored in *pMem to val,
54523 ** manifest type INTEGER.
54524 */
54525 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
54526   sqlite3VdbeMemRelease(pMem);
54527   pMem->u.i = val;
54528   pMem->flags = MEM_Int;
54529   pMem->type = SQLITE_INTEGER;
54530 }
54531
54532 #ifndef SQLITE_OMIT_FLOATING_POINT
54533 /*
54534 ** Delete any previous value and set the value stored in *pMem to val,
54535 ** manifest type REAL.
54536 */
54537 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
54538   if( sqlite3IsNaN(val) ){
54539     sqlite3VdbeMemSetNull(pMem);
54540   }else{
54541     sqlite3VdbeMemRelease(pMem);
54542     pMem->r = val;
54543     pMem->flags = MEM_Real;
54544     pMem->type = SQLITE_FLOAT;
54545   }
54546 }
54547 #endif
54548
54549 /*
54550 ** Delete any previous value and set the value of pMem to be an
54551 ** empty boolean index.
54552 */
54553 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
54554   sqlite3 *db = pMem->db;
54555   assert( db!=0 );
54556   assert( (pMem->flags & MEM_RowSet)==0 );
54557   sqlite3VdbeMemRelease(pMem);
54558   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
54559   if( db->mallocFailed ){
54560     pMem->flags = MEM_Null;
54561   }else{
54562     assert( pMem->zMalloc );
54563     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
54564                                        sqlite3DbMallocSize(db, pMem->zMalloc));
54565     assert( pMem->u.pRowSet!=0 );
54566     pMem->flags = MEM_RowSet;
54567   }
54568 }
54569
54570 /*
54571 ** Return true if the Mem object contains a TEXT or BLOB that is
54572 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
54573 */
54574 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
54575   assert( p->db!=0 );
54576   if( p->flags & (MEM_Str|MEM_Blob) ){
54577     int n = p->n;
54578     if( p->flags & MEM_Zero ){
54579       n += p->u.nZero;
54580     }
54581     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
54582   }
54583   return 0; 
54584 }
54585
54586 #ifdef SQLITE_DEBUG
54587 /*
54588 ** This routine prepares a memory cell for modication by breaking
54589 ** its link to a shallow copy and by marking any current shallow
54590 ** copies of this cell as invalid.
54591 **
54592 ** This is used for testing and debugging only - to make sure shallow
54593 ** copies are not misused.
54594 */
54595 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
54596   int i;
54597   Mem *pX;
54598   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
54599     if( pX->pScopyFrom==pMem ){
54600       pX->flags |= MEM_Invalid;
54601       pX->pScopyFrom = 0;
54602     }
54603   }
54604   pMem->pScopyFrom = 0;
54605 }
54606 #endif /* SQLITE_DEBUG */
54607
54608 /*
54609 ** Size of struct Mem not including the Mem.zMalloc member.
54610 */
54611 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
54612
54613 /*
54614 ** Make an shallow copy of pFrom into pTo.  Prior contents of
54615 ** pTo are freed.  The pFrom->z field is not duplicated.  If
54616 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
54617 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
54618 */
54619 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
54620   assert( (pFrom->flags & MEM_RowSet)==0 );
54621   sqlite3VdbeMemReleaseExternal(pTo);
54622   memcpy(pTo, pFrom, MEMCELLSIZE);
54623   pTo->xDel = 0;
54624   if( (pFrom->flags&MEM_Static)==0 ){
54625     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
54626     assert( srcType==MEM_Ephem || srcType==MEM_Static );
54627     pTo->flags |= srcType;
54628   }
54629 }
54630
54631 /*
54632 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
54633 ** freed before the copy is made.
54634 */
54635 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
54636   int rc = SQLITE_OK;
54637
54638   assert( (pFrom->flags & MEM_RowSet)==0 );
54639   sqlite3VdbeMemReleaseExternal(pTo);
54640   memcpy(pTo, pFrom, MEMCELLSIZE);
54641   pTo->flags &= ~MEM_Dyn;
54642
54643   if( pTo->flags&(MEM_Str|MEM_Blob) ){
54644     if( 0==(pFrom->flags&MEM_Static) ){
54645       pTo->flags |= MEM_Ephem;
54646       rc = sqlite3VdbeMemMakeWriteable(pTo);
54647     }
54648   }
54649
54650   return rc;
54651 }
54652
54653 /*
54654 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
54655 ** freed. If pFrom contains ephemeral data, a copy is made.
54656 **
54657 ** pFrom contains an SQL NULL when this routine returns.
54658 */
54659 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
54660   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
54661   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
54662   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
54663
54664   sqlite3VdbeMemRelease(pTo);
54665   memcpy(pTo, pFrom, sizeof(Mem));
54666   pFrom->flags = MEM_Null;
54667   pFrom->xDel = 0;
54668   pFrom->zMalloc = 0;
54669 }
54670
54671 /*
54672 ** Change the value of a Mem to be a string or a BLOB.
54673 **
54674 ** The memory management strategy depends on the value of the xDel
54675 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
54676 ** string is copied into a (possibly existing) buffer managed by the 
54677 ** Mem structure. Otherwise, any existing buffer is freed and the
54678 ** pointer copied.
54679 **
54680 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
54681 ** size limit) then no memory allocation occurs.  If the string can be
54682 ** stored without allocating memory, then it is.  If a memory allocation
54683 ** is required to store the string, then value of pMem is unchanged.  In
54684 ** either case, SQLITE_TOOBIG is returned.
54685 */
54686 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
54687   Mem *pMem,          /* Memory cell to set to string value */
54688   const char *z,      /* String pointer */
54689   int n,              /* Bytes in string, or negative */
54690   u8 enc,             /* Encoding of z.  0 for BLOBs */
54691   void (*xDel)(void*) /* Destructor function */
54692 ){
54693   int nByte = n;      /* New value for pMem->n */
54694   int iLimit;         /* Maximum allowed string or blob size */
54695   u16 flags = 0;      /* New value for pMem->flags */
54696
54697   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
54698   assert( (pMem->flags & MEM_RowSet)==0 );
54699
54700   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
54701   if( !z ){
54702     sqlite3VdbeMemSetNull(pMem);
54703     return SQLITE_OK;
54704   }
54705
54706   if( pMem->db ){
54707     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
54708   }else{
54709     iLimit = SQLITE_MAX_LENGTH;
54710   }
54711   flags = (enc==0?MEM_Blob:MEM_Str);
54712   if( nByte<0 ){
54713     assert( enc!=0 );
54714     if( enc==SQLITE_UTF8 ){
54715       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
54716     }else{
54717       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
54718     }
54719     flags |= MEM_Term;
54720   }
54721
54722   /* The following block sets the new values of Mem.z and Mem.xDel. It
54723   ** also sets a flag in local variable "flags" to indicate the memory
54724   ** management (one of MEM_Dyn or MEM_Static).
54725   */
54726   if( xDel==SQLITE_TRANSIENT ){
54727     int nAlloc = nByte;
54728     if( flags&MEM_Term ){
54729       nAlloc += (enc==SQLITE_UTF8?1:2);
54730     }
54731     if( nByte>iLimit ){
54732       return SQLITE_TOOBIG;
54733     }
54734     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
54735       return SQLITE_NOMEM;
54736     }
54737     memcpy(pMem->z, z, nAlloc);
54738   }else if( xDel==SQLITE_DYNAMIC ){
54739     sqlite3VdbeMemRelease(pMem);
54740     pMem->zMalloc = pMem->z = (char *)z;
54741     pMem->xDel = 0;
54742   }else{
54743     sqlite3VdbeMemRelease(pMem);
54744     pMem->z = (char *)z;
54745     pMem->xDel = xDel;
54746     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
54747   }
54748
54749   pMem->n = nByte;
54750   pMem->flags = flags;
54751   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
54752   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
54753
54754 #ifndef SQLITE_OMIT_UTF16
54755   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
54756     return SQLITE_NOMEM;
54757   }
54758 #endif
54759
54760   if( nByte>iLimit ){
54761     return SQLITE_TOOBIG;
54762   }
54763
54764   return SQLITE_OK;
54765 }
54766
54767 /*
54768 ** Compare the values contained by the two memory cells, returning
54769 ** negative, zero or positive if pMem1 is less than, equal to, or greater
54770 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
54771 ** and reals) sorted numerically, followed by text ordered by the collating
54772 ** sequence pColl and finally blob's ordered by memcmp().
54773 **
54774 ** Two NULL values are considered equal by this function.
54775 */
54776 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
54777   int rc;
54778   int f1, f2;
54779   int combined_flags;
54780
54781   f1 = pMem1->flags;
54782   f2 = pMem2->flags;
54783   combined_flags = f1|f2;
54784   assert( (combined_flags & MEM_RowSet)==0 );
54785  
54786   /* If one value is NULL, it is less than the other. If both values
54787   ** are NULL, return 0.
54788   */
54789   if( combined_flags&MEM_Null ){
54790     return (f2&MEM_Null) - (f1&MEM_Null);
54791   }
54792
54793   /* If one value is a number and the other is not, the number is less.
54794   ** If both are numbers, compare as reals if one is a real, or as integers
54795   ** if both values are integers.
54796   */
54797   if( combined_flags&(MEM_Int|MEM_Real) ){
54798     if( !(f1&(MEM_Int|MEM_Real)) ){
54799       return 1;
54800     }
54801     if( !(f2&(MEM_Int|MEM_Real)) ){
54802       return -1;
54803     }
54804     if( (f1 & f2 & MEM_Int)==0 ){
54805       double r1, r2;
54806       if( (f1&MEM_Real)==0 ){
54807         r1 = (double)pMem1->u.i;
54808       }else{
54809         r1 = pMem1->r;
54810       }
54811       if( (f2&MEM_Real)==0 ){
54812         r2 = (double)pMem2->u.i;
54813       }else{
54814         r2 = pMem2->r;
54815       }
54816       if( r1<r2 ) return -1;
54817       if( r1>r2 ) return 1;
54818       return 0;
54819     }else{
54820       assert( f1&MEM_Int );
54821       assert( f2&MEM_Int );
54822       if( pMem1->u.i < pMem2->u.i ) return -1;
54823       if( pMem1->u.i > pMem2->u.i ) return 1;
54824       return 0;
54825     }
54826   }
54827
54828   /* If one value is a string and the other is a blob, the string is less.
54829   ** If both are strings, compare using the collating functions.
54830   */
54831   if( combined_flags&MEM_Str ){
54832     if( (f1 & MEM_Str)==0 ){
54833       return 1;
54834     }
54835     if( (f2 & MEM_Str)==0 ){
54836       return -1;
54837     }
54838
54839     assert( pMem1->enc==pMem2->enc );
54840     assert( pMem1->enc==SQLITE_UTF8 || 
54841             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
54842
54843     /* The collation sequence must be defined at this point, even if
54844     ** the user deletes the collation sequence after the vdbe program is
54845     ** compiled (this was not always the case).
54846     */
54847     assert( !pColl || pColl->xCmp );
54848
54849     if( pColl ){
54850       if( pMem1->enc==pColl->enc ){
54851         /* The strings are already in the correct encoding.  Call the
54852         ** comparison function directly */
54853         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
54854       }else{
54855         const void *v1, *v2;
54856         int n1, n2;
54857         Mem c1;
54858         Mem c2;
54859         memset(&c1, 0, sizeof(c1));
54860         memset(&c2, 0, sizeof(c2));
54861         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
54862         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
54863         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
54864         n1 = v1==0 ? 0 : c1.n;
54865         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
54866         n2 = v2==0 ? 0 : c2.n;
54867         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
54868         sqlite3VdbeMemRelease(&c1);
54869         sqlite3VdbeMemRelease(&c2);
54870         return rc;
54871       }
54872     }
54873     /* If a NULL pointer was passed as the collate function, fall through
54874     ** to the blob case and use memcmp().  */
54875   }
54876  
54877   /* Both values must be blobs.  Compare using memcmp().  */
54878   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
54879   if( rc==0 ){
54880     rc = pMem1->n - pMem2->n;
54881   }
54882   return rc;
54883 }
54884
54885 /*
54886 ** Move data out of a btree key or data field and into a Mem structure.
54887 ** The data or key is taken from the entry that pCur is currently pointing
54888 ** to.  offset and amt determine what portion of the data or key to retrieve.
54889 ** key is true to get the key or false to get data.  The result is written
54890 ** into the pMem element.
54891 **
54892 ** The pMem structure is assumed to be uninitialized.  Any prior content
54893 ** is overwritten without being freed.
54894 **
54895 ** If this routine fails for any reason (malloc returns NULL or unable
54896 ** to read from the disk) then the pMem is left in an inconsistent state.
54897 */
54898 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
54899   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
54900   int offset,       /* Offset from the start of data to return bytes from. */
54901   int amt,          /* Number of bytes to return. */
54902   int key,          /* If true, retrieve from the btree key, not data. */
54903   Mem *pMem         /* OUT: Return data in this Mem structure. */
54904 ){
54905   char *zData;        /* Data from the btree layer */
54906   int available = 0;  /* Number of bytes available on the local btree page */
54907   int rc = SQLITE_OK; /* Return code */
54908
54909   assert( sqlite3BtreeCursorIsValid(pCur) );
54910
54911   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
54912   ** that both the BtShared and database handle mutexes are held. */
54913   assert( (pMem->flags & MEM_RowSet)==0 );
54914   if( key ){
54915     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
54916   }else{
54917     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
54918   }
54919   assert( zData!=0 );
54920
54921   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
54922     sqlite3VdbeMemRelease(pMem);
54923     pMem->z = &zData[offset];
54924     pMem->flags = MEM_Blob|MEM_Ephem;
54925   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
54926     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
54927     pMem->enc = 0;
54928     pMem->type = SQLITE_BLOB;
54929     if( key ){
54930       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
54931     }else{
54932       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
54933     }
54934     pMem->z[amt] = 0;
54935     pMem->z[amt+1] = 0;
54936     if( rc!=SQLITE_OK ){
54937       sqlite3VdbeMemRelease(pMem);
54938     }
54939   }
54940   pMem->n = amt;
54941
54942   return rc;
54943 }
54944
54945 /* This function is only available internally, it is not part of the
54946 ** external API. It works in a similar way to sqlite3_value_text(),
54947 ** except the data returned is in the encoding specified by the second
54948 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
54949 ** SQLITE_UTF8.
54950 **
54951 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
54952 ** If that is the case, then the result must be aligned on an even byte
54953 ** boundary.
54954 */
54955 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
54956   if( !pVal ) return 0;
54957
54958   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
54959   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
54960   assert( (pVal->flags & MEM_RowSet)==0 );
54961
54962   if( pVal->flags&MEM_Null ){
54963     return 0;
54964   }
54965   assert( (MEM_Blob>>3) == MEM_Str );
54966   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
54967   expandBlob(pVal);
54968   if( pVal->flags&MEM_Str ){
54969     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
54970     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
54971       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
54972       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
54973         return 0;
54974       }
54975     }
54976     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
54977   }else{
54978     assert( (pVal->flags&MEM_Blob)==0 );
54979     sqlite3VdbeMemStringify(pVal, enc);
54980     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
54981   }
54982   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
54983               || pVal->db->mallocFailed );
54984   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
54985     return pVal->z;
54986   }else{
54987     return 0;
54988   }
54989 }
54990
54991 /*
54992 ** Create a new sqlite3_value object.
54993 */
54994 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
54995   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
54996   if( p ){
54997     p->flags = MEM_Null;
54998     p->type = SQLITE_NULL;
54999     p->db = db;
55000   }
55001   return p;
55002 }
55003
55004 /*
55005 ** Create a new sqlite3_value object, containing the value of pExpr.
55006 **
55007 ** This only works for very simple expressions that consist of one constant
55008 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
55009 ** be converted directly into a value, then the value is allocated and
55010 ** a pointer written to *ppVal. The caller is responsible for deallocating
55011 ** the value by passing it to sqlite3ValueFree() later on. If the expression
55012 ** cannot be converted to a value, then *ppVal is set to NULL.
55013 */
55014 SQLITE_PRIVATE int sqlite3ValueFromExpr(
55015   sqlite3 *db,              /* The database connection */
55016   Expr *pExpr,              /* The expression to evaluate */
55017   u8 enc,                   /* Encoding to use */
55018   u8 affinity,              /* Affinity to use */
55019   sqlite3_value **ppVal     /* Write the new value here */
55020 ){
55021   int op;
55022   char *zVal = 0;
55023   sqlite3_value *pVal = 0;
55024   int negInt = 1;
55025   const char *zNeg = "";
55026
55027   if( !pExpr ){
55028     *ppVal = 0;
55029     return SQLITE_OK;
55030   }
55031   op = pExpr->op;
55032
55033   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
55034   ** The ifdef here is to enable us to achieve 100% branch test coverage even
55035   ** when SQLITE_ENABLE_STAT2 is omitted.
55036   */
55037 #ifdef SQLITE_ENABLE_STAT2
55038   if( op==TK_REGISTER ) op = pExpr->op2;
55039 #else
55040   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
55041 #endif
55042
55043   /* Handle negative integers in a single step.  This is needed in the
55044   ** case when the value is -9223372036854775808.
55045   */
55046   if( op==TK_UMINUS
55047    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
55048     pExpr = pExpr->pLeft;
55049     op = pExpr->op;
55050     negInt = -1;
55051     zNeg = "-";
55052   }
55053
55054   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
55055     pVal = sqlite3ValueNew(db);
55056     if( pVal==0 ) goto no_mem;
55057     if( ExprHasProperty(pExpr, EP_IntValue) ){
55058       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
55059     }else{
55060       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
55061       if( zVal==0 ) goto no_mem;
55062       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
55063       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
55064     }
55065     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
55066       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
55067     }else{
55068       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
55069     }
55070     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
55071     if( enc!=SQLITE_UTF8 ){
55072       sqlite3VdbeChangeEncoding(pVal, enc);
55073     }
55074   }else if( op==TK_UMINUS ) {
55075     /* This branch happens for multiple negative signs.  Ex: -(-5) */
55076     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
55077       sqlite3VdbeMemNumerify(pVal);
55078       pVal->u.i = -1 * pVal->u.i;
55079       /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
55080       pVal->r = (double)-1 * pVal->r;
55081       sqlite3ValueApplyAffinity(pVal, affinity, enc);
55082     }
55083   }
55084 #ifndef SQLITE_OMIT_BLOB_LITERAL
55085   else if( op==TK_BLOB ){
55086     int nVal;
55087     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
55088     assert( pExpr->u.zToken[1]=='\'' );
55089     pVal = sqlite3ValueNew(db);
55090     if( !pVal ) goto no_mem;
55091     zVal = &pExpr->u.zToken[2];
55092     nVal = sqlite3Strlen30(zVal)-1;
55093     assert( zVal[nVal]=='\'' );
55094     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
55095                          0, SQLITE_DYNAMIC);
55096   }
55097 #endif
55098
55099   if( pVal ){
55100     sqlite3VdbeMemStoreType(pVal);
55101   }
55102   *ppVal = pVal;
55103   return SQLITE_OK;
55104
55105 no_mem:
55106   db->mallocFailed = 1;
55107   sqlite3DbFree(db, zVal);
55108   sqlite3ValueFree(pVal);
55109   *ppVal = 0;
55110   return SQLITE_NOMEM;
55111 }
55112
55113 /*
55114 ** Change the string value of an sqlite3_value object
55115 */
55116 SQLITE_PRIVATE void sqlite3ValueSetStr(
55117   sqlite3_value *v,     /* Value to be set */
55118   int n,                /* Length of string z */
55119   const void *z,        /* Text of the new string */
55120   u8 enc,               /* Encoding to use */
55121   void (*xDel)(void*)   /* Destructor for the string */
55122 ){
55123   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
55124 }
55125
55126 /*
55127 ** Free an sqlite3_value object
55128 */
55129 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
55130   if( !v ) return;
55131   sqlite3VdbeMemRelease((Mem *)v);
55132   sqlite3DbFree(((Mem*)v)->db, v);
55133 }
55134
55135 /*
55136 ** Return the number of bytes in the sqlite3_value object assuming
55137 ** that it uses the encoding "enc"
55138 */
55139 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
55140   Mem *p = (Mem*)pVal;
55141   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
55142     if( p->flags & MEM_Zero ){
55143       return p->n + p->u.nZero;
55144     }else{
55145       return p->n;
55146     }
55147   }
55148   return 0;
55149 }
55150
55151 /************** End of vdbemem.c *********************************************/
55152 /************** Begin file vdbeaux.c *****************************************/
55153 /*
55154 ** 2003 September 6
55155 **
55156 ** The author disclaims copyright to this source code.  In place of
55157 ** a legal notice, here is a blessing:
55158 **
55159 **    May you do good and not evil.
55160 **    May you find forgiveness for yourself and forgive others.
55161 **    May you share freely, never taking more than you give.
55162 **
55163 *************************************************************************
55164 ** This file contains code used for creating, destroying, and populating
55165 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
55166 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
55167 ** But that file was getting too big so this subroutines were split out.
55168 */
55169
55170
55171
55172 /*
55173 ** When debugging the code generator in a symbolic debugger, one can
55174 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
55175 ** as they are added to the instruction stream.
55176 */
55177 #ifdef SQLITE_DEBUG
55178 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
55179 #endif
55180
55181
55182 /*
55183 ** Create a new virtual database engine.
55184 */
55185 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
55186   Vdbe *p;
55187   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
55188   if( p==0 ) return 0;
55189   p->db = db;
55190   if( db->pVdbe ){
55191     db->pVdbe->pPrev = p;
55192   }
55193   p->pNext = db->pVdbe;
55194   p->pPrev = 0;
55195   db->pVdbe = p;
55196   p->magic = VDBE_MAGIC_INIT;
55197   return p;
55198 }
55199
55200 /*
55201 ** Remember the SQL string for a prepared statement.
55202 */
55203 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
55204   assert( isPrepareV2==1 || isPrepareV2==0 );
55205   if( p==0 ) return;
55206 #ifdef SQLITE_OMIT_TRACE
55207   if( !isPrepareV2 ) return;
55208 #endif
55209   assert( p->zSql==0 );
55210   p->zSql = sqlite3DbStrNDup(p->db, z, n);
55211   p->isPrepareV2 = (u8)isPrepareV2;
55212 }
55213
55214 /*
55215 ** Return the SQL associated with a prepared statement
55216 */
55217 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
55218   Vdbe *p = (Vdbe *)pStmt;
55219   return (p && p->isPrepareV2) ? p->zSql : 0;
55220 }
55221
55222 /*
55223 ** Swap all content between two VDBE structures.
55224 */
55225 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
55226   Vdbe tmp, *pTmp;
55227   char *zTmp;
55228   tmp = *pA;
55229   *pA = *pB;
55230   *pB = tmp;
55231   pTmp = pA->pNext;
55232   pA->pNext = pB->pNext;
55233   pB->pNext = pTmp;
55234   pTmp = pA->pPrev;
55235   pA->pPrev = pB->pPrev;
55236   pB->pPrev = pTmp;
55237   zTmp = pA->zSql;
55238   pA->zSql = pB->zSql;
55239   pB->zSql = zTmp;
55240   pB->isPrepareV2 = pA->isPrepareV2;
55241 }
55242
55243 #ifdef SQLITE_DEBUG
55244 /*
55245 ** Turn tracing on or off
55246 */
55247 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
55248   p->trace = trace;
55249 }
55250 #endif
55251
55252 /*
55253 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
55254 ** it was.
55255 **
55256 ** If an out-of-memory error occurs while resizing the array, return
55257 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
55258 ** unchanged (this is so that any opcodes already allocated can be 
55259 ** correctly deallocated along with the rest of the Vdbe).
55260 */
55261 static int growOpArray(Vdbe *p){
55262   VdbeOp *pNew;
55263   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
55264   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
55265   if( pNew ){
55266     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
55267     p->aOp = pNew;
55268   }
55269   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
55270 }
55271
55272 /*
55273 ** Add a new instruction to the list of instructions current in the
55274 ** VDBE.  Return the address of the new instruction.
55275 **
55276 ** Parameters:
55277 **
55278 **    p               Pointer to the VDBE
55279 **
55280 **    op              The opcode for this instruction
55281 **
55282 **    p1, p2, p3      Operands
55283 **
55284 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
55285 ** the sqlite3VdbeChangeP4() function to change the value of the P4
55286 ** operand.
55287 */
55288 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
55289   int i;
55290   VdbeOp *pOp;
55291
55292   i = p->nOp;
55293   assert( p->magic==VDBE_MAGIC_INIT );
55294   assert( op>0 && op<0xff );
55295   if( p->nOpAlloc<=i ){
55296     if( growOpArray(p) ){
55297       return 1;
55298     }
55299   }
55300   p->nOp++;
55301   pOp = &p->aOp[i];
55302   pOp->opcode = (u8)op;
55303   pOp->p5 = 0;
55304   pOp->p1 = p1;
55305   pOp->p2 = p2;
55306   pOp->p3 = p3;
55307   pOp->p4.p = 0;
55308   pOp->p4type = P4_NOTUSED;
55309   p->expired = 0;
55310 #ifdef SQLITE_DEBUG
55311   pOp->zComment = 0;
55312   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
55313 #endif
55314 #ifdef VDBE_PROFILE
55315   pOp->cycles = 0;
55316   pOp->cnt = 0;
55317 #endif
55318   return i;
55319 }
55320 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
55321   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
55322 }
55323 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
55324   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
55325 }
55326 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
55327   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
55328 }
55329
55330
55331 /*
55332 ** Add an opcode that includes the p4 value as a pointer.
55333 */
55334 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
55335   Vdbe *p,            /* Add the opcode to this VM */
55336   int op,             /* The new opcode */
55337   int p1,             /* The P1 operand */
55338   int p2,             /* The P2 operand */
55339   int p3,             /* The P3 operand */
55340   const char *zP4,    /* The P4 operand */
55341   int p4type          /* P4 operand type */
55342 ){
55343   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
55344   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
55345   return addr;
55346 }
55347
55348 /*
55349 ** Add an opcode that includes the p4 value as an integer.
55350 */
55351 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
55352   Vdbe *p,            /* Add the opcode to this VM */
55353   int op,             /* The new opcode */
55354   int p1,             /* The P1 operand */
55355   int p2,             /* The P2 operand */
55356   int p3,             /* The P3 operand */
55357   int p4              /* The P4 operand as an integer */
55358 ){
55359   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
55360   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
55361   return addr;
55362 }
55363
55364 /*
55365 ** Create a new symbolic label for an instruction that has yet to be
55366 ** coded.  The symbolic label is really just a negative number.  The
55367 ** label can be used as the P2 value of an operation.  Later, when
55368 ** the label is resolved to a specific address, the VDBE will scan
55369 ** through its operation list and change all values of P2 which match
55370 ** the label into the resolved address.
55371 **
55372 ** The VDBE knows that a P2 value is a label because labels are
55373 ** always negative and P2 values are suppose to be non-negative.
55374 ** Hence, a negative P2 value is a label that has yet to be resolved.
55375 **
55376 ** Zero is returned if a malloc() fails.
55377 */
55378 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
55379   int i;
55380   i = p->nLabel++;
55381   assert( p->magic==VDBE_MAGIC_INIT );
55382   if( i>=p->nLabelAlloc ){
55383     int n = p->nLabelAlloc*2 + 5;
55384     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
55385                                        n*sizeof(p->aLabel[0]));
55386     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
55387   }
55388   if( p->aLabel ){
55389     p->aLabel[i] = -1;
55390   }
55391   return -1-i;
55392 }
55393
55394 /*
55395 ** Resolve label "x" to be the address of the next instruction to
55396 ** be inserted.  The parameter "x" must have been obtained from
55397 ** a prior call to sqlite3VdbeMakeLabel().
55398 */
55399 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
55400   int j = -1-x;
55401   assert( p->magic==VDBE_MAGIC_INIT );
55402   assert( j>=0 && j<p->nLabel );
55403   if( p->aLabel ){
55404     p->aLabel[j] = p->nOp;
55405   }
55406 }
55407
55408 /*
55409 ** Mark the VDBE as one that can only be run one time.
55410 */
55411 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
55412   p->runOnlyOnce = 1;
55413 }
55414
55415 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
55416
55417 /*
55418 ** The following type and function are used to iterate through all opcodes
55419 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
55420 ** invoke directly or indirectly. It should be used as follows:
55421 **
55422 **   Op *pOp;
55423 **   VdbeOpIter sIter;
55424 **
55425 **   memset(&sIter, 0, sizeof(sIter));
55426 **   sIter.v = v;                            // v is of type Vdbe* 
55427 **   while( (pOp = opIterNext(&sIter)) ){
55428 **     // Do something with pOp
55429 **   }
55430 **   sqlite3DbFree(v->db, sIter.apSub);
55431 ** 
55432 */
55433 typedef struct VdbeOpIter VdbeOpIter;
55434 struct VdbeOpIter {
55435   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
55436   SubProgram **apSub;        /* Array of subprograms */
55437   int nSub;                  /* Number of entries in apSub */
55438   int iAddr;                 /* Address of next instruction to return */
55439   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
55440 };
55441 static Op *opIterNext(VdbeOpIter *p){
55442   Vdbe *v = p->v;
55443   Op *pRet = 0;
55444   Op *aOp;
55445   int nOp;
55446
55447   if( p->iSub<=p->nSub ){
55448
55449     if( p->iSub==0 ){
55450       aOp = v->aOp;
55451       nOp = v->nOp;
55452     }else{
55453       aOp = p->apSub[p->iSub-1]->aOp;
55454       nOp = p->apSub[p->iSub-1]->nOp;
55455     }
55456     assert( p->iAddr<nOp );
55457
55458     pRet = &aOp[p->iAddr];
55459     p->iAddr++;
55460     if( p->iAddr==nOp ){
55461       p->iSub++;
55462       p->iAddr = 0;
55463     }
55464   
55465     if( pRet->p4type==P4_SUBPROGRAM ){
55466       int nByte = (p->nSub+1)*sizeof(SubProgram*);
55467       int j;
55468       for(j=0; j<p->nSub; j++){
55469         if( p->apSub[j]==pRet->p4.pProgram ) break;
55470       }
55471       if( j==p->nSub ){
55472         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
55473         if( !p->apSub ){
55474           pRet = 0;
55475         }else{
55476           p->apSub[p->nSub++] = pRet->p4.pProgram;
55477         }
55478       }
55479     }
55480   }
55481
55482   return pRet;
55483 }
55484
55485 /*
55486 ** Check if the program stored in the VM associated with pParse may
55487 ** throw an ABORT exception (causing the statement, but not entire transaction
55488 ** to be rolled back). This condition is true if the main program or any
55489 ** sub-programs contains any of the following:
55490 **
55491 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
55492 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
55493 **   *  OP_Destroy
55494 **   *  OP_VUpdate
55495 **   *  OP_VRename
55496 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
55497 **
55498 ** Then check that the value of Parse.mayAbort is true if an
55499 ** ABORT may be thrown, or false otherwise. Return true if it does
55500 ** match, or false otherwise. This function is intended to be used as
55501 ** part of an assert statement in the compiler. Similar to:
55502 **
55503 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
55504 */
55505 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
55506   int hasAbort = 0;
55507   Op *pOp;
55508   VdbeOpIter sIter;
55509   memset(&sIter, 0, sizeof(sIter));
55510   sIter.v = v;
55511
55512   while( (pOp = opIterNext(&sIter))!=0 ){
55513     int opcode = pOp->opcode;
55514     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
55515 #ifndef SQLITE_OMIT_FOREIGN_KEY
55516      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
55517 #endif
55518      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
55519       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
55520     ){
55521       hasAbort = 1;
55522       break;
55523     }
55524   }
55525   sqlite3DbFree(v->db, sIter.apSub);
55526
55527   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
55528   ** If malloc failed, then the while() loop above may not have iterated
55529   ** through all opcodes and hasAbort may be set incorrectly. Return
55530   ** true for this case to prevent the assert() in the callers frame
55531   ** from failing.  */
55532   return ( v->db->mallocFailed || hasAbort==mayAbort );
55533 }
55534 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
55535
55536 /*
55537 ** Loop through the program looking for P2 values that are negative
55538 ** on jump instructions.  Each such value is a label.  Resolve the
55539 ** label by setting the P2 value to its correct non-zero value.
55540 **
55541 ** This routine is called once after all opcodes have been inserted.
55542 **
55543 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
55544 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
55545 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
55546 **
55547 ** The Op.opflags field is set on all opcodes.
55548 */
55549 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
55550   int i;
55551   int nMaxArgs = *pMaxFuncArgs;
55552   Op *pOp;
55553   int *aLabel = p->aLabel;
55554   p->readOnly = 1;
55555   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
55556     u8 opcode = pOp->opcode;
55557
55558     pOp->opflags = sqlite3OpcodeProperty[opcode];
55559     if( opcode==OP_Function || opcode==OP_AggStep ){
55560       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
55561     }else if( opcode==OP_Transaction && pOp->p2!=0 ){
55562       p->readOnly = 0;
55563 #ifndef SQLITE_OMIT_VIRTUALTABLE
55564     }else if( opcode==OP_VUpdate ){
55565       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
55566     }else if( opcode==OP_VFilter ){
55567       int n;
55568       assert( p->nOp - i >= 3 );
55569       assert( pOp[-1].opcode==OP_Integer );
55570       n = pOp[-1].p1;
55571       if( n>nMaxArgs ) nMaxArgs = n;
55572 #endif
55573     }
55574
55575     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
55576       assert( -1-pOp->p2<p->nLabel );
55577       pOp->p2 = aLabel[-1-pOp->p2];
55578     }
55579   }
55580   sqlite3DbFree(p->db, p->aLabel);
55581   p->aLabel = 0;
55582
55583   *pMaxFuncArgs = nMaxArgs;
55584 }
55585
55586 /*
55587 ** Return the address of the next instruction to be inserted.
55588 */
55589 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
55590   assert( p->magic==VDBE_MAGIC_INIT );
55591   return p->nOp;
55592 }
55593
55594 /*
55595 ** This function returns a pointer to the array of opcodes associated with
55596 ** the Vdbe passed as the first argument. It is the callers responsibility
55597 ** to arrange for the returned array to be eventually freed using the 
55598 ** vdbeFreeOpArray() function.
55599 **
55600 ** Before returning, *pnOp is set to the number of entries in the returned
55601 ** array. Also, *pnMaxArg is set to the larger of its current value and 
55602 ** the number of entries in the Vdbe.apArg[] array required to execute the 
55603 ** returned program.
55604 */
55605 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
55606   VdbeOp *aOp = p->aOp;
55607   assert( aOp && !p->db->mallocFailed );
55608
55609   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
55610   assert( p->aMutex.nMutex==0 );
55611
55612   resolveP2Values(p, pnMaxArg);
55613   *pnOp = p->nOp;
55614   p->aOp = 0;
55615   return aOp;
55616 }
55617
55618 /*
55619 ** Add a whole list of operations to the operation stack.  Return the
55620 ** address of the first operation added.
55621 */
55622 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
55623   int addr;
55624   assert( p->magic==VDBE_MAGIC_INIT );
55625   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
55626     return 0;
55627   }
55628   addr = p->nOp;
55629   if( ALWAYS(nOp>0) ){
55630     int i;
55631     VdbeOpList const *pIn = aOp;
55632     for(i=0; i<nOp; i++, pIn++){
55633       int p2 = pIn->p2;
55634       VdbeOp *pOut = &p->aOp[i+addr];
55635       pOut->opcode = pIn->opcode;
55636       pOut->p1 = pIn->p1;
55637       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
55638         pOut->p2 = addr + ADDR(p2);
55639       }else{
55640         pOut->p2 = p2;
55641       }
55642       pOut->p3 = pIn->p3;
55643       pOut->p4type = P4_NOTUSED;
55644       pOut->p4.p = 0;
55645       pOut->p5 = 0;
55646 #ifdef SQLITE_DEBUG
55647       pOut->zComment = 0;
55648       if( sqlite3VdbeAddopTrace ){
55649         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
55650       }
55651 #endif
55652     }
55653     p->nOp += nOp;
55654   }
55655   return addr;
55656 }
55657
55658 /*
55659 ** Change the value of the P1 operand for a specific instruction.
55660 ** This routine is useful when a large program is loaded from a
55661 ** static array using sqlite3VdbeAddOpList but we want to make a
55662 ** few minor changes to the program.
55663 */
55664 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
55665   assert( p!=0 );
55666   assert( addr>=0 );
55667   if( p->nOp>addr ){
55668     p->aOp[addr].p1 = val;
55669   }
55670 }
55671
55672 /*
55673 ** Change the value of the P2 operand for a specific instruction.
55674 ** This routine is useful for setting a jump destination.
55675 */
55676 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
55677   assert( p!=0 );
55678   assert( addr>=0 );
55679   if( p->nOp>addr ){
55680     p->aOp[addr].p2 = val;
55681   }
55682 }
55683
55684 /*
55685 ** Change the value of the P3 operand for a specific instruction.
55686 */
55687 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
55688   assert( p!=0 );
55689   assert( addr>=0 );
55690   if( p->nOp>addr ){
55691     p->aOp[addr].p3 = val;
55692   }
55693 }
55694
55695 /*
55696 ** Change the value of the P5 operand for the most recently
55697 ** added operation.
55698 */
55699 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
55700   assert( p!=0 );
55701   if( p->aOp ){
55702     assert( p->nOp>0 );
55703     p->aOp[p->nOp-1].p5 = val;
55704   }
55705 }
55706
55707 /*
55708 ** Change the P2 operand of instruction addr so that it points to
55709 ** the address of the next instruction to be coded.
55710 */
55711 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
55712   sqlite3VdbeChangeP2(p, addr, p->nOp);
55713 }
55714
55715
55716 /*
55717 ** If the input FuncDef structure is ephemeral, then free it.  If
55718 ** the FuncDef is not ephermal, then do nothing.
55719 */
55720 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
55721   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
55722     sqlite3DbFree(db, pDef);
55723   }
55724 }
55725
55726 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
55727
55728 /*
55729 ** Delete a P4 value if necessary.
55730 */
55731 static void freeP4(sqlite3 *db, int p4type, void *p4){
55732   if( p4 ){
55733     assert( db );
55734     switch( p4type ){
55735       case P4_REAL:
55736       case P4_INT64:
55737       case P4_DYNAMIC:
55738       case P4_KEYINFO:
55739       case P4_INTARRAY:
55740       case P4_KEYINFO_HANDOFF: {
55741         sqlite3DbFree(db, p4);
55742         break;
55743       }
55744       case P4_MPRINTF: {
55745         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
55746         break;
55747       }
55748       case P4_VDBEFUNC: {
55749         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
55750         freeEphemeralFunction(db, pVdbeFunc->pFunc);
55751         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
55752         sqlite3DbFree(db, pVdbeFunc);
55753         break;
55754       }
55755       case P4_FUNCDEF: {
55756         freeEphemeralFunction(db, (FuncDef*)p4);
55757         break;
55758       }
55759       case P4_MEM: {
55760         if( db->pnBytesFreed==0 ){
55761           sqlite3ValueFree((sqlite3_value*)p4);
55762         }else{
55763           Mem *p = (Mem*)p4;
55764           sqlite3DbFree(db, p->zMalloc);
55765           sqlite3DbFree(db, p);
55766         }
55767         break;
55768       }
55769       case P4_VTAB : {
55770         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
55771         break;
55772       }
55773     }
55774   }
55775 }
55776
55777 /*
55778 ** Free the space allocated for aOp and any p4 values allocated for the
55779 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
55780 ** nOp entries. 
55781 */
55782 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
55783   if( aOp ){
55784     Op *pOp;
55785     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
55786       freeP4(db, pOp->p4type, pOp->p4.p);
55787 #ifdef SQLITE_DEBUG
55788       sqlite3DbFree(db, pOp->zComment);
55789 #endif     
55790     }
55791   }
55792   sqlite3DbFree(db, aOp);
55793 }
55794
55795 /*
55796 ** Link the SubProgram object passed as the second argument into the linked
55797 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
55798 ** objects when the VM is no longer required.
55799 */
55800 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
55801   p->pNext = pVdbe->pProgram;
55802   pVdbe->pProgram = p;
55803 }
55804
55805 /*
55806 ** Change N opcodes starting at addr to No-ops.
55807 */
55808 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
55809   if( p->aOp ){
55810     VdbeOp *pOp = &p->aOp[addr];
55811     sqlite3 *db = p->db;
55812     while( N-- ){
55813       freeP4(db, pOp->p4type, pOp->p4.p);
55814       memset(pOp, 0, sizeof(pOp[0]));
55815       pOp->opcode = OP_Noop;
55816       pOp++;
55817     }
55818   }
55819 }
55820
55821 /*
55822 ** Change the value of the P4 operand for a specific instruction.
55823 ** This routine is useful when a large program is loaded from a
55824 ** static array using sqlite3VdbeAddOpList but we want to make a
55825 ** few minor changes to the program.
55826 **
55827 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
55828 ** the string is made into memory obtained from sqlite3_malloc().
55829 ** A value of n==0 means copy bytes of zP4 up to and including the
55830 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
55831 **
55832 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
55833 ** A copy is made of the KeyInfo structure into memory obtained from
55834 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
55835 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
55836 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
55837 ** caller should not free the allocation, it will be freed when the Vdbe is
55838 ** finalized.
55839 ** 
55840 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
55841 ** to a string or structure that is guaranteed to exist for the lifetime of
55842 ** the Vdbe. In these cases we can just copy the pointer.
55843 **
55844 ** If addr<0 then change P4 on the most recently inserted instruction.
55845 */
55846 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
55847   Op *pOp;
55848   sqlite3 *db;
55849   assert( p!=0 );
55850   db = p->db;
55851   assert( p->magic==VDBE_MAGIC_INIT );
55852   if( p->aOp==0 || db->mallocFailed ){
55853     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
55854       freeP4(db, n, (void*)*(char**)&zP4);
55855     }
55856     return;
55857   }
55858   assert( p->nOp>0 );
55859   assert( addr<p->nOp );
55860   if( addr<0 ){
55861     addr = p->nOp - 1;
55862   }
55863   pOp = &p->aOp[addr];
55864   freeP4(db, pOp->p4type, pOp->p4.p);
55865   pOp->p4.p = 0;
55866   if( n==P4_INT32 ){
55867     /* Note: this cast is safe, because the origin data point was an int
55868     ** that was cast to a (const char *). */
55869     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
55870     pOp->p4type = P4_INT32;
55871   }else if( zP4==0 ){
55872     pOp->p4.p = 0;
55873     pOp->p4type = P4_NOTUSED;
55874   }else if( n==P4_KEYINFO ){
55875     KeyInfo *pKeyInfo;
55876     int nField, nByte;
55877
55878     nField = ((KeyInfo*)zP4)->nField;
55879     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
55880     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
55881     pOp->p4.pKeyInfo = pKeyInfo;
55882     if( pKeyInfo ){
55883       u8 *aSortOrder;
55884       memcpy((char*)pKeyInfo, zP4, nByte - nField);
55885       aSortOrder = pKeyInfo->aSortOrder;
55886       if( aSortOrder ){
55887         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
55888         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
55889       }
55890       pOp->p4type = P4_KEYINFO;
55891     }else{
55892       p->db->mallocFailed = 1;
55893       pOp->p4type = P4_NOTUSED;
55894     }
55895   }else if( n==P4_KEYINFO_HANDOFF ){
55896     pOp->p4.p = (void*)zP4;
55897     pOp->p4type = P4_KEYINFO;
55898   }else if( n==P4_VTAB ){
55899     pOp->p4.p = (void*)zP4;
55900     pOp->p4type = P4_VTAB;
55901     sqlite3VtabLock((VTable *)zP4);
55902     assert( ((VTable *)zP4)->db==p->db );
55903   }else if( n<0 ){
55904     pOp->p4.p = (void*)zP4;
55905     pOp->p4type = (signed char)n;
55906   }else{
55907     if( n==0 ) n = sqlite3Strlen30(zP4);
55908     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
55909     pOp->p4type = P4_DYNAMIC;
55910   }
55911 }
55912
55913 #ifndef NDEBUG
55914 /*
55915 ** Change the comment on the the most recently coded instruction.  Or
55916 ** insert a No-op and add the comment to that new instruction.  This
55917 ** makes the code easier to read during debugging.  None of this happens
55918 ** in a production build.
55919 */
55920 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
55921   va_list ap;
55922   if( !p ) return;
55923   assert( p->nOp>0 || p->aOp==0 );
55924   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
55925   if( p->nOp ){
55926     char **pz = &p->aOp[p->nOp-1].zComment;
55927     va_start(ap, zFormat);
55928     sqlite3DbFree(p->db, *pz);
55929     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
55930     va_end(ap);
55931   }
55932 }
55933 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
55934   va_list ap;
55935   if( !p ) return;
55936   sqlite3VdbeAddOp0(p, OP_Noop);
55937   assert( p->nOp>0 || p->aOp==0 );
55938   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
55939   if( p->nOp ){
55940     char **pz = &p->aOp[p->nOp-1].zComment;
55941     va_start(ap, zFormat);
55942     sqlite3DbFree(p->db, *pz);
55943     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
55944     va_end(ap);
55945   }
55946 }
55947 #endif  /* NDEBUG */
55948
55949 /*
55950 ** Return the opcode for a given address.  If the address is -1, then
55951 ** return the most recently inserted opcode.
55952 **
55953 ** If a memory allocation error has occurred prior to the calling of this
55954 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
55955 ** is readable but not writable, though it is cast to a writable value.
55956 ** The return of a dummy opcode allows the call to continue functioning
55957 ** after a OOM fault without having to check to see if the return from 
55958 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
55959 ** dummy will never be written to.  This is verified by code inspection and
55960 ** by running with Valgrind.
55961 **
55962 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
55963 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
55964 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
55965 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
55966 ** having to double-check to make sure that the result is non-negative. But
55967 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
55968 ** check the value of p->nOp-1 before continuing.
55969 */
55970 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
55971   /* C89 specifies that the constant "dummy" will be initialized to all
55972   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
55973   static const VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
55974   assert( p->magic==VDBE_MAGIC_INIT );
55975   if( addr<0 ){
55976 #ifdef SQLITE_OMIT_TRACE
55977     if( p->nOp==0 ) return (VdbeOp*)&dummy;
55978 #endif
55979     addr = p->nOp - 1;
55980   }
55981   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
55982   if( p->db->mallocFailed ){
55983     return (VdbeOp*)&dummy;
55984   }else{
55985     return &p->aOp[addr];
55986   }
55987 }
55988
55989 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
55990      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
55991 /*
55992 ** Compute a string that describes the P4 parameter for an opcode.
55993 ** Use zTemp for any required temporary buffer space.
55994 */
55995 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
55996   char *zP4 = zTemp;
55997   assert( nTemp>=20 );
55998   switch( pOp->p4type ){
55999     case P4_KEYINFO_STATIC:
56000     case P4_KEYINFO: {
56001       int i, j;
56002       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
56003       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
56004       i = sqlite3Strlen30(zTemp);
56005       for(j=0; j<pKeyInfo->nField; j++){
56006         CollSeq *pColl = pKeyInfo->aColl[j];
56007         if( pColl ){
56008           int n = sqlite3Strlen30(pColl->zName);
56009           if( i+n>nTemp-6 ){
56010             memcpy(&zTemp[i],",...",4);
56011             break;
56012           }
56013           zTemp[i++] = ',';
56014           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
56015             zTemp[i++] = '-';
56016           }
56017           memcpy(&zTemp[i], pColl->zName,n+1);
56018           i += n;
56019         }else if( i+4<nTemp-6 ){
56020           memcpy(&zTemp[i],",nil",4);
56021           i += 4;
56022         }
56023       }
56024       zTemp[i++] = ')';
56025       zTemp[i] = 0;
56026       assert( i<nTemp );
56027       break;
56028     }
56029     case P4_COLLSEQ: {
56030       CollSeq *pColl = pOp->p4.pColl;
56031       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
56032       break;
56033     }
56034     case P4_FUNCDEF: {
56035       FuncDef *pDef = pOp->p4.pFunc;
56036       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
56037       break;
56038     }
56039     case P4_INT64: {
56040       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
56041       break;
56042     }
56043     case P4_INT32: {
56044       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
56045       break;
56046     }
56047     case P4_REAL: {
56048       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
56049       break;
56050     }
56051     case P4_MEM: {
56052       Mem *pMem = pOp->p4.pMem;
56053       assert( (pMem->flags & MEM_Null)==0 );
56054       if( pMem->flags & MEM_Str ){
56055         zP4 = pMem->z;
56056       }else if( pMem->flags & MEM_Int ){
56057         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
56058       }else if( pMem->flags & MEM_Real ){
56059         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
56060       }else{
56061         assert( pMem->flags & MEM_Blob );
56062         zP4 = "(blob)";
56063       }
56064       break;
56065     }
56066 #ifndef SQLITE_OMIT_VIRTUALTABLE
56067     case P4_VTAB: {
56068       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
56069       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
56070       break;
56071     }
56072 #endif
56073     case P4_INTARRAY: {
56074       sqlite3_snprintf(nTemp, zTemp, "intarray");
56075       break;
56076     }
56077     case P4_SUBPROGRAM: {
56078       sqlite3_snprintf(nTemp, zTemp, "program");
56079       break;
56080     }
56081     default: {
56082       zP4 = pOp->p4.z;
56083       if( zP4==0 ){
56084         zP4 = zTemp;
56085         zTemp[0] = 0;
56086       }
56087     }
56088   }
56089   assert( zP4!=0 );
56090   return zP4;
56091 }
56092 #endif
56093
56094 /*
56095 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
56096 **
56097 ** The prepared statement has to know in advance which Btree objects
56098 ** will be used so that it can acquire mutexes on them all in sorted
56099 ** order (via sqlite3VdbeMutexArrayEnter().  Mutexes are acquired
56100 ** in order (and released in reverse order) to avoid deadlocks.
56101 */
56102 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
56103   int mask;
56104   assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
56105   assert( i<(int)sizeof(p->btreeMask)*8 );
56106   mask = ((u32)1)<<i;
56107   if( (p->btreeMask & mask)==0 ){
56108     p->btreeMask |= mask;
56109     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
56110   }
56111 }
56112
56113
56114 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
56115 /*
56116 ** Print a single opcode.  This routine is used for debugging only.
56117 */
56118 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
56119   char *zP4;
56120   char zPtr[50];
56121   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
56122   if( pOut==0 ) pOut = stdout;
56123   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
56124   fprintf(pOut, zFormat1, pc, 
56125       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
56126 #ifdef SQLITE_DEBUG
56127       pOp->zComment ? pOp->zComment : ""
56128 #else
56129       ""
56130 #endif
56131   );
56132   fflush(pOut);
56133 }
56134 #endif
56135
56136 /*
56137 ** Release an array of N Mem elements
56138 */
56139 static void releaseMemArray(Mem *p, int N){
56140   if( p && N ){
56141     Mem *pEnd;
56142     sqlite3 *db = p->db;
56143     u8 malloc_failed = db->mallocFailed;
56144     if( db->pnBytesFreed ){
56145       for(pEnd=&p[N]; p<pEnd; p++){
56146         sqlite3DbFree(db, p->zMalloc);
56147       }
56148       return;
56149     }
56150     for(pEnd=&p[N]; p<pEnd; p++){
56151       assert( (&p[1])==pEnd || p[0].db==p[1].db );
56152
56153       /* This block is really an inlined version of sqlite3VdbeMemRelease()
56154       ** that takes advantage of the fact that the memory cell value is 
56155       ** being set to NULL after releasing any dynamic resources.
56156       **
56157       ** The justification for duplicating code is that according to 
56158       ** callgrind, this causes a certain test case to hit the CPU 4.7 
56159       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
56160       ** sqlite3MemRelease() were called from here. With -O2, this jumps
56161       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
56162       ** with no indexes using a single prepared INSERT statement, bind() 
56163       ** and reset(). Inserts are grouped into a transaction.
56164       */
56165       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
56166         sqlite3VdbeMemRelease(p);
56167       }else if( p->zMalloc ){
56168         sqlite3DbFree(db, p->zMalloc);
56169         p->zMalloc = 0;
56170       }
56171
56172       p->flags = MEM_Null;
56173     }
56174     db->mallocFailed = malloc_failed;
56175   }
56176 }
56177
56178 /*
56179 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
56180 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
56181 */
56182 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
56183   int i;
56184   Mem *aMem = VdbeFrameMem(p);
56185   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
56186   for(i=0; i<p->nChildCsr; i++){
56187     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
56188   }
56189   releaseMemArray(aMem, p->nChildMem);
56190   sqlite3DbFree(p->v->db, p);
56191 }
56192
56193 #ifndef SQLITE_OMIT_EXPLAIN
56194 /*
56195 ** Give a listing of the program in the virtual machine.
56196 **
56197 ** The interface is the same as sqlite3VdbeExec().  But instead of
56198 ** running the code, it invokes the callback once for each instruction.
56199 ** This feature is used to implement "EXPLAIN".
56200 **
56201 ** When p->explain==1, each instruction is listed.  When
56202 ** p->explain==2, only OP_Explain instructions are listed and these
56203 ** are shown in a different format.  p->explain==2 is used to implement
56204 ** EXPLAIN QUERY PLAN.
56205 **
56206 ** When p->explain==1, first the main program is listed, then each of
56207 ** the trigger subprograms are listed one by one.
56208 */
56209 SQLITE_PRIVATE int sqlite3VdbeList(
56210   Vdbe *p                   /* The VDBE */
56211 ){
56212   int nRow;                            /* Stop when row count reaches this */
56213   int nSub = 0;                        /* Number of sub-vdbes seen so far */
56214   SubProgram **apSub = 0;              /* Array of sub-vdbes */
56215   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
56216   sqlite3 *db = p->db;                 /* The database connection */
56217   int i;                               /* Loop counter */
56218   int rc = SQLITE_OK;                  /* Return code */
56219   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
56220
56221   assert( p->explain );
56222   assert( p->magic==VDBE_MAGIC_RUN );
56223   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
56224
56225   /* Even though this opcode does not use dynamic strings for
56226   ** the result, result columns may become dynamic if the user calls
56227   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
56228   */
56229   releaseMemArray(pMem, 8);
56230
56231   if( p->rc==SQLITE_NOMEM ){
56232     /* This happens if a malloc() inside a call to sqlite3_column_text() or
56233     ** sqlite3_column_text16() failed.  */
56234     db->mallocFailed = 1;
56235     return SQLITE_ERROR;
56236   }
56237
56238   /* When the number of output rows reaches nRow, that means the
56239   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
56240   ** nRow is the sum of the number of rows in the main program, plus
56241   ** the sum of the number of rows in all trigger subprograms encountered
56242   ** so far.  The nRow value will increase as new trigger subprograms are
56243   ** encountered, but p->pc will eventually catch up to nRow.
56244   */
56245   nRow = p->nOp;
56246   if( p->explain==1 ){
56247     /* The first 8 memory cells are used for the result set.  So we will
56248     ** commandeer the 9th cell to use as storage for an array of pointers
56249     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
56250     ** cells.  */
56251     assert( p->nMem>9 );
56252     pSub = &p->aMem[9];
56253     if( pSub->flags&MEM_Blob ){
56254       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
56255       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
56256       nSub = pSub->n/sizeof(Vdbe*);
56257       apSub = (SubProgram **)pSub->z;
56258     }
56259     for(i=0; i<nSub; i++){
56260       nRow += apSub[i]->nOp;
56261     }
56262   }
56263
56264   do{
56265     i = p->pc++;
56266   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
56267   if( i>=nRow ){
56268     p->rc = SQLITE_OK;
56269     rc = SQLITE_DONE;
56270   }else if( db->u1.isInterrupted ){
56271     p->rc = SQLITE_INTERRUPT;
56272     rc = SQLITE_ERROR;
56273     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
56274   }else{
56275     char *z;
56276     Op *pOp;
56277     if( i<p->nOp ){
56278       /* The output line number is small enough that we are still in the
56279       ** main program. */
56280       pOp = &p->aOp[i];
56281     }else{
56282       /* We are currently listing subprograms.  Figure out which one and
56283       ** pick up the appropriate opcode. */
56284       int j;
56285       i -= p->nOp;
56286       for(j=0; i>=apSub[j]->nOp; j++){
56287         i -= apSub[j]->nOp;
56288       }
56289       pOp = &apSub[j]->aOp[i];
56290     }
56291     if( p->explain==1 ){
56292       pMem->flags = MEM_Int;
56293       pMem->type = SQLITE_INTEGER;
56294       pMem->u.i = i;                                /* Program counter */
56295       pMem++;
56296   
56297       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
56298       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
56299       assert( pMem->z!=0 );
56300       pMem->n = sqlite3Strlen30(pMem->z);
56301       pMem->type = SQLITE_TEXT;
56302       pMem->enc = SQLITE_UTF8;
56303       pMem++;
56304
56305       /* When an OP_Program opcode is encounter (the only opcode that has
56306       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
56307       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
56308       ** has not already been seen.
56309       */
56310       if( pOp->p4type==P4_SUBPROGRAM ){
56311         int nByte = (nSub+1)*sizeof(SubProgram*);
56312         int j;
56313         for(j=0; j<nSub; j++){
56314           if( apSub[j]==pOp->p4.pProgram ) break;
56315         }
56316         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
56317           apSub = (SubProgram **)pSub->z;
56318           apSub[nSub++] = pOp->p4.pProgram;
56319           pSub->flags |= MEM_Blob;
56320           pSub->n = nSub*sizeof(SubProgram*);
56321         }
56322       }
56323     }
56324
56325     pMem->flags = MEM_Int;
56326     pMem->u.i = pOp->p1;                          /* P1 */
56327     pMem->type = SQLITE_INTEGER;
56328     pMem++;
56329
56330     pMem->flags = MEM_Int;
56331     pMem->u.i = pOp->p2;                          /* P2 */
56332     pMem->type = SQLITE_INTEGER;
56333     pMem++;
56334
56335     pMem->flags = MEM_Int;
56336     pMem->u.i = pOp->p3;                          /* P3 */
56337     pMem->type = SQLITE_INTEGER;
56338     pMem++;
56339
56340     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
56341       assert( p->db->mallocFailed );
56342       return SQLITE_ERROR;
56343     }
56344     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
56345     z = displayP4(pOp, pMem->z, 32);
56346     if( z!=pMem->z ){
56347       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
56348     }else{
56349       assert( pMem->z!=0 );
56350       pMem->n = sqlite3Strlen30(pMem->z);
56351       pMem->enc = SQLITE_UTF8;
56352     }
56353     pMem->type = SQLITE_TEXT;
56354     pMem++;
56355
56356     if( p->explain==1 ){
56357       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
56358         assert( p->db->mallocFailed );
56359         return SQLITE_ERROR;
56360       }
56361       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
56362       pMem->n = 2;
56363       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
56364       pMem->type = SQLITE_TEXT;
56365       pMem->enc = SQLITE_UTF8;
56366       pMem++;
56367   
56368 #ifdef SQLITE_DEBUG
56369       if( pOp->zComment ){
56370         pMem->flags = MEM_Str|MEM_Term;
56371         pMem->z = pOp->zComment;
56372         pMem->n = sqlite3Strlen30(pMem->z);
56373         pMem->enc = SQLITE_UTF8;
56374         pMem->type = SQLITE_TEXT;
56375       }else
56376 #endif
56377       {
56378         pMem->flags = MEM_Null;                       /* Comment */
56379         pMem->type = SQLITE_NULL;
56380       }
56381     }
56382
56383     p->nResColumn = 8 - 4*(p->explain-1);
56384     p->rc = SQLITE_OK;
56385     rc = SQLITE_ROW;
56386   }
56387   return rc;
56388 }
56389 #endif /* SQLITE_OMIT_EXPLAIN */
56390
56391 #ifdef SQLITE_DEBUG
56392 /*
56393 ** Print the SQL that was used to generate a VDBE program.
56394 */
56395 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
56396   int nOp = p->nOp;
56397   VdbeOp *pOp;
56398   if( nOp<1 ) return;
56399   pOp = &p->aOp[0];
56400   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
56401     const char *z = pOp->p4.z;
56402     while( sqlite3Isspace(*z) ) z++;
56403     printf("SQL: [%s]\n", z);
56404   }
56405 }
56406 #endif
56407
56408 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
56409 /*
56410 ** Print an IOTRACE message showing SQL content.
56411 */
56412 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
56413   int nOp = p->nOp;
56414   VdbeOp *pOp;
56415   if( sqlite3IoTrace==0 ) return;
56416   if( nOp<1 ) return;
56417   pOp = &p->aOp[0];
56418   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
56419     int i, j;
56420     char z[1000];
56421     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
56422     for(i=0; sqlite3Isspace(z[i]); i++){}
56423     for(j=0; z[i]; i++){
56424       if( sqlite3Isspace(z[i]) ){
56425         if( z[i-1]!=' ' ){
56426           z[j++] = ' ';
56427         }
56428       }else{
56429         z[j++] = z[i];
56430       }
56431     }
56432     z[j] = 0;
56433     sqlite3IoTrace("SQL %s\n", z);
56434   }
56435 }
56436 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
56437
56438 /*
56439 ** Allocate space from a fixed size buffer and return a pointer to
56440 ** that space.  If insufficient space is available, return NULL.
56441 **
56442 ** The pBuf parameter is the initial value of a pointer which will
56443 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
56444 ** NULL, it means that memory space has already been allocated and that
56445 ** this routine should not allocate any new memory.  When pBuf is not
56446 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
56447 ** is NULL.
56448 **
56449 ** nByte is the number of bytes of space needed.
56450 **
56451 ** *ppFrom points to available space and pEnd points to the end of the
56452 ** available space.  When space is allocated, *ppFrom is advanced past
56453 ** the end of the allocated space.
56454 **
56455 ** *pnByte is a counter of the number of bytes of space that have failed
56456 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
56457 ** request, then increment *pnByte by the amount of the request.
56458 */
56459 static void *allocSpace(
56460   void *pBuf,          /* Where return pointer will be stored */
56461   int nByte,           /* Number of bytes to allocate */
56462   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
56463   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
56464   int *pnByte          /* If allocation cannot be made, increment *pnByte */
56465 ){
56466   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
56467   if( pBuf ) return pBuf;
56468   nByte = ROUND8(nByte);
56469   if( &(*ppFrom)[nByte] <= pEnd ){
56470     pBuf = (void*)*ppFrom;
56471     *ppFrom += nByte;
56472   }else{
56473     *pnByte += nByte;
56474   }
56475   return pBuf;
56476 }
56477
56478 /*
56479 ** Prepare a virtual machine for execution.  This involves things such
56480 ** as allocating stack space and initializing the program counter.
56481 ** After the VDBE has be prepped, it can be executed by one or more
56482 ** calls to sqlite3VdbeExec().  
56483 **
56484 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
56485 ** VDBE_MAGIC_RUN.
56486 **
56487 ** This function may be called more than once on a single virtual machine.
56488 ** The first call is made while compiling the SQL statement. Subsequent
56489 ** calls are made as part of the process of resetting a statement to be
56490 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor 
56491 ** and isExplain parameters are only passed correct values the first time
56492 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
56493 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
56494 */
56495 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
56496   Vdbe *p,                       /* The VDBE */
56497   int nVar,                      /* Number of '?' see in the SQL statement */
56498   int nMem,                      /* Number of memory cells to allocate */
56499   int nCursor,                   /* Number of cursors to allocate */
56500   int nArg,                      /* Maximum number of args in SubPrograms */
56501   int isExplain,                 /* True if the EXPLAIN keywords is present */
56502   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
56503 ){
56504   int n;
56505   sqlite3 *db = p->db;
56506
56507   assert( p!=0 );
56508   assert( p->magic==VDBE_MAGIC_INIT );
56509
56510   /* There should be at least one opcode.
56511   */
56512   assert( p->nOp>0 );
56513
56514   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
56515   p->magic = VDBE_MAGIC_RUN;
56516
56517   /* For each cursor required, also allocate a memory cell. Memory
56518   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
56519   ** the vdbe program. Instead they are used to allocate space for
56520   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
56521   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
56522   ** stores the blob of memory associated with cursor 1, etc.
56523   **
56524   ** See also: allocateCursor().
56525   */
56526   nMem += nCursor;
56527
56528   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
56529   ** an array to marshal SQL function arguments in. This is only done the
56530   ** first time this function is called for a given VDBE, not when it is
56531   ** being called from sqlite3_reset() to reset the virtual machine.
56532   */
56533   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
56534     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
56535     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
56536     int nByte;                              /* How much extra memory needed */
56537
56538     resolveP2Values(p, &nArg);
56539     p->usesStmtJournal = (u8)usesStmtJournal;
56540     if( isExplain && nMem<10 ){
56541       nMem = 10;
56542     }
56543     memset(zCsr, 0, zEnd-zCsr);
56544     zCsr += (zCsr - (u8*)0)&7;
56545     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
56546
56547     /* Memory for registers, parameters, cursor, etc, is allocated in two
56548     ** passes.  On the first pass, we try to reuse unused space at the 
56549     ** end of the opcode array.  If we are unable to satisfy all memory
56550     ** requirements by reusing the opcode array tail, then the second
56551     ** pass will fill in the rest using a fresh allocation.  
56552     **
56553     ** This two-pass approach that reuses as much memory as possible from
56554     ** the leftover space at the end of the opcode array can significantly
56555     ** reduce the amount of memory held by a prepared statement.
56556     */
56557     do {
56558       nByte = 0;
56559       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
56560       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
56561       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
56562       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
56563       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
56564                             &zCsr, zEnd, &nByte);
56565       if( nByte ){
56566         p->pFree = sqlite3DbMallocZero(db, nByte);
56567       }
56568       zCsr = p->pFree;
56569       zEnd = &zCsr[nByte];
56570     }while( nByte && !db->mallocFailed );
56571
56572     p->nCursor = (u16)nCursor;
56573     if( p->aVar ){
56574       p->nVar = (ynVar)nVar;
56575       for(n=0; n<nVar; n++){
56576         p->aVar[n].flags = MEM_Null;
56577         p->aVar[n].db = db;
56578       }
56579     }
56580     if( p->aMem ){
56581       p->aMem--;                      /* aMem[] goes from 1..nMem */
56582       p->nMem = nMem;                 /*       not from 0..nMem-1 */
56583       for(n=1; n<=nMem; n++){
56584         p->aMem[n].flags = MEM_Null;
56585         p->aMem[n].db = db;
56586       }
56587     }
56588   }
56589 #ifdef SQLITE_DEBUG
56590   for(n=1; n<p->nMem; n++){
56591     assert( p->aMem[n].db==db );
56592   }
56593 #endif
56594
56595   p->pc = -1;
56596   p->rc = SQLITE_OK;
56597   p->errorAction = OE_Abort;
56598   p->explain |= isExplain;
56599   p->magic = VDBE_MAGIC_RUN;
56600   p->nChange = 0;
56601   p->cacheCtr = 1;
56602   p->minWriteFileFormat = 255;
56603   p->iStatement = 0;
56604   p->nFkConstraint = 0;
56605 #ifdef VDBE_PROFILE
56606   {
56607     int i;
56608     for(i=0; i<p->nOp; i++){
56609       p->aOp[i].cnt = 0;
56610       p->aOp[i].cycles = 0;
56611     }
56612   }
56613 #endif
56614 }
56615
56616 /*
56617 ** Close a VDBE cursor and release all the resources that cursor 
56618 ** happens to hold.
56619 */
56620 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
56621   if( pCx==0 ){
56622     return;
56623   }
56624   if( pCx->pBt ){
56625     sqlite3BtreeClose(pCx->pBt);
56626     /* The pCx->pCursor will be close automatically, if it exists, by
56627     ** the call above. */
56628   }else if( pCx->pCursor ){
56629     sqlite3BtreeCloseCursor(pCx->pCursor);
56630   }
56631 #ifndef SQLITE_OMIT_VIRTUALTABLE
56632   if( pCx->pVtabCursor ){
56633     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
56634     const sqlite3_module *pModule = pCx->pModule;
56635     p->inVtabMethod = 1;
56636     pModule->xClose(pVtabCursor);
56637     p->inVtabMethod = 0;
56638   }
56639 #endif
56640 }
56641
56642 /*
56643 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
56644 ** is used, for example, when a trigger sub-program is halted to restore
56645 ** control to the main program.
56646 */
56647 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
56648   Vdbe *v = pFrame->v;
56649   v->aOp = pFrame->aOp;
56650   v->nOp = pFrame->nOp;
56651   v->aMem = pFrame->aMem;
56652   v->nMem = pFrame->nMem;
56653   v->apCsr = pFrame->apCsr;
56654   v->nCursor = pFrame->nCursor;
56655   v->db->lastRowid = pFrame->lastRowid;
56656   v->nChange = pFrame->nChange;
56657   return pFrame->pc;
56658 }
56659
56660 /*
56661 ** Close all cursors.
56662 **
56663 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
56664 ** cell array. This is necessary as the memory cell array may contain
56665 ** pointers to VdbeFrame objects, which may in turn contain pointers to
56666 ** open cursors.
56667 */
56668 static void closeAllCursors(Vdbe *p){
56669   if( p->pFrame ){
56670     VdbeFrame *pFrame = p->pFrame;
56671     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
56672     sqlite3VdbeFrameRestore(pFrame);
56673   }
56674   p->pFrame = 0;
56675   p->nFrame = 0;
56676
56677   if( p->apCsr ){
56678     int i;
56679     for(i=0; i<p->nCursor; i++){
56680       VdbeCursor *pC = p->apCsr[i];
56681       if( pC ){
56682         sqlite3VdbeFreeCursor(p, pC);
56683         p->apCsr[i] = 0;
56684       }
56685     }
56686   }
56687   if( p->aMem ){
56688     releaseMemArray(&p->aMem[1], p->nMem);
56689   }
56690   while( p->pDelFrame ){
56691     VdbeFrame *pDel = p->pDelFrame;
56692     p->pDelFrame = pDel->pParent;
56693     sqlite3VdbeFrameDelete(pDel);
56694   }
56695 }
56696
56697 /*
56698 ** Clean up the VM after execution.
56699 **
56700 ** This routine will automatically close any cursors, lists, and/or
56701 ** sorters that were left open.  It also deletes the values of
56702 ** variables in the aVar[] array.
56703 */
56704 static void Cleanup(Vdbe *p){
56705   sqlite3 *db = p->db;
56706
56707 #ifdef SQLITE_DEBUG
56708   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
56709   ** Vdbe.aMem[] arrays have already been cleaned up.  */
56710   int i;
56711   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
56712   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
56713 #endif
56714
56715   sqlite3DbFree(db, p->zErrMsg);
56716   p->zErrMsg = 0;
56717   p->pResultSet = 0;
56718 }
56719
56720 /*
56721 ** Set the number of result columns that will be returned by this SQL
56722 ** statement. This is now set at compile time, rather than during
56723 ** execution of the vdbe program so that sqlite3_column_count() can
56724 ** be called on an SQL statement before sqlite3_step().
56725 */
56726 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
56727   Mem *pColName;
56728   int n;
56729   sqlite3 *db = p->db;
56730
56731   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
56732   sqlite3DbFree(db, p->aColName);
56733   n = nResColumn*COLNAME_N;
56734   p->nResColumn = (u16)nResColumn;
56735   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
56736   if( p->aColName==0 ) return;
56737   while( n-- > 0 ){
56738     pColName->flags = MEM_Null;
56739     pColName->db = p->db;
56740     pColName++;
56741   }
56742 }
56743
56744 /*
56745 ** Set the name of the idx'th column to be returned by the SQL statement.
56746 ** zName must be a pointer to a nul terminated string.
56747 **
56748 ** This call must be made after a call to sqlite3VdbeSetNumCols().
56749 **
56750 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
56751 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
56752 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
56753 */
56754 SQLITE_PRIVATE int sqlite3VdbeSetColName(
56755   Vdbe *p,                         /* Vdbe being configured */
56756   int idx,                         /* Index of column zName applies to */
56757   int var,                         /* One of the COLNAME_* constants */
56758   const char *zName,               /* Pointer to buffer containing name */
56759   void (*xDel)(void*)              /* Memory management strategy for zName */
56760 ){
56761   int rc;
56762   Mem *pColName;
56763   assert( idx<p->nResColumn );
56764   assert( var<COLNAME_N );
56765   if( p->db->mallocFailed ){
56766     assert( !zName || xDel!=SQLITE_DYNAMIC );
56767     return SQLITE_NOMEM;
56768   }
56769   assert( p->aColName!=0 );
56770   pColName = &(p->aColName[idx+var*p->nResColumn]);
56771   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
56772   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
56773   return rc;
56774 }
56775
56776 /*
56777 ** A read or write transaction may or may not be active on database handle
56778 ** db. If a transaction is active, commit it. If there is a
56779 ** write-transaction spanning more than one database file, this routine
56780 ** takes care of the master journal trickery.
56781 */
56782 static int vdbeCommit(sqlite3 *db, Vdbe *p){
56783   int i;
56784   int nTrans = 0;  /* Number of databases with an active write-transaction */
56785   int rc = SQLITE_OK;
56786   int needXcommit = 0;
56787
56788 #ifdef SQLITE_OMIT_VIRTUALTABLE
56789   /* With this option, sqlite3VtabSync() is defined to be simply 
56790   ** SQLITE_OK so p is not used. 
56791   */
56792   UNUSED_PARAMETER(p);
56793 #endif
56794
56795   /* Before doing anything else, call the xSync() callback for any
56796   ** virtual module tables written in this transaction. This has to
56797   ** be done before determining whether a master journal file is 
56798   ** required, as an xSync() callback may add an attached database
56799   ** to the transaction.
56800   */
56801   rc = sqlite3VtabSync(db, &p->zErrMsg);
56802
56803   /* This loop determines (a) if the commit hook should be invoked and
56804   ** (b) how many database files have open write transactions, not 
56805   ** including the temp database. (b) is important because if more than 
56806   ** one database file has an open write transaction, a master journal
56807   ** file is required for an atomic commit.
56808   */ 
56809   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
56810     Btree *pBt = db->aDb[i].pBt;
56811     if( sqlite3BtreeIsInTrans(pBt) ){
56812       needXcommit = 1;
56813       if( i!=1 ) nTrans++;
56814       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
56815     }
56816   }
56817   if( rc!=SQLITE_OK ){
56818     return rc;
56819   }
56820
56821   /* If there are any write-transactions at all, invoke the commit hook */
56822   if( needXcommit && db->xCommitCallback ){
56823     rc = db->xCommitCallback(db->pCommitArg);
56824     if( rc ){
56825       return SQLITE_CONSTRAINT;
56826     }
56827   }
56828
56829   /* The simple case - no more than one database file (not counting the
56830   ** TEMP database) has a transaction active.   There is no need for the
56831   ** master-journal.
56832   **
56833   ** If the return value of sqlite3BtreeGetFilename() is a zero length
56834   ** string, it means the main database is :memory: or a temp file.  In 
56835   ** that case we do not support atomic multi-file commits, so use the 
56836   ** simple case then too.
56837   */
56838   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
56839    || nTrans<=1
56840   ){
56841     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
56842       Btree *pBt = db->aDb[i].pBt;
56843       if( pBt ){
56844         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
56845       }
56846     }
56847
56848     /* Do the commit only if all databases successfully complete phase 1. 
56849     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
56850     ** IO error while deleting or truncating a journal file. It is unlikely,
56851     ** but could happen. In this case abandon processing and return the error.
56852     */
56853     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
56854       Btree *pBt = db->aDb[i].pBt;
56855       if( pBt ){
56856         rc = sqlite3BtreeCommitPhaseTwo(pBt);
56857       }
56858     }
56859     if( rc==SQLITE_OK ){
56860       sqlite3VtabCommit(db);
56861     }
56862   }
56863
56864   /* The complex case - There is a multi-file write-transaction active.
56865   ** This requires a master journal file to ensure the transaction is
56866   ** committed atomicly.
56867   */
56868 #ifndef SQLITE_OMIT_DISKIO
56869   else{
56870     sqlite3_vfs *pVfs = db->pVfs;
56871     int needSync = 0;
56872     char *zMaster = 0;   /* File-name for the master journal */
56873     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
56874     sqlite3_file *pMaster = 0;
56875     i64 offset = 0;
56876     int res;
56877
56878     /* Select a master journal file name */
56879     do {
56880       u32 iRandom;
56881       sqlite3DbFree(db, zMaster);
56882       sqlite3_randomness(sizeof(iRandom), &iRandom);
56883       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
56884       if( !zMaster ){
56885         return SQLITE_NOMEM;
56886       }
56887       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
56888     }while( rc==SQLITE_OK && res );
56889     if( rc==SQLITE_OK ){
56890       /* Open the master journal. */
56891       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
56892           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
56893           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
56894       );
56895     }
56896     if( rc!=SQLITE_OK ){
56897       sqlite3DbFree(db, zMaster);
56898       return rc;
56899     }
56900  
56901     /* Write the name of each database file in the transaction into the new
56902     ** master journal file. If an error occurs at this point close
56903     ** and delete the master journal file. All the individual journal files
56904     ** still have 'null' as the master journal pointer, so they will roll
56905     ** back independently if a failure occurs.
56906     */
56907     for(i=0; i<db->nDb; i++){
56908       Btree *pBt = db->aDb[i].pBt;
56909       if( sqlite3BtreeIsInTrans(pBt) ){
56910         char const *zFile = sqlite3BtreeGetJournalname(pBt);
56911         if( zFile==0 ){
56912           continue;  /* Ignore TEMP and :memory: databases */
56913         }
56914         assert( zFile[0]!=0 );
56915         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
56916           needSync = 1;
56917         }
56918         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
56919         offset += sqlite3Strlen30(zFile)+1;
56920         if( rc!=SQLITE_OK ){
56921           sqlite3OsCloseFree(pMaster);
56922           sqlite3OsDelete(pVfs, zMaster, 0);
56923           sqlite3DbFree(db, zMaster);
56924           return rc;
56925         }
56926       }
56927     }
56928
56929     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
56930     ** flag is set this is not required.
56931     */
56932     if( needSync 
56933      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
56934      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
56935     ){
56936       sqlite3OsCloseFree(pMaster);
56937       sqlite3OsDelete(pVfs, zMaster, 0);
56938       sqlite3DbFree(db, zMaster);
56939       return rc;
56940     }
56941
56942     /* Sync all the db files involved in the transaction. The same call
56943     ** sets the master journal pointer in each individual journal. If
56944     ** an error occurs here, do not delete the master journal file.
56945     **
56946     ** If the error occurs during the first call to
56947     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
56948     ** master journal file will be orphaned. But we cannot delete it,
56949     ** in case the master journal file name was written into the journal
56950     ** file before the failure occurred.
56951     */
56952     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
56953       Btree *pBt = db->aDb[i].pBt;
56954       if( pBt ){
56955         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
56956       }
56957     }
56958     sqlite3OsCloseFree(pMaster);
56959     assert( rc!=SQLITE_BUSY );
56960     if( rc!=SQLITE_OK ){
56961       sqlite3DbFree(db, zMaster);
56962       return rc;
56963     }
56964
56965     /* Delete the master journal file. This commits the transaction. After
56966     ** doing this the directory is synced again before any individual
56967     ** transaction files are deleted.
56968     */
56969     rc = sqlite3OsDelete(pVfs, zMaster, 1);
56970     sqlite3DbFree(db, zMaster);
56971     zMaster = 0;
56972     if( rc ){
56973       return rc;
56974     }
56975
56976     /* All files and directories have already been synced, so the following
56977     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
56978     ** deleting or truncating journals. If something goes wrong while
56979     ** this is happening we don't really care. The integrity of the
56980     ** transaction is already guaranteed, but some stray 'cold' journals
56981     ** may be lying around. Returning an error code won't help matters.
56982     */
56983     disable_simulated_io_errors();
56984     sqlite3BeginBenignMalloc();
56985     for(i=0; i<db->nDb; i++){ 
56986       Btree *pBt = db->aDb[i].pBt;
56987       if( pBt ){
56988         sqlite3BtreeCommitPhaseTwo(pBt);
56989       }
56990     }
56991     sqlite3EndBenignMalloc();
56992     enable_simulated_io_errors();
56993
56994     sqlite3VtabCommit(db);
56995   }
56996 #endif
56997
56998   return rc;
56999 }
57000
57001 /* 
57002 ** This routine checks that the sqlite3.activeVdbeCnt count variable
57003 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
57004 ** currently active. An assertion fails if the two counts do not match.
57005 ** This is an internal self-check only - it is not an essential processing
57006 ** step.
57007 **
57008 ** This is a no-op if NDEBUG is defined.
57009 */
57010 #ifndef NDEBUG
57011 static void checkActiveVdbeCnt(sqlite3 *db){
57012   Vdbe *p;
57013   int cnt = 0;
57014   int nWrite = 0;
57015   p = db->pVdbe;
57016   while( p ){
57017     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
57018       cnt++;
57019       if( p->readOnly==0 ) nWrite++;
57020     }
57021     p = p->pNext;
57022   }
57023   assert( cnt==db->activeVdbeCnt );
57024   assert( nWrite==db->writeVdbeCnt );
57025 }
57026 #else
57027 #define checkActiveVdbeCnt(x)
57028 #endif
57029
57030 /*
57031 ** For every Btree that in database connection db which 
57032 ** has been modified, "trip" or invalidate each cursor in
57033 ** that Btree might have been modified so that the cursor
57034 ** can never be used again.  This happens when a rollback
57035 *** occurs.  We have to trip all the other cursors, even
57036 ** cursor from other VMs in different database connections,
57037 ** so that none of them try to use the data at which they
57038 ** were pointing and which now may have been changed due
57039 ** to the rollback.
57040 **
57041 ** Remember that a rollback can delete tables complete and
57042 ** reorder rootpages.  So it is not sufficient just to save
57043 ** the state of the cursor.  We have to invalidate the cursor
57044 ** so that it is never used again.
57045 */
57046 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
57047   int i;
57048   for(i=0; i<db->nDb; i++){
57049     Btree *p = db->aDb[i].pBt;
57050     if( p && sqlite3BtreeIsInTrans(p) ){
57051       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
57052     }
57053   }
57054 }
57055
57056 /*
57057 ** If the Vdbe passed as the first argument opened a statement-transaction,
57058 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
57059 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
57060 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
57061 ** statement transaction is commtted.
57062 **
57063 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
57064 ** Otherwise SQLITE_OK.
57065 */
57066 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
57067   sqlite3 *const db = p->db;
57068   int rc = SQLITE_OK;
57069
57070   /* If p->iStatement is greater than zero, then this Vdbe opened a 
57071   ** statement transaction that should be closed here. The only exception
57072   ** is that an IO error may have occured, causing an emergency rollback.
57073   ** In this case (db->nStatement==0), and there is nothing to do.
57074   */
57075   if( db->nStatement && p->iStatement ){
57076     int i;
57077     const int iSavepoint = p->iStatement-1;
57078
57079     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
57080     assert( db->nStatement>0 );
57081     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
57082
57083     for(i=0; i<db->nDb; i++){ 
57084       int rc2 = SQLITE_OK;
57085       Btree *pBt = db->aDb[i].pBt;
57086       if( pBt ){
57087         if( eOp==SAVEPOINT_ROLLBACK ){
57088           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
57089         }
57090         if( rc2==SQLITE_OK ){
57091           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
57092         }
57093         if( rc==SQLITE_OK ){
57094           rc = rc2;
57095         }
57096       }
57097     }
57098     db->nStatement--;
57099     p->iStatement = 0;
57100
57101     /* If the statement transaction is being rolled back, also restore the 
57102     ** database handles deferred constraint counter to the value it had when 
57103     ** the statement transaction was opened.  */
57104     if( eOp==SAVEPOINT_ROLLBACK ){
57105       db->nDeferredCons = p->nStmtDefCons;
57106     }
57107   }
57108   return rc;
57109 }
57110
57111 /*
57112 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
57113 ** this routine obtains the mutex associated with each BtShared structure
57114 ** that may be accessed by the VM passed as an argument. In doing so it
57115 ** sets the BtShared.db member of each of the BtShared structures, ensuring
57116 ** that the correct busy-handler callback is invoked if required.
57117 **
57118 ** If SQLite is not threadsafe but does support shared-cache mode, then
57119 ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
57120 ** of all of BtShared structures accessible via the database handle 
57121 ** associated with the VM. Of course only a subset of these structures
57122 ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
57123 ** that subset out, but there is no advantage to doing so.
57124 **
57125 ** If SQLite is not threadsafe and does not support shared-cache mode, this
57126 ** function is a no-op.
57127 */
57128 #ifndef SQLITE_OMIT_SHARED_CACHE
57129 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
57130 #if SQLITE_THREADSAFE
57131   sqlite3BtreeMutexArrayEnter(&p->aMutex);
57132 #else
57133   sqlite3BtreeEnterAll(p->db);
57134 #endif
57135 }
57136 #endif
57137
57138 /*
57139 ** This function is called when a transaction opened by the database 
57140 ** handle associated with the VM passed as an argument is about to be 
57141 ** committed. If there are outstanding deferred foreign key constraint
57142 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
57143 **
57144 ** If there are outstanding FK violations and this function returns 
57145 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
57146 ** an error message to it. Then return SQLITE_ERROR.
57147 */
57148 #ifndef SQLITE_OMIT_FOREIGN_KEY
57149 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
57150   sqlite3 *db = p->db;
57151   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
57152     p->rc = SQLITE_CONSTRAINT;
57153     p->errorAction = OE_Abort;
57154     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
57155     return SQLITE_ERROR;
57156   }
57157   return SQLITE_OK;
57158 }
57159 #endif
57160
57161 /*
57162 ** This routine is called the when a VDBE tries to halt.  If the VDBE
57163 ** has made changes and is in autocommit mode, then commit those
57164 ** changes.  If a rollback is needed, then do the rollback.
57165 **
57166 ** This routine is the only way to move the state of a VM from
57167 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
57168 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
57169 **
57170 ** Return an error code.  If the commit could not complete because of
57171 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
57172 ** means the close did not happen and needs to be repeated.
57173 */
57174 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
57175   int rc;                         /* Used to store transient return codes */
57176   sqlite3 *db = p->db;
57177
57178   /* This function contains the logic that determines if a statement or
57179   ** transaction will be committed or rolled back as a result of the
57180   ** execution of this virtual machine. 
57181   **
57182   ** If any of the following errors occur:
57183   **
57184   **     SQLITE_NOMEM
57185   **     SQLITE_IOERR
57186   **     SQLITE_FULL
57187   **     SQLITE_INTERRUPT
57188   **
57189   ** Then the internal cache might have been left in an inconsistent
57190   ** state.  We need to rollback the statement transaction, if there is
57191   ** one, or the complete transaction if there is no statement transaction.
57192   */
57193
57194   if( p->db->mallocFailed ){
57195     p->rc = SQLITE_NOMEM;
57196   }
57197   closeAllCursors(p);
57198   if( p->magic!=VDBE_MAGIC_RUN ){
57199     return SQLITE_OK;
57200   }
57201   checkActiveVdbeCnt(db);
57202
57203   /* No commit or rollback needed if the program never started */
57204   if( p->pc>=0 ){
57205     int mrc;   /* Primary error code from p->rc */
57206     int eStatementOp = 0;
57207     int isSpecialError;            /* Set to true if a 'special' error */
57208
57209     /* Lock all btrees used by the statement */
57210     sqlite3VdbeMutexArrayEnter(p);
57211
57212     /* Check for one of the special errors */
57213     mrc = p->rc & 0xff;
57214     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
57215     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
57216                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
57217     if( isSpecialError ){
57218       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
57219       ** no rollback is necessary. Otherwise, at least a savepoint 
57220       ** transaction must be rolled back to restore the database to a 
57221       ** consistent state.
57222       **
57223       ** Even if the statement is read-only, it is important to perform
57224       ** a statement or transaction rollback operation. If the error 
57225       ** occured while writing to the journal, sub-journal or database
57226       ** file as part of an effort to free up cache space (see function
57227       ** pagerStress() in pager.c), the rollback is required to restore 
57228       ** the pager to a consistent state.
57229       */
57230       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
57231         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
57232           eStatementOp = SAVEPOINT_ROLLBACK;
57233         }else{
57234           /* We are forced to roll back the active transaction. Before doing
57235           ** so, abort any other statements this handle currently has active.
57236           */
57237           invalidateCursorsOnModifiedBtrees(db);
57238           sqlite3RollbackAll(db);
57239           sqlite3CloseSavepoints(db);
57240           db->autoCommit = 1;
57241         }
57242       }
57243     }
57244
57245     /* Check for immediate foreign key violations. */
57246     if( p->rc==SQLITE_OK ){
57247       sqlite3VdbeCheckFk(p, 0);
57248     }
57249   
57250     /* If the auto-commit flag is set and this is the only active writer 
57251     ** VM, then we do either a commit or rollback of the current transaction. 
57252     **
57253     ** Note: This block also runs if one of the special errors handled 
57254     ** above has occurred. 
57255     */
57256     if( !sqlite3VtabInSync(db) 
57257      && db->autoCommit 
57258      && db->writeVdbeCnt==(p->readOnly==0) 
57259     ){
57260       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
57261         if( sqlite3VdbeCheckFk(p, 1) ){
57262           sqlite3BtreeMutexArrayLeave(&p->aMutex);
57263           return SQLITE_ERROR;
57264         }
57265         /* The auto-commit flag is true, the vdbe program was successful 
57266         ** or hit an 'OR FAIL' constraint and there are no deferred foreign
57267         ** key constraints to hold up the transaction. This means a commit 
57268         ** is required.  */
57269         rc = vdbeCommit(db, p);
57270         if( rc==SQLITE_BUSY ){
57271           sqlite3BtreeMutexArrayLeave(&p->aMutex);
57272           return SQLITE_BUSY;
57273         }else if( rc!=SQLITE_OK ){
57274           p->rc = rc;
57275           sqlite3RollbackAll(db);
57276         }else{
57277           db->nDeferredCons = 0;
57278           sqlite3CommitInternalChanges(db);
57279         }
57280       }else{
57281         sqlite3RollbackAll(db);
57282       }
57283       db->nStatement = 0;
57284     }else if( eStatementOp==0 ){
57285       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
57286         eStatementOp = SAVEPOINT_RELEASE;
57287       }else if( p->errorAction==OE_Abort ){
57288         eStatementOp = SAVEPOINT_ROLLBACK;
57289       }else{
57290         invalidateCursorsOnModifiedBtrees(db);
57291         sqlite3RollbackAll(db);
57292         sqlite3CloseSavepoints(db);
57293         db->autoCommit = 1;
57294       }
57295     }
57296   
57297     /* If eStatementOp is non-zero, then a statement transaction needs to
57298     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
57299     ** do so. If this operation returns an error, and the current statement
57300     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
57301     ** current statement error code.
57302     **
57303     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
57304     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
57305     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in 
57306     ** the following code.
57307     */
57308     if( eStatementOp ){
57309       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
57310       if( rc ){
57311         assert( eStatementOp==SAVEPOINT_ROLLBACK );
57312         if( NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT ){
57313           p->rc = rc;
57314           sqlite3DbFree(db, p->zErrMsg);
57315           p->zErrMsg = 0;
57316         }
57317         invalidateCursorsOnModifiedBtrees(db);
57318         sqlite3RollbackAll(db);
57319         sqlite3CloseSavepoints(db);
57320         db->autoCommit = 1;
57321       }
57322     }
57323   
57324     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
57325     ** has been rolled back, update the database connection change-counter. 
57326     */
57327     if( p->changeCntOn ){
57328       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
57329         sqlite3VdbeSetChanges(db, p->nChange);
57330       }else{
57331         sqlite3VdbeSetChanges(db, 0);
57332       }
57333       p->nChange = 0;
57334     }
57335   
57336     /* Rollback or commit any schema changes that occurred. */
57337     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
57338       sqlite3ResetInternalSchema(db, 0);
57339       db->flags = (db->flags | SQLITE_InternChanges);
57340     }
57341
57342     /* Release the locks */
57343     sqlite3BtreeMutexArrayLeave(&p->aMutex);
57344   }
57345
57346   /* We have successfully halted and closed the VM.  Record this fact. */
57347   if( p->pc>=0 ){
57348     db->activeVdbeCnt--;
57349     if( !p->readOnly ){
57350       db->writeVdbeCnt--;
57351     }
57352     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
57353   }
57354   p->magic = VDBE_MAGIC_HALT;
57355   checkActiveVdbeCnt(db);
57356   if( p->db->mallocFailed ){
57357     p->rc = SQLITE_NOMEM;
57358   }
57359
57360   /* If the auto-commit flag is set to true, then any locks that were held
57361   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
57362   ** to invoke any required unlock-notify callbacks.
57363   */
57364   if( db->autoCommit ){
57365     sqlite3ConnectionUnlocked(db);
57366   }
57367
57368   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
57369   return SQLITE_OK;
57370 }
57371
57372
57373 /*
57374 ** Each VDBE holds the result of the most recent sqlite3_step() call
57375 ** in p->rc.  This routine sets that result back to SQLITE_OK.
57376 */
57377 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
57378   p->rc = SQLITE_OK;
57379 }
57380
57381 /*
57382 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
57383 ** Write any error messages into *pzErrMsg.  Return the result code.
57384 **
57385 ** After this routine is run, the VDBE should be ready to be executed
57386 ** again.
57387 **
57388 ** To look at it another way, this routine resets the state of the
57389 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
57390 ** VDBE_MAGIC_INIT.
57391 */
57392 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
57393   sqlite3 *db;
57394   db = p->db;
57395
57396   /* If the VM did not run to completion or if it encountered an
57397   ** error, then it might not have been halted properly.  So halt
57398   ** it now.
57399   */
57400   sqlite3VdbeHalt(p);
57401
57402   /* If the VDBE has be run even partially, then transfer the error code
57403   ** and error message from the VDBE into the main database structure.  But
57404   ** if the VDBE has just been set to run but has not actually executed any
57405   ** instructions yet, leave the main database error information unchanged.
57406   */
57407   if( p->pc>=0 ){
57408     if( p->zErrMsg ){
57409       sqlite3BeginBenignMalloc();
57410       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
57411       sqlite3EndBenignMalloc();
57412       db->errCode = p->rc;
57413       sqlite3DbFree(db, p->zErrMsg);
57414       p->zErrMsg = 0;
57415     }else if( p->rc ){
57416       sqlite3Error(db, p->rc, 0);
57417     }else{
57418       sqlite3Error(db, SQLITE_OK, 0);
57419     }
57420     if( p->runOnlyOnce ) p->expired = 1;
57421   }else if( p->rc && p->expired ){
57422     /* The expired flag was set on the VDBE before the first call
57423     ** to sqlite3_step(). For consistency (since sqlite3_step() was
57424     ** called), set the database error in this case as well.
57425     */
57426     sqlite3Error(db, p->rc, 0);
57427     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
57428     sqlite3DbFree(db, p->zErrMsg);
57429     p->zErrMsg = 0;
57430   }
57431
57432   /* Reclaim all memory used by the VDBE
57433   */
57434   Cleanup(p);
57435
57436   /* Save profiling information from this VDBE run.
57437   */
57438 #ifdef VDBE_PROFILE
57439   {
57440     FILE *out = fopen("vdbe_profile.out", "a");
57441     if( out ){
57442       int i;
57443       fprintf(out, "---- ");
57444       for(i=0; i<p->nOp; i++){
57445         fprintf(out, "%02x", p->aOp[i].opcode);
57446       }
57447       fprintf(out, "\n");
57448       for(i=0; i<p->nOp; i++){
57449         fprintf(out, "%6d %10lld %8lld ",
57450            p->aOp[i].cnt,
57451            p->aOp[i].cycles,
57452            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
57453         );
57454         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
57455       }
57456       fclose(out);
57457     }
57458   }
57459 #endif
57460   p->magic = VDBE_MAGIC_INIT;
57461   return p->rc & db->errMask;
57462 }
57463  
57464 /*
57465 ** Clean up and delete a VDBE after execution.  Return an integer which is
57466 ** the result code.  Write any error message text into *pzErrMsg.
57467 */
57468 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
57469   int rc = SQLITE_OK;
57470   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
57471     rc = sqlite3VdbeReset(p);
57472     assert( (rc & p->db->errMask)==rc );
57473   }
57474   sqlite3VdbeDelete(p);
57475   return rc;
57476 }
57477
57478 /*
57479 ** Call the destructor for each auxdata entry in pVdbeFunc for which
57480 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
57481 ** are always destroyed.  To destroy all auxdata entries, call this
57482 ** routine with mask==0.
57483 */
57484 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
57485   int i;
57486   for(i=0; i<pVdbeFunc->nAux; i++){
57487     struct AuxData *pAux = &pVdbeFunc->apAux[i];
57488     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
57489       if( pAux->xDelete ){
57490         pAux->xDelete(pAux->pAux);
57491       }
57492       pAux->pAux = 0;
57493     }
57494   }
57495 }
57496
57497 /*
57498 ** Free all memory associated with the Vdbe passed as the second argument.
57499 ** The difference between this function and sqlite3VdbeDelete() is that
57500 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
57501 ** the database connection.
57502 */
57503 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
57504   SubProgram *pSub, *pNext;
57505   assert( p->db==0 || p->db==db );
57506   releaseMemArray(p->aVar, p->nVar);
57507   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
57508   for(pSub=p->pProgram; pSub; pSub=pNext){
57509     pNext = pSub->pNext;
57510     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
57511     sqlite3DbFree(db, pSub);
57512   }
57513   vdbeFreeOpArray(db, p->aOp, p->nOp);
57514   sqlite3DbFree(db, p->aLabel);
57515   sqlite3DbFree(db, p->aColName);
57516   sqlite3DbFree(db, p->zSql);
57517   sqlite3DbFree(db, p->pFree);
57518   sqlite3DbFree(db, p);
57519 }
57520
57521 /*
57522 ** Delete an entire VDBE.
57523 */
57524 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
57525   sqlite3 *db;
57526
57527   if( NEVER(p==0) ) return;
57528   db = p->db;
57529   if( p->pPrev ){
57530     p->pPrev->pNext = p->pNext;
57531   }else{
57532     assert( db->pVdbe==p );
57533     db->pVdbe = p->pNext;
57534   }
57535   if( p->pNext ){
57536     p->pNext->pPrev = p->pPrev;
57537   }
57538   p->magic = VDBE_MAGIC_DEAD;
57539   p->db = 0;
57540   sqlite3VdbeDeleteObject(db, p);
57541 }
57542
57543 /*
57544 ** Make sure the cursor p is ready to read or write the row to which it
57545 ** was last positioned.  Return an error code if an OOM fault or I/O error
57546 ** prevents us from positioning the cursor to its correct position.
57547 **
57548 ** If a MoveTo operation is pending on the given cursor, then do that
57549 ** MoveTo now.  If no move is pending, check to see if the row has been
57550 ** deleted out from under the cursor and if it has, mark the row as
57551 ** a NULL row.
57552 **
57553 ** If the cursor is already pointing to the correct row and that row has
57554 ** not been deleted out from under the cursor, then this routine is a no-op.
57555 */
57556 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
57557   if( p->deferredMoveto ){
57558     int res, rc;
57559 #ifdef SQLITE_TEST
57560     extern int sqlite3_search_count;
57561 #endif
57562     assert( p->isTable );
57563     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
57564     if( rc ) return rc;
57565     p->lastRowid = p->movetoTarget;
57566     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
57567     p->rowidIsValid = 1;
57568 #ifdef SQLITE_TEST
57569     sqlite3_search_count++;
57570 #endif
57571     p->deferredMoveto = 0;
57572     p->cacheStatus = CACHE_STALE;
57573   }else if( ALWAYS(p->pCursor) ){
57574     int hasMoved;
57575     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
57576     if( rc ) return rc;
57577     if( hasMoved ){
57578       p->cacheStatus = CACHE_STALE;
57579       p->nullRow = 1;
57580     }
57581   }
57582   return SQLITE_OK;
57583 }
57584
57585 /*
57586 ** The following functions:
57587 **
57588 ** sqlite3VdbeSerialType()
57589 ** sqlite3VdbeSerialTypeLen()
57590 ** sqlite3VdbeSerialLen()
57591 ** sqlite3VdbeSerialPut()
57592 ** sqlite3VdbeSerialGet()
57593 **
57594 ** encapsulate the code that serializes values for storage in SQLite
57595 ** data and index records. Each serialized value consists of a
57596 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
57597 ** integer, stored as a varint.
57598 **
57599 ** In an SQLite index record, the serial type is stored directly before
57600 ** the blob of data that it corresponds to. In a table record, all serial
57601 ** types are stored at the start of the record, and the blobs of data at
57602 ** the end. Hence these functions allow the caller to handle the
57603 ** serial-type and data blob seperately.
57604 **
57605 ** The following table describes the various storage classes for data:
57606 **
57607 **   serial type        bytes of data      type
57608 **   --------------     ---------------    ---------------
57609 **      0                     0            NULL
57610 **      1                     1            signed integer
57611 **      2                     2            signed integer
57612 **      3                     3            signed integer
57613 **      4                     4            signed integer
57614 **      5                     6            signed integer
57615 **      6                     8            signed integer
57616 **      7                     8            IEEE float
57617 **      8                     0            Integer constant 0
57618 **      9                     0            Integer constant 1
57619 **     10,11                               reserved for expansion
57620 **    N>=12 and even       (N-12)/2        BLOB
57621 **    N>=13 and odd        (N-13)/2        text
57622 **
57623 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
57624 ** of SQLite will not understand those serial types.
57625 */
57626
57627 /*
57628 ** Return the serial-type for the value stored in pMem.
57629 */
57630 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
57631   int flags = pMem->flags;
57632   int n;
57633
57634   if( flags&MEM_Null ){
57635     return 0;
57636   }
57637   if( flags&MEM_Int ){
57638     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
57639 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
57640     i64 i = pMem->u.i;
57641     u64 u;
57642     if( file_format>=4 && (i&1)==i ){
57643       return 8+(u32)i;
57644     }
57645     u = i<0 ? -i : i;
57646     if( u<=127 ) return 1;
57647     if( u<=32767 ) return 2;
57648     if( u<=8388607 ) return 3;
57649     if( u<=2147483647 ) return 4;
57650     if( u<=MAX_6BYTE ) return 5;
57651     return 6;
57652   }
57653   if( flags&MEM_Real ){
57654     return 7;
57655   }
57656   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
57657   n = pMem->n;
57658   if( flags & MEM_Zero ){
57659     n += pMem->u.nZero;
57660   }
57661   assert( n>=0 );
57662   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
57663 }
57664
57665 /*
57666 ** Return the length of the data corresponding to the supplied serial-type.
57667 */
57668 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
57669   if( serial_type>=12 ){
57670     return (serial_type-12)/2;
57671   }else{
57672     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
57673     return aSize[serial_type];
57674   }
57675 }
57676
57677 /*
57678 ** If we are on an architecture with mixed-endian floating 
57679 ** points (ex: ARM7) then swap the lower 4 bytes with the 
57680 ** upper 4 bytes.  Return the result.
57681 **
57682 ** For most architectures, this is a no-op.
57683 **
57684 ** (later):  It is reported to me that the mixed-endian problem
57685 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
57686 ** that early versions of GCC stored the two words of a 64-bit
57687 ** float in the wrong order.  And that error has been propagated
57688 ** ever since.  The blame is not necessarily with GCC, though.
57689 ** GCC might have just copying the problem from a prior compiler.
57690 ** I am also told that newer versions of GCC that follow a different
57691 ** ABI get the byte order right.
57692 **
57693 ** Developers using SQLite on an ARM7 should compile and run their
57694 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
57695 ** enabled, some asserts below will ensure that the byte order of
57696 ** floating point values is correct.
57697 **
57698 ** (2007-08-30)  Frank van Vugt has studied this problem closely
57699 ** and has send his findings to the SQLite developers.  Frank
57700 ** writes that some Linux kernels offer floating point hardware
57701 ** emulation that uses only 32-bit mantissas instead of a full 
57702 ** 48-bits as required by the IEEE standard.  (This is the
57703 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
57704 ** byte swapping becomes very complicated.  To avoid problems,
57705 ** the necessary byte swapping is carried out using a 64-bit integer
57706 ** rather than a 64-bit float.  Frank assures us that the code here
57707 ** works for him.  We, the developers, have no way to independently
57708 ** verify this, but Frank seems to know what he is talking about
57709 ** so we trust him.
57710 */
57711 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
57712 static u64 floatSwap(u64 in){
57713   union {
57714     u64 r;
57715     u32 i[2];
57716   } u;
57717   u32 t;
57718
57719   u.r = in;
57720   t = u.i[0];
57721   u.i[0] = u.i[1];
57722   u.i[1] = t;
57723   return u.r;
57724 }
57725 # define swapMixedEndianFloat(X)  X = floatSwap(X)
57726 #else
57727 # define swapMixedEndianFloat(X)
57728 #endif
57729
57730 /*
57731 ** Write the serialized data blob for the value stored in pMem into 
57732 ** buf. It is assumed that the caller has allocated sufficient space.
57733 ** Return the number of bytes written.
57734 **
57735 ** nBuf is the amount of space left in buf[].  nBuf must always be
57736 ** large enough to hold the entire field.  Except, if the field is
57737 ** a blob with a zero-filled tail, then buf[] might be just the right
57738 ** size to hold everything except for the zero-filled tail.  If buf[]
57739 ** is only big enough to hold the non-zero prefix, then only write that
57740 ** prefix into buf[].  But if buf[] is large enough to hold both the
57741 ** prefix and the tail then write the prefix and set the tail to all
57742 ** zeros.
57743 **
57744 ** Return the number of bytes actually written into buf[].  The number
57745 ** of bytes in the zero-filled tail is included in the return value only
57746 ** if those bytes were zeroed in buf[].
57747 */ 
57748 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
57749   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
57750   u32 len;
57751
57752   /* Integer and Real */
57753   if( serial_type<=7 && serial_type>0 ){
57754     u64 v;
57755     u32 i;
57756     if( serial_type==7 ){
57757       assert( sizeof(v)==sizeof(pMem->r) );
57758       memcpy(&v, &pMem->r, sizeof(v));
57759       swapMixedEndianFloat(v);
57760     }else{
57761       v = pMem->u.i;
57762     }
57763     len = i = sqlite3VdbeSerialTypeLen(serial_type);
57764     assert( len<=(u32)nBuf );
57765     while( i-- ){
57766       buf[i] = (u8)(v&0xFF);
57767       v >>= 8;
57768     }
57769     return len;
57770   }
57771
57772   /* String or blob */
57773   if( serial_type>=12 ){
57774     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
57775              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
57776     assert( pMem->n<=nBuf );
57777     len = pMem->n;
57778     memcpy(buf, pMem->z, len);
57779     if( pMem->flags & MEM_Zero ){
57780       len += pMem->u.nZero;
57781       assert( nBuf>=0 );
57782       if( len > (u32)nBuf ){
57783         len = (u32)nBuf;
57784       }
57785       memset(&buf[pMem->n], 0, len-pMem->n);
57786     }
57787     return len;
57788   }
57789
57790   /* NULL or constants 0 or 1 */
57791   return 0;
57792 }
57793
57794 /*
57795 ** Deserialize the data blob pointed to by buf as serial type serial_type
57796 ** and store the result in pMem.  Return the number of bytes read.
57797 */ 
57798 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
57799   const unsigned char *buf,     /* Buffer to deserialize from */
57800   u32 serial_type,              /* Serial type to deserialize */
57801   Mem *pMem                     /* Memory cell to write value into */
57802 ){
57803   switch( serial_type ){
57804     case 10:   /* Reserved for future use */
57805     case 11:   /* Reserved for future use */
57806     case 0: {  /* NULL */
57807       pMem->flags = MEM_Null;
57808       break;
57809     }
57810     case 1: { /* 1-byte signed integer */
57811       pMem->u.i = (signed char)buf[0];
57812       pMem->flags = MEM_Int;
57813       return 1;
57814     }
57815     case 2: { /* 2-byte signed integer */
57816       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
57817       pMem->flags = MEM_Int;
57818       return 2;
57819     }
57820     case 3: { /* 3-byte signed integer */
57821       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
57822       pMem->flags = MEM_Int;
57823       return 3;
57824     }
57825     case 4: { /* 4-byte signed integer */
57826       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
57827       pMem->flags = MEM_Int;
57828       return 4;
57829     }
57830     case 5: { /* 6-byte signed integer */
57831       u64 x = (((signed char)buf[0])<<8) | buf[1];
57832       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
57833       x = (x<<32) | y;
57834       pMem->u.i = *(i64*)&x;
57835       pMem->flags = MEM_Int;
57836       return 6;
57837     }
57838     case 6:   /* 8-byte signed integer */
57839     case 7: { /* IEEE floating point */
57840       u64 x;
57841       u32 y;
57842 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
57843       /* Verify that integers and floating point values use the same
57844       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
57845       ** defined that 64-bit floating point values really are mixed
57846       ** endian.
57847       */
57848       static const u64 t1 = ((u64)0x3ff00000)<<32;
57849       static const double r1 = 1.0;
57850       u64 t2 = t1;
57851       swapMixedEndianFloat(t2);
57852       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
57853 #endif
57854
57855       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
57856       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
57857       x = (x<<32) | y;
57858       if( serial_type==6 ){
57859         pMem->u.i = *(i64*)&x;
57860         pMem->flags = MEM_Int;
57861       }else{
57862         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
57863         swapMixedEndianFloat(x);
57864         memcpy(&pMem->r, &x, sizeof(x));
57865         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
57866       }
57867       return 8;
57868     }
57869     case 8:    /* Integer 0 */
57870     case 9: {  /* Integer 1 */
57871       pMem->u.i = serial_type-8;
57872       pMem->flags = MEM_Int;
57873       return 0;
57874     }
57875     default: {
57876       u32 len = (serial_type-12)/2;
57877       pMem->z = (char *)buf;
57878       pMem->n = len;
57879       pMem->xDel = 0;
57880       if( serial_type&0x01 ){
57881         pMem->flags = MEM_Str | MEM_Ephem;
57882       }else{
57883         pMem->flags = MEM_Blob | MEM_Ephem;
57884       }
57885       return len;
57886     }
57887   }
57888   return 0;
57889 }
57890
57891
57892 /*
57893 ** Given the nKey-byte encoding of a record in pKey[], parse the
57894 ** record into a UnpackedRecord structure.  Return a pointer to
57895 ** that structure.
57896 **
57897 ** The calling function might provide szSpace bytes of memory
57898 ** space at pSpace.  This space can be used to hold the returned
57899 ** VDbeParsedRecord structure if it is large enough.  If it is
57900 ** not big enough, space is obtained from sqlite3_malloc().
57901 **
57902 ** The returned structure should be closed by a call to
57903 ** sqlite3VdbeDeleteUnpackedRecord().
57904 */ 
57905 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
57906   KeyInfo *pKeyInfo,     /* Information about the record format */
57907   int nKey,              /* Size of the binary record */
57908   const void *pKey,      /* The binary record */
57909   char *pSpace,          /* Unaligned space available to hold the object */
57910   int szSpace            /* Size of pSpace[] in bytes */
57911 ){
57912   const unsigned char *aKey = (const unsigned char *)pKey;
57913   UnpackedRecord *p;  /* The unpacked record that we will return */
57914   int nByte;          /* Memory space needed to hold p, in bytes */
57915   int d;
57916   u32 idx;
57917   u16 u;              /* Unsigned loop counter */
57918   u32 szHdr;
57919   Mem *pMem;
57920   int nOff;           /* Increase pSpace by this much to 8-byte align it */
57921   
57922   /*
57923   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
57924   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
57925   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
57926   */
57927   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
57928   pSpace += nOff;
57929   szSpace -= nOff;
57930   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
57931   if( nByte>szSpace ){
57932     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
57933     if( p==0 ) return 0;
57934     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
57935   }else{
57936     p = (UnpackedRecord*)pSpace;
57937     p->flags = UNPACKED_NEED_DESTROY;
57938   }
57939   p->pKeyInfo = pKeyInfo;
57940   p->nField = pKeyInfo->nField + 1;
57941   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
57942   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57943   idx = getVarint32(aKey, szHdr);
57944   d = szHdr;
57945   u = 0;
57946   while( idx<szHdr && u<p->nField && d<=nKey ){
57947     u32 serial_type;
57948
57949     idx += getVarint32(&aKey[idx], serial_type);
57950     pMem->enc = pKeyInfo->enc;
57951     pMem->db = pKeyInfo->db;
57952     pMem->flags = 0;
57953     pMem->zMalloc = 0;
57954     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
57955     pMem++;
57956     u++;
57957   }
57958   assert( u<=pKeyInfo->nField + 1 );
57959   p->nField = u;
57960   return (void*)p;
57961 }
57962
57963 /*
57964 ** This routine destroys a UnpackedRecord object.
57965 */
57966 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
57967   int i;
57968   Mem *pMem;
57969
57970   assert( p!=0 );
57971   assert( p->flags & UNPACKED_NEED_DESTROY );
57972   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
57973     /* The unpacked record is always constructed by the
57974     ** sqlite3VdbeUnpackRecord() function above, which makes all
57975     ** strings and blobs static.  And none of the elements are
57976     ** ever transformed, so there is never anything to delete.
57977     */
57978     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
57979   }
57980   if( p->flags & UNPACKED_NEED_FREE ){
57981     sqlite3DbFree(p->pKeyInfo->db, p);
57982   }
57983 }
57984
57985 /*
57986 ** This function compares the two table rows or index records
57987 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
57988 ** or positive integer if key1 is less than, equal to or 
57989 ** greater than key2.  The {nKey1, pKey1} key must be a blob
57990 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
57991 ** key must be a parsed key such as obtained from
57992 ** sqlite3VdbeParseRecord.
57993 **
57994 ** Key1 and Key2 do not have to contain the same number of fields.
57995 ** The key with fewer fields is usually compares less than the 
57996 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
57997 ** and the common prefixes are equal, then key1 is less than key2.
57998 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
57999 ** equal, then the keys are considered to be equal and
58000 ** the parts beyond the common prefix are ignored.
58001 **
58002 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
58003 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
58004 ** an index key, and thus ends with a rowid value.  The last byte
58005 ** of the header will therefore be the serial type of the rowid:
58006 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
58007 ** The serial type of the final rowid will always be a single byte.
58008 ** By ignoring this last byte of the header, we force the comparison
58009 ** to ignore the rowid at the end of key1.
58010 */
58011 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
58012   int nKey1, const void *pKey1, /* Left key */
58013   UnpackedRecord *pPKey2        /* Right key */
58014 ){
58015   int d1;            /* Offset into aKey[] of next data element */
58016   u32 idx1;          /* Offset into aKey[] of next header element */
58017   u32 szHdr1;        /* Number of bytes in header */
58018   int i = 0;
58019   int nField;
58020   int rc = 0;
58021   const unsigned char *aKey1 = (const unsigned char *)pKey1;
58022   KeyInfo *pKeyInfo;
58023   Mem mem1;
58024
58025   pKeyInfo = pPKey2->pKeyInfo;
58026   mem1.enc = pKeyInfo->enc;
58027   mem1.db = pKeyInfo->db;
58028   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
58029   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
58030
58031   /* Compilers may complain that mem1.u.i is potentially uninitialized.
58032   ** We could initialize it, as shown here, to silence those complaints.
58033   ** But in fact, mem1.u.i will never actually be used initialized, and doing 
58034   ** the unnecessary initialization has a measurable negative performance
58035   ** impact, since this routine is a very high runner.  And so, we choose
58036   ** to ignore the compiler warnings and leave this variable uninitialized.
58037   */
58038   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
58039   
58040   idx1 = getVarint32(aKey1, szHdr1);
58041   d1 = szHdr1;
58042   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
58043     szHdr1--;
58044   }
58045   nField = pKeyInfo->nField;
58046   while( idx1<szHdr1 && i<pPKey2->nField ){
58047     u32 serial_type1;
58048
58049     /* Read the serial types for the next element in each key. */
58050     idx1 += getVarint32( aKey1+idx1, serial_type1 );
58051     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
58052
58053     /* Extract the values to be compared.
58054     */
58055     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
58056
58057     /* Do the comparison
58058     */
58059     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
58060                            i<nField ? pKeyInfo->aColl[i] : 0);
58061     if( rc!=0 ){
58062       assert( mem1.zMalloc==0 );  /* See comment below */
58063
58064       /* Invert the result if we are using DESC sort order. */
58065       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
58066         rc = -rc;
58067       }
58068     
58069       /* If the PREFIX_SEARCH flag is set and all fields except the final
58070       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
58071       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
58072       ** This is used by the OP_IsUnique opcode.
58073       */
58074       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
58075         assert( idx1==szHdr1 && rc );
58076         assert( mem1.flags & MEM_Int );
58077         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
58078         pPKey2->rowid = mem1.u.i;
58079       }
58080     
58081       return rc;
58082     }
58083     i++;
58084   }
58085
58086   /* No memory allocation is ever used on mem1.  Prove this using
58087   ** the following assert().  If the assert() fails, it indicates a
58088   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
58089   */
58090   assert( mem1.zMalloc==0 );
58091
58092   /* rc==0 here means that one of the keys ran out of fields and
58093   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
58094   ** flag is set, then break the tie by treating key2 as larger.
58095   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
58096   ** are considered to be equal.  Otherwise, the longer key is the 
58097   ** larger.  As it happens, the pPKey2 will always be the longer
58098   ** if there is a difference.
58099   */
58100   assert( rc==0 );
58101   if( pPKey2->flags & UNPACKED_INCRKEY ){
58102     rc = -1;
58103   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
58104     /* Leave rc==0 */
58105   }else if( idx1<szHdr1 ){
58106     rc = 1;
58107   }
58108   return rc;
58109 }
58110  
58111
58112 /*
58113 ** pCur points at an index entry created using the OP_MakeRecord opcode.
58114 ** Read the rowid (the last field in the record) and store it in *rowid.
58115 ** Return SQLITE_OK if everything works, or an error code otherwise.
58116 **
58117 ** pCur might be pointing to text obtained from a corrupt database file.
58118 ** So the content cannot be trusted.  Do appropriate checks on the content.
58119 */
58120 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
58121   i64 nCellKey = 0;
58122   int rc;
58123   u32 szHdr;        /* Size of the header */
58124   u32 typeRowid;    /* Serial type of the rowid */
58125   u32 lenRowid;     /* Size of the rowid */
58126   Mem m, v;
58127
58128   UNUSED_PARAMETER(db);
58129
58130   /* Get the size of the index entry.  Only indices entries of less
58131   ** than 2GiB are support - anything large must be database corruption.
58132   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
58133   ** this code can safely assume that nCellKey is 32-bits  
58134   */
58135   assert( sqlite3BtreeCursorIsValid(pCur) );
58136   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
58137   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
58138   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
58139
58140   /* Read in the complete content of the index entry */
58141   memset(&m, 0, sizeof(m));
58142   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
58143   if( rc ){
58144     return rc;
58145   }
58146
58147   /* The index entry must begin with a header size */
58148   (void)getVarint32((u8*)m.z, szHdr);
58149   testcase( szHdr==3 );
58150   testcase( szHdr==m.n );
58151   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
58152     goto idx_rowid_corruption;
58153   }
58154
58155   /* The last field of the index should be an integer - the ROWID.
58156   ** Verify that the last entry really is an integer. */
58157   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
58158   testcase( typeRowid==1 );
58159   testcase( typeRowid==2 );
58160   testcase( typeRowid==3 );
58161   testcase( typeRowid==4 );
58162   testcase( typeRowid==5 );
58163   testcase( typeRowid==6 );
58164   testcase( typeRowid==8 );
58165   testcase( typeRowid==9 );
58166   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
58167     goto idx_rowid_corruption;
58168   }
58169   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
58170   testcase( (u32)m.n==szHdr+lenRowid );
58171   if( unlikely((u32)m.n<szHdr+lenRowid) ){
58172     goto idx_rowid_corruption;
58173   }
58174
58175   /* Fetch the integer off the end of the index record */
58176   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
58177   *rowid = v.u.i;
58178   sqlite3VdbeMemRelease(&m);
58179   return SQLITE_OK;
58180
58181   /* Jump here if database corruption is detected after m has been
58182   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
58183 idx_rowid_corruption:
58184   testcase( m.zMalloc!=0 );
58185   sqlite3VdbeMemRelease(&m);
58186   return SQLITE_CORRUPT_BKPT;
58187 }
58188
58189 /*
58190 ** Compare the key of the index entry that cursor pC is pointing to against
58191 ** the key string in pUnpacked.  Write into *pRes a number
58192 ** that is negative, zero, or positive if pC is less than, equal to,
58193 ** or greater than pUnpacked.  Return SQLITE_OK on success.
58194 **
58195 ** pUnpacked is either created without a rowid or is truncated so that it
58196 ** omits the rowid at the end.  The rowid at the end of the index entry
58197 ** is ignored as well.  Hence, this routine only compares the prefixes 
58198 ** of the keys prior to the final rowid, not the entire key.
58199 */
58200 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
58201   VdbeCursor *pC,             /* The cursor to compare against */
58202   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
58203   int *res                    /* Write the comparison result here */
58204 ){
58205   i64 nCellKey = 0;
58206   int rc;
58207   BtCursor *pCur = pC->pCursor;
58208   Mem m;
58209
58210   assert( sqlite3BtreeCursorIsValid(pCur) );
58211   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
58212   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
58213   /* nCellKey will always be between 0 and 0xffffffff because of the say
58214   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
58215   if( nCellKey<=0 || nCellKey>0x7fffffff ){
58216     *res = 0;
58217     return SQLITE_CORRUPT_BKPT;
58218   }
58219   memset(&m, 0, sizeof(m));
58220   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
58221   if( rc ){
58222     return rc;
58223   }
58224   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
58225   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
58226   sqlite3VdbeMemRelease(&m);
58227   return SQLITE_OK;
58228 }
58229
58230 /*
58231 ** This routine sets the value to be returned by subsequent calls to
58232 ** sqlite3_changes() on the database handle 'db'. 
58233 */
58234 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
58235   assert( sqlite3_mutex_held(db->mutex) );
58236   db->nChange = nChange;
58237   db->nTotalChange += nChange;
58238 }
58239
58240 /*
58241 ** Set a flag in the vdbe to update the change counter when it is finalised
58242 ** or reset.
58243 */
58244 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
58245   v->changeCntOn = 1;
58246 }
58247
58248 /*
58249 ** Mark every prepared statement associated with a database connection
58250 ** as expired.
58251 **
58252 ** An expired statement means that recompilation of the statement is
58253 ** recommend.  Statements expire when things happen that make their
58254 ** programs obsolete.  Removing user-defined functions or collating
58255 ** sequences, or changing an authorization function are the types of
58256 ** things that make prepared statements obsolete.
58257 */
58258 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
58259   Vdbe *p;
58260   for(p = db->pVdbe; p; p=p->pNext){
58261     p->expired = 1;
58262   }
58263 }
58264
58265 /*
58266 ** Return the database associated with the Vdbe.
58267 */
58268 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
58269   return v->db;
58270 }
58271
58272 /*
58273 ** Return a pointer to an sqlite3_value structure containing the value bound
58274 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
58275 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
58276 ** constants) to the value before returning it.
58277 **
58278 ** The returned value must be freed by the caller using sqlite3ValueFree().
58279 */
58280 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
58281   assert( iVar>0 );
58282   if( v ){
58283     Mem *pMem = &v->aVar[iVar-1];
58284     if( 0==(pMem->flags & MEM_Null) ){
58285       sqlite3_value *pRet = sqlite3ValueNew(v->db);
58286       if( pRet ){
58287         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
58288         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
58289         sqlite3VdbeMemStoreType((Mem *)pRet);
58290       }
58291       return pRet;
58292     }
58293   }
58294   return 0;
58295 }
58296
58297 /*
58298 ** Configure SQL variable iVar so that binding a new value to it signals
58299 ** to sqlite3_reoptimize() that re-preparing the statement may result
58300 ** in a better query plan.
58301 */
58302 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
58303   assert( iVar>0 );
58304   if( iVar>32 ){
58305     v->expmask = 0xffffffff;
58306   }else{
58307     v->expmask |= ((u32)1 << (iVar-1));
58308   }
58309 }
58310
58311 /************** End of vdbeaux.c *********************************************/
58312 /************** Begin file vdbeapi.c *****************************************/
58313 /*
58314 ** 2004 May 26
58315 **
58316 ** The author disclaims copyright to this source code.  In place of
58317 ** a legal notice, here is a blessing:
58318 **
58319 **    May you do good and not evil.
58320 **    May you find forgiveness for yourself and forgive others.
58321 **    May you share freely, never taking more than you give.
58322 **
58323 *************************************************************************
58324 **
58325 ** This file contains code use to implement APIs that are part of the
58326 ** VDBE.
58327 */
58328
58329 #ifndef SQLITE_OMIT_DEPRECATED
58330 /*
58331 ** Return TRUE (non-zero) of the statement supplied as an argument needs
58332 ** to be recompiled.  A statement needs to be recompiled whenever the
58333 ** execution environment changes in a way that would alter the program
58334 ** that sqlite3_prepare() generates.  For example, if new functions or
58335 ** collating sequences are registered or if an authorizer function is
58336 ** added or changed.
58337 */
58338 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
58339   Vdbe *p = (Vdbe*)pStmt;
58340   return p==0 || p->expired;
58341 }
58342 #endif
58343
58344 /*
58345 ** Check on a Vdbe to make sure it has not been finalized.  Log
58346 ** an error and return true if it has been finalized (or is otherwise
58347 ** invalid).  Return false if it is ok.
58348 */
58349 static int vdbeSafety(Vdbe *p){
58350   if( p->db==0 ){
58351     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
58352     return 1;
58353   }else{
58354     return 0;
58355   }
58356 }
58357 static int vdbeSafetyNotNull(Vdbe *p){
58358   if( p==0 ){
58359     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
58360     return 1;
58361   }else{
58362     return vdbeSafety(p);
58363   }
58364 }
58365
58366 /*
58367 ** The following routine destroys a virtual machine that is created by
58368 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
58369 ** success/failure code that describes the result of executing the virtual
58370 ** machine.
58371 **
58372 ** This routine sets the error code and string returned by
58373 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
58374 */
58375 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
58376   int rc;
58377   if( pStmt==0 ){
58378     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
58379     ** pointer is a harmless no-op. */
58380     rc = SQLITE_OK;
58381   }else{
58382     Vdbe *v = (Vdbe*)pStmt;
58383     sqlite3 *db = v->db;
58384 #if SQLITE_THREADSAFE
58385     sqlite3_mutex *mutex;
58386 #endif
58387     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
58388 #if SQLITE_THREADSAFE
58389     mutex = v->db->mutex;
58390 #endif
58391     sqlite3_mutex_enter(mutex);
58392     rc = sqlite3VdbeFinalize(v);
58393     rc = sqlite3ApiExit(db, rc);
58394     sqlite3_mutex_leave(mutex);
58395   }
58396   return rc;
58397 }
58398
58399 /*
58400 ** Terminate the current execution of an SQL statement and reset it
58401 ** back to its starting state so that it can be reused. A success code from
58402 ** the prior execution is returned.
58403 **
58404 ** This routine sets the error code and string returned by
58405 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
58406 */
58407 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
58408   int rc;
58409   if( pStmt==0 ){
58410     rc = SQLITE_OK;
58411   }else{
58412     Vdbe *v = (Vdbe*)pStmt;
58413     sqlite3_mutex_enter(v->db->mutex);
58414     rc = sqlite3VdbeReset(v);
58415     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
58416     assert( (rc & (v->db->errMask))==rc );
58417     rc = sqlite3ApiExit(v->db, rc);
58418     sqlite3_mutex_leave(v->db->mutex);
58419   }
58420   return rc;
58421 }
58422
58423 /*
58424 ** Set all the parameters in the compiled SQL statement to NULL.
58425 */
58426 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
58427   int i;
58428   int rc = SQLITE_OK;
58429   Vdbe *p = (Vdbe*)pStmt;
58430 #if SQLITE_THREADSAFE
58431   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
58432 #endif
58433   sqlite3_mutex_enter(mutex);
58434   for(i=0; i<p->nVar; i++){
58435     sqlite3VdbeMemRelease(&p->aVar[i]);
58436     p->aVar[i].flags = MEM_Null;
58437   }
58438   if( p->isPrepareV2 && p->expmask ){
58439     p->expired = 1;
58440   }
58441   sqlite3_mutex_leave(mutex);
58442   return rc;
58443 }
58444
58445
58446 /**************************** sqlite3_value_  *******************************
58447 ** The following routines extract information from a Mem or sqlite3_value
58448 ** structure.
58449 */
58450 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
58451   Mem *p = (Mem*)pVal;
58452   if( p->flags & (MEM_Blob|MEM_Str) ){
58453     sqlite3VdbeMemExpandBlob(p);
58454     p->flags &= ~MEM_Str;
58455     p->flags |= MEM_Blob;
58456     return p->n ? p->z : 0;
58457   }else{
58458     return sqlite3_value_text(pVal);
58459   }
58460 }
58461 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
58462   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
58463 }
58464 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
58465   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
58466 }
58467 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
58468   return sqlite3VdbeRealValue((Mem*)pVal);
58469 }
58470 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
58471   return (int)sqlite3VdbeIntValue((Mem*)pVal);
58472 }
58473 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
58474   return sqlite3VdbeIntValue((Mem*)pVal);
58475 }
58476 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
58477   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
58478 }
58479 #ifndef SQLITE_OMIT_UTF16
58480 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
58481   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
58482 }
58483 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
58484   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
58485 }
58486 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
58487   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
58488 }
58489 #endif /* SQLITE_OMIT_UTF16 */
58490 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
58491   return pVal->type;
58492 }
58493
58494 /**************************** sqlite3_result_  *******************************
58495 ** The following routines are used by user-defined functions to specify
58496 ** the function result.
58497 **
58498 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
58499 ** result as a string or blob but if the string or blob is too large, it
58500 ** then sets the error code to SQLITE_TOOBIG
58501 */
58502 static void setResultStrOrError(
58503   sqlite3_context *pCtx,  /* Function context */
58504   const char *z,          /* String pointer */
58505   int n,                  /* Bytes in string, or negative */
58506   u8 enc,                 /* Encoding of z.  0 for BLOBs */
58507   void (*xDel)(void*)     /* Destructor function */
58508 ){
58509   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
58510     sqlite3_result_error_toobig(pCtx);
58511   }
58512 }
58513 SQLITE_API void sqlite3_result_blob(
58514   sqlite3_context *pCtx, 
58515   const void *z, 
58516   int n, 
58517   void (*xDel)(void *)
58518 ){
58519   assert( n>=0 );
58520   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58521   setResultStrOrError(pCtx, z, n, 0, xDel);
58522 }
58523 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
58524   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58525   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
58526 }
58527 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
58528   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58529   pCtx->isError = SQLITE_ERROR;
58530   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
58531 }
58532 #ifndef SQLITE_OMIT_UTF16
58533 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
58534   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58535   pCtx->isError = SQLITE_ERROR;
58536   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
58537 }
58538 #endif
58539 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
58540   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58541   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
58542 }
58543 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
58544   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58545   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
58546 }
58547 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
58548   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58549   sqlite3VdbeMemSetNull(&pCtx->s);
58550 }
58551 SQLITE_API void sqlite3_result_text(
58552   sqlite3_context *pCtx, 
58553   const char *z, 
58554   int n,
58555   void (*xDel)(void *)
58556 ){
58557   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58558   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
58559 }
58560 #ifndef SQLITE_OMIT_UTF16
58561 SQLITE_API void sqlite3_result_text16(
58562   sqlite3_context *pCtx, 
58563   const void *z, 
58564   int n, 
58565   void (*xDel)(void *)
58566 ){
58567   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58568   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
58569 }
58570 SQLITE_API void sqlite3_result_text16be(
58571   sqlite3_context *pCtx, 
58572   const void *z, 
58573   int n, 
58574   void (*xDel)(void *)
58575 ){
58576   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58577   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
58578 }
58579 SQLITE_API void sqlite3_result_text16le(
58580   sqlite3_context *pCtx, 
58581   const void *z, 
58582   int n, 
58583   void (*xDel)(void *)
58584 ){
58585   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58586   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
58587 }
58588 #endif /* SQLITE_OMIT_UTF16 */
58589 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
58590   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58591   sqlite3VdbeMemCopy(&pCtx->s, pValue);
58592 }
58593 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
58594   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58595   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
58596 }
58597 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
58598   pCtx->isError = errCode;
58599   if( pCtx->s.flags & MEM_Null ){
58600     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
58601                          SQLITE_UTF8, SQLITE_STATIC);
58602   }
58603 }
58604
58605 /* Force an SQLITE_TOOBIG error. */
58606 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
58607   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58608   pCtx->isError = SQLITE_TOOBIG;
58609   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
58610                        SQLITE_UTF8, SQLITE_STATIC);
58611 }
58612
58613 /* An SQLITE_NOMEM error. */
58614 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
58615   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58616   sqlite3VdbeMemSetNull(&pCtx->s);
58617   pCtx->isError = SQLITE_NOMEM;
58618   pCtx->s.db->mallocFailed = 1;
58619 }
58620
58621 /*
58622 ** This function is called after a transaction has been committed. It 
58623 ** invokes callbacks registered with sqlite3_wal_hook() as required.
58624 */
58625 static int doWalCallbacks(sqlite3 *db){
58626   int rc = SQLITE_OK;
58627 #ifndef SQLITE_OMIT_WAL
58628   int i;
58629   for(i=0; i<db->nDb; i++){
58630     Btree *pBt = db->aDb[i].pBt;
58631     if( pBt ){
58632       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
58633       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
58634         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
58635       }
58636     }
58637   }
58638 #endif
58639   return rc;
58640 }
58641
58642 /*
58643 ** Execute the statement pStmt, either until a row of data is ready, the
58644 ** statement is completely executed or an error occurs.
58645 **
58646 ** This routine implements the bulk of the logic behind the sqlite_step()
58647 ** API.  The only thing omitted is the automatic recompile if a 
58648 ** schema change has occurred.  That detail is handled by the
58649 ** outer sqlite3_step() wrapper procedure.
58650 */
58651 static int sqlite3Step(Vdbe *p){
58652   sqlite3 *db;
58653   int rc;
58654
58655   assert(p);
58656   if( p->magic!=VDBE_MAGIC_RUN ){
58657     /* We used to require that sqlite3_reset() be called before retrying
58658     ** sqlite3_step() after any error.  But after 3.6.23, we changed this
58659     ** so that sqlite3_reset() would be called automatically instead of
58660     ** throwing the error.
58661     */
58662     sqlite3_reset((sqlite3_stmt*)p);
58663   }
58664
58665   /* Check that malloc() has not failed. If it has, return early. */
58666   db = p->db;
58667   if( db->mallocFailed ){
58668     p->rc = SQLITE_NOMEM;
58669     return SQLITE_NOMEM;
58670   }
58671
58672   if( p->pc<=0 && p->expired ){
58673     p->rc = SQLITE_SCHEMA;
58674     rc = SQLITE_ERROR;
58675     goto end_of_step;
58676   }
58677   if( p->pc<0 ){
58678     /* If there are no other statements currently running, then
58679     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
58680     ** from interrupting a statement that has not yet started.
58681     */
58682     if( db->activeVdbeCnt==0 ){
58683       db->u1.isInterrupted = 0;
58684     }
58685
58686     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
58687
58688 #ifndef SQLITE_OMIT_TRACE
58689     if( db->xProfile && !db->init.busy ){
58690       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
58691     }
58692 #endif
58693
58694     db->activeVdbeCnt++;
58695     if( p->readOnly==0 ) db->writeVdbeCnt++;
58696     p->pc = 0;
58697   }
58698 #ifndef SQLITE_OMIT_EXPLAIN
58699   if( p->explain ){
58700     rc = sqlite3VdbeList(p);
58701   }else
58702 #endif /* SQLITE_OMIT_EXPLAIN */
58703   {
58704     rc = sqlite3VdbeExec(p);
58705   }
58706
58707 #ifndef SQLITE_OMIT_TRACE
58708   /* Invoke the profile callback if there is one
58709   */
58710   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
58711     sqlite3_int64 iNow;
58712     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
58713     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
58714   }
58715 #endif
58716
58717   if( rc==SQLITE_DONE ){
58718     assert( p->rc==SQLITE_OK );
58719     p->rc = doWalCallbacks(db);
58720     if( p->rc!=SQLITE_OK ){
58721       rc = SQLITE_ERROR;
58722     }
58723   }
58724
58725   db->errCode = rc;
58726   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
58727     p->rc = SQLITE_NOMEM;
58728   }
58729 end_of_step:
58730   /* At this point local variable rc holds the value that should be 
58731   ** returned if this statement was compiled using the legacy 
58732   ** sqlite3_prepare() interface. According to the docs, this can only
58733   ** be one of the values in the first assert() below. Variable p->rc 
58734   ** contains the value that would be returned if sqlite3_finalize() 
58735   ** were called on statement p.
58736   */
58737   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
58738        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
58739   );
58740   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
58741   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
58742     /* If this statement was prepared using sqlite3_prepare_v2(), and an
58743     ** error has occured, then return the error code in p->rc to the
58744     ** caller. Set the error code in the database handle to the same value.
58745     */ 
58746     rc = db->errCode = p->rc;
58747   }
58748   return (rc&db->errMask);
58749 }
58750
58751 /*
58752 ** This is the top-level implementation of sqlite3_step().  Call
58753 ** sqlite3Step() to do most of the work.  If a schema error occurs,
58754 ** call sqlite3Reprepare() and try again.
58755 */
58756 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
58757   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
58758   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
58759   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
58760   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
58761   sqlite3 *db;             /* The database connection */
58762
58763   if( vdbeSafetyNotNull(v) ){
58764     return SQLITE_MISUSE_BKPT;
58765   }
58766   db = v->db;
58767   sqlite3_mutex_enter(db->mutex);
58768   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
58769          && cnt++ < 5
58770          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
58771     sqlite3_reset(pStmt);
58772     v->expired = 0;
58773   }
58774   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
58775     /* This case occurs after failing to recompile an sql statement. 
58776     ** The error message from the SQL compiler has already been loaded 
58777     ** into the database handle. This block copies the error message 
58778     ** from the database handle into the statement and sets the statement
58779     ** program counter to 0 to ensure that when the statement is 
58780     ** finalized or reset the parser error message is available via
58781     ** sqlite3_errmsg() and sqlite3_errcode().
58782     */
58783     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
58784     sqlite3DbFree(db, v->zErrMsg);
58785     if( !db->mallocFailed ){
58786       v->zErrMsg = sqlite3DbStrDup(db, zErr);
58787       v->rc = rc2;
58788     } else {
58789       v->zErrMsg = 0;
58790       v->rc = rc = SQLITE_NOMEM;
58791     }
58792   }
58793   rc = sqlite3ApiExit(db, rc);
58794   sqlite3_mutex_leave(db->mutex);
58795   return rc;
58796 }
58797
58798 /*
58799 ** Extract the user data from a sqlite3_context structure and return a
58800 ** pointer to it.
58801 */
58802 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
58803   assert( p && p->pFunc );
58804   return p->pFunc->pUserData;
58805 }
58806
58807 /*
58808 ** Extract the user data from a sqlite3_context structure and return a
58809 ** pointer to it.
58810 **
58811 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
58812 ** returns a copy of the pointer to the database connection (the 1st
58813 ** parameter) of the sqlite3_create_function() and
58814 ** sqlite3_create_function16() routines that originally registered the
58815 ** application defined function.
58816 */
58817 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
58818   assert( p && p->pFunc );
58819   return p->s.db;
58820 }
58821
58822 /*
58823 ** The following is the implementation of an SQL function that always
58824 ** fails with an error message stating that the function is used in the
58825 ** wrong context.  The sqlite3_overload_function() API might construct
58826 ** SQL function that use this routine so that the functions will exist
58827 ** for name resolution but are actually overloaded by the xFindFunction
58828 ** method of virtual tables.
58829 */
58830 SQLITE_PRIVATE void sqlite3InvalidFunction(
58831   sqlite3_context *context,  /* The function calling context */
58832   int NotUsed,               /* Number of arguments to the function */
58833   sqlite3_value **NotUsed2   /* Value of each argument */
58834 ){
58835   const char *zName = context->pFunc->zName;
58836   char *zErr;
58837   UNUSED_PARAMETER2(NotUsed, NotUsed2);
58838   zErr = sqlite3_mprintf(
58839       "unable to use function %s in the requested context", zName);
58840   sqlite3_result_error(context, zErr, -1);
58841   sqlite3_free(zErr);
58842 }
58843
58844 /*
58845 ** Allocate or return the aggregate context for a user function.  A new
58846 ** context is allocated on the first call.  Subsequent calls return the
58847 ** same context that was returned on prior calls.
58848 */
58849 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
58850   Mem *pMem;
58851   assert( p && p->pFunc && p->pFunc->xStep );
58852   assert( sqlite3_mutex_held(p->s.db->mutex) );
58853   pMem = p->pMem;
58854   testcase( nByte<0 );
58855   if( (pMem->flags & MEM_Agg)==0 ){
58856     if( nByte<=0 ){
58857       sqlite3VdbeMemReleaseExternal(pMem);
58858       pMem->flags = MEM_Null;
58859       pMem->z = 0;
58860     }else{
58861       sqlite3VdbeMemGrow(pMem, nByte, 0);
58862       pMem->flags = MEM_Agg;
58863       pMem->u.pDef = p->pFunc;
58864       if( pMem->z ){
58865         memset(pMem->z, 0, nByte);
58866       }
58867     }
58868   }
58869   return (void*)pMem->z;
58870 }
58871
58872 /*
58873 ** Return the auxilary data pointer, if any, for the iArg'th argument to
58874 ** the user-function defined by pCtx.
58875 */
58876 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
58877   VdbeFunc *pVdbeFunc;
58878
58879   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58880   pVdbeFunc = pCtx->pVdbeFunc;
58881   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
58882     return 0;
58883   }
58884   return pVdbeFunc->apAux[iArg].pAux;
58885 }
58886
58887 /*
58888 ** Set the auxilary data pointer and delete function, for the iArg'th
58889 ** argument to the user-function defined by pCtx. Any previous value is
58890 ** deleted by calling the delete function specified when it was set.
58891 */
58892 SQLITE_API void sqlite3_set_auxdata(
58893   sqlite3_context *pCtx, 
58894   int iArg, 
58895   void *pAux, 
58896   void (*xDelete)(void*)
58897 ){
58898   struct AuxData *pAuxData;
58899   VdbeFunc *pVdbeFunc;
58900   if( iArg<0 ) goto failed;
58901
58902   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
58903   pVdbeFunc = pCtx->pVdbeFunc;
58904   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
58905     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
58906     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
58907     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
58908     if( !pVdbeFunc ){
58909       goto failed;
58910     }
58911     pCtx->pVdbeFunc = pVdbeFunc;
58912     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
58913     pVdbeFunc->nAux = iArg+1;
58914     pVdbeFunc->pFunc = pCtx->pFunc;
58915   }
58916
58917   pAuxData = &pVdbeFunc->apAux[iArg];
58918   if( pAuxData->pAux && pAuxData->xDelete ){
58919     pAuxData->xDelete(pAuxData->pAux);
58920   }
58921   pAuxData->pAux = pAux;
58922   pAuxData->xDelete = xDelete;
58923   return;
58924
58925 failed:
58926   if( xDelete ){
58927     xDelete(pAux);
58928   }
58929 }
58930
58931 #ifndef SQLITE_OMIT_DEPRECATED
58932 /*
58933 ** Return the number of times the Step function of a aggregate has been 
58934 ** called.
58935 **
58936 ** This function is deprecated.  Do not use it for new code.  It is
58937 ** provide only to avoid breaking legacy code.  New aggregate function
58938 ** implementations should keep their own counts within their aggregate
58939 ** context.
58940 */
58941 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
58942   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
58943   return p->pMem->n;
58944 }
58945 #endif
58946
58947 /*
58948 ** Return the number of columns in the result set for the statement pStmt.
58949 */
58950 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
58951   Vdbe *pVm = (Vdbe *)pStmt;
58952   return pVm ? pVm->nResColumn : 0;
58953 }
58954
58955 /*
58956 ** Return the number of values available from the current row of the
58957 ** currently executing statement pStmt.
58958 */
58959 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
58960   Vdbe *pVm = (Vdbe *)pStmt;
58961   if( pVm==0 || pVm->pResultSet==0 ) return 0;
58962   return pVm->nResColumn;
58963 }
58964
58965
58966 /*
58967 ** Check to see if column iCol of the given statement is valid.  If
58968 ** it is, return a pointer to the Mem for the value of that column.
58969 ** If iCol is not valid, return a pointer to a Mem which has a value
58970 ** of NULL.
58971 */
58972 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
58973   Vdbe *pVm;
58974   int vals;
58975   Mem *pOut;
58976
58977   pVm = (Vdbe *)pStmt;
58978   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
58979     sqlite3_mutex_enter(pVm->db->mutex);
58980     vals = sqlite3_data_count(pStmt);
58981     pOut = &pVm->pResultSet[i];
58982   }else{
58983     /* If the value passed as the second argument is out of range, return
58984     ** a pointer to the following static Mem object which contains the
58985     ** value SQL NULL. Even though the Mem structure contains an element
58986     ** of type i64, on certain architecture (x86) with certain compiler
58987     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
58988     ** instead of an 8-byte one. This all works fine, except that when
58989     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
58990     ** that a Mem structure is located on an 8-byte boundary. To prevent
58991     ** this assert() from failing, when building with SQLITE_DEBUG defined
58992     ** using gcc, force nullMem to be 8-byte aligned using the magical
58993     ** __attribute__((aligned(8))) macro.  */
58994     static const Mem nullMem 
58995 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
58996       __attribute__((aligned(8))) 
58997 #endif
58998       = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
58999
59000     if( pVm && ALWAYS(pVm->db) ){
59001       sqlite3_mutex_enter(pVm->db->mutex);
59002       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
59003     }
59004     pOut = (Mem*)&nullMem;
59005   }
59006   return pOut;
59007 }
59008
59009 /*
59010 ** This function is called after invoking an sqlite3_value_XXX function on a 
59011 ** column value (i.e. a value returned by evaluating an SQL expression in the
59012 ** select list of a SELECT statement) that may cause a malloc() failure. If 
59013 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
59014 ** code of statement pStmt set to SQLITE_NOMEM.
59015 **
59016 ** Specifically, this is called from within:
59017 **
59018 **     sqlite3_column_int()
59019 **     sqlite3_column_int64()
59020 **     sqlite3_column_text()
59021 **     sqlite3_column_text16()
59022 **     sqlite3_column_real()
59023 **     sqlite3_column_bytes()
59024 **     sqlite3_column_bytes16()
59025 **     sqiite3_column_blob()
59026 */
59027 static void columnMallocFailure(sqlite3_stmt *pStmt)
59028 {
59029   /* If malloc() failed during an encoding conversion within an
59030   ** sqlite3_column_XXX API, then set the return code of the statement to
59031   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
59032   ** and _finalize() will return NOMEM.
59033   */
59034   Vdbe *p = (Vdbe *)pStmt;
59035   if( p ){
59036     p->rc = sqlite3ApiExit(p->db, p->rc);
59037     sqlite3_mutex_leave(p->db->mutex);
59038   }
59039 }
59040
59041 /**************************** sqlite3_column_  *******************************
59042 ** The following routines are used to access elements of the current row
59043 ** in the result set.
59044 */
59045 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
59046   const void *val;
59047   val = sqlite3_value_blob( columnMem(pStmt,i) );
59048   /* Even though there is no encoding conversion, value_blob() might
59049   ** need to call malloc() to expand the result of a zeroblob() 
59050   ** expression. 
59051   */
59052   columnMallocFailure(pStmt);
59053   return val;
59054 }
59055 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
59056   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
59057   columnMallocFailure(pStmt);
59058   return val;
59059 }
59060 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
59061   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
59062   columnMallocFailure(pStmt);
59063   return val;
59064 }
59065 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
59066   double val = sqlite3_value_double( columnMem(pStmt,i) );
59067   columnMallocFailure(pStmt);
59068   return val;
59069 }
59070 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
59071   int val = sqlite3_value_int( columnMem(pStmt,i) );
59072   columnMallocFailure(pStmt);
59073   return val;
59074 }
59075 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
59076   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
59077   columnMallocFailure(pStmt);
59078   return val;
59079 }
59080 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
59081   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
59082   columnMallocFailure(pStmt);
59083   return val;
59084 }
59085 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
59086   Mem *pOut = columnMem(pStmt, i);
59087   if( pOut->flags&MEM_Static ){
59088     pOut->flags &= ~MEM_Static;
59089     pOut->flags |= MEM_Ephem;
59090   }
59091   columnMallocFailure(pStmt);
59092   return (sqlite3_value *)pOut;
59093 }
59094 #ifndef SQLITE_OMIT_UTF16
59095 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
59096   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
59097   columnMallocFailure(pStmt);
59098   return val;
59099 }
59100 #endif /* SQLITE_OMIT_UTF16 */
59101 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
59102   int iType = sqlite3_value_type( columnMem(pStmt,i) );
59103   columnMallocFailure(pStmt);
59104   return iType;
59105 }
59106
59107 /* The following function is experimental and subject to change or
59108 ** removal */
59109 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
59110 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
59111 **}
59112 */
59113
59114 /*
59115 ** Convert the N-th element of pStmt->pColName[] into a string using
59116 ** xFunc() then return that string.  If N is out of range, return 0.
59117 **
59118 ** There are up to 5 names for each column.  useType determines which
59119 ** name is returned.  Here are the names:
59120 **
59121 **    0      The column name as it should be displayed for output
59122 **    1      The datatype name for the column
59123 **    2      The name of the database that the column derives from
59124 **    3      The name of the table that the column derives from
59125 **    4      The name of the table column that the result column derives from
59126 **
59127 ** If the result is not a simple column reference (if it is an expression
59128 ** or a constant) then useTypes 2, 3, and 4 return NULL.
59129 */
59130 static const void *columnName(
59131   sqlite3_stmt *pStmt,
59132   int N,
59133   const void *(*xFunc)(Mem*),
59134   int useType
59135 ){
59136   const void *ret = 0;
59137   Vdbe *p = (Vdbe *)pStmt;
59138   int n;
59139   sqlite3 *db = p->db;
59140   
59141   assert( db!=0 );
59142   n = sqlite3_column_count(pStmt);
59143   if( N<n && N>=0 ){
59144     N += useType*n;
59145     sqlite3_mutex_enter(db->mutex);
59146     assert( db->mallocFailed==0 );
59147     ret = xFunc(&p->aColName[N]);
59148      /* A malloc may have failed inside of the xFunc() call. If this
59149     ** is the case, clear the mallocFailed flag and return NULL.
59150     */
59151     if( db->mallocFailed ){
59152       db->mallocFailed = 0;
59153       ret = 0;
59154     }
59155     sqlite3_mutex_leave(db->mutex);
59156   }
59157   return ret;
59158 }
59159
59160 /*
59161 ** Return the name of the Nth column of the result set returned by SQL
59162 ** statement pStmt.
59163 */
59164 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
59165   return columnName(
59166       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
59167 }
59168 #ifndef SQLITE_OMIT_UTF16
59169 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
59170   return columnName(
59171       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
59172 }
59173 #endif
59174
59175 /*
59176 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
59177 ** not define OMIT_DECLTYPE.
59178 */
59179 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
59180 # error "Must not define both SQLITE_OMIT_DECLTYPE \
59181          and SQLITE_ENABLE_COLUMN_METADATA"
59182 #endif
59183
59184 #ifndef SQLITE_OMIT_DECLTYPE
59185 /*
59186 ** Return the column declaration type (if applicable) of the 'i'th column
59187 ** of the result set of SQL statement pStmt.
59188 */
59189 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
59190   return columnName(
59191       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
59192 }
59193 #ifndef SQLITE_OMIT_UTF16
59194 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
59195   return columnName(
59196       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
59197 }
59198 #endif /* SQLITE_OMIT_UTF16 */
59199 #endif /* SQLITE_OMIT_DECLTYPE */
59200
59201 #ifdef SQLITE_ENABLE_COLUMN_METADATA
59202 /*
59203 ** Return the name of the database from which a result column derives.
59204 ** NULL is returned if the result column is an expression or constant or
59205 ** anything else which is not an unabiguous reference to a database column.
59206 */
59207 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
59208   return columnName(
59209       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
59210 }
59211 #ifndef SQLITE_OMIT_UTF16
59212 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
59213   return columnName(
59214       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
59215 }
59216 #endif /* SQLITE_OMIT_UTF16 */
59217
59218 /*
59219 ** Return the name of the table from which a result column derives.
59220 ** NULL is returned if the result column is an expression or constant or
59221 ** anything else which is not an unabiguous reference to a database column.
59222 */
59223 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
59224   return columnName(
59225       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
59226 }
59227 #ifndef SQLITE_OMIT_UTF16
59228 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
59229   return columnName(
59230       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
59231 }
59232 #endif /* SQLITE_OMIT_UTF16 */
59233
59234 /*
59235 ** Return the name of the table column from which a result column derives.
59236 ** NULL is returned if the result column is an expression or constant or
59237 ** anything else which is not an unabiguous reference to a database column.
59238 */
59239 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
59240   return columnName(
59241       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
59242 }
59243 #ifndef SQLITE_OMIT_UTF16
59244 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
59245   return columnName(
59246       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
59247 }
59248 #endif /* SQLITE_OMIT_UTF16 */
59249 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
59250
59251
59252 /******************************* sqlite3_bind_  ***************************
59253 ** 
59254 ** Routines used to attach values to wildcards in a compiled SQL statement.
59255 */
59256 /*
59257 ** Unbind the value bound to variable i in virtual machine p. This is the 
59258 ** the same as binding a NULL value to the column. If the "i" parameter is
59259 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
59260 **
59261 ** A successful evaluation of this routine acquires the mutex on p.
59262 ** the mutex is released if any kind of error occurs.
59263 **
59264 ** The error code stored in database p->db is overwritten with the return
59265 ** value in any case.
59266 */
59267 static int vdbeUnbind(Vdbe *p, int i){
59268   Mem *pVar;
59269   if( vdbeSafetyNotNull(p) ){
59270     return SQLITE_MISUSE_BKPT;
59271   }
59272   sqlite3_mutex_enter(p->db->mutex);
59273   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
59274     sqlite3Error(p->db, SQLITE_MISUSE, 0);
59275     sqlite3_mutex_leave(p->db->mutex);
59276     sqlite3_log(SQLITE_MISUSE, 
59277         "bind on a busy prepared statement: [%s]", p->zSql);
59278     return SQLITE_MISUSE_BKPT;
59279   }
59280   if( i<1 || i>p->nVar ){
59281     sqlite3Error(p->db, SQLITE_RANGE, 0);
59282     sqlite3_mutex_leave(p->db->mutex);
59283     return SQLITE_RANGE;
59284   }
59285   i--;
59286   pVar = &p->aVar[i];
59287   sqlite3VdbeMemRelease(pVar);
59288   pVar->flags = MEM_Null;
59289   sqlite3Error(p->db, SQLITE_OK, 0);
59290
59291   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
59292   ** binding a new value to this variable invalidates the current query plan.
59293   **
59294   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
59295   ** parameter in the WHERE clause might influence the choice of query plan
59296   ** for a statement, then the statement will be automatically recompiled,
59297   ** as if there had been a schema change, on the first sqlite3_step() call
59298   ** following any change to the bindings of that parameter.
59299   */
59300   if( p->isPrepareV2 &&
59301      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
59302   ){
59303     p->expired = 1;
59304   }
59305   return SQLITE_OK;
59306 }
59307
59308 /*
59309 ** Bind a text or BLOB value.
59310 */
59311 static int bindText(
59312   sqlite3_stmt *pStmt,   /* The statement to bind against */
59313   int i,                 /* Index of the parameter to bind */
59314   const void *zData,     /* Pointer to the data to be bound */
59315   int nData,             /* Number of bytes of data to be bound */
59316   void (*xDel)(void*),   /* Destructor for the data */
59317   u8 encoding            /* Encoding for the data */
59318 ){
59319   Vdbe *p = (Vdbe *)pStmt;
59320   Mem *pVar;
59321   int rc;
59322
59323   rc = vdbeUnbind(p, i);
59324   if( rc==SQLITE_OK ){
59325     if( zData!=0 ){
59326       pVar = &p->aVar[i-1];
59327       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
59328       if( rc==SQLITE_OK && encoding!=0 ){
59329         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
59330       }
59331       sqlite3Error(p->db, rc, 0);
59332       rc = sqlite3ApiExit(p->db, rc);
59333     }
59334     sqlite3_mutex_leave(p->db->mutex);
59335   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
59336     xDel((void*)zData);
59337   }
59338   return rc;
59339 }
59340
59341
59342 /*
59343 ** Bind a blob value to an SQL statement variable.
59344 */
59345 SQLITE_API int sqlite3_bind_blob(
59346   sqlite3_stmt *pStmt, 
59347   int i, 
59348   const void *zData, 
59349   int nData, 
59350   void (*xDel)(void*)
59351 ){
59352   return bindText(pStmt, i, zData, nData, xDel, 0);
59353 }
59354 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
59355   int rc;
59356   Vdbe *p = (Vdbe *)pStmt;
59357   rc = vdbeUnbind(p, i);
59358   if( rc==SQLITE_OK ){
59359     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
59360     sqlite3_mutex_leave(p->db->mutex);
59361   }
59362   return rc;
59363 }
59364 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
59365   return sqlite3_bind_int64(p, i, (i64)iValue);
59366 }
59367 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
59368   int rc;
59369   Vdbe *p = (Vdbe *)pStmt;
59370   rc = vdbeUnbind(p, i);
59371   if( rc==SQLITE_OK ){
59372     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
59373     sqlite3_mutex_leave(p->db->mutex);
59374   }
59375   return rc;
59376 }
59377 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
59378   int rc;
59379   Vdbe *p = (Vdbe*)pStmt;
59380   rc = vdbeUnbind(p, i);
59381   if( rc==SQLITE_OK ){
59382     sqlite3_mutex_leave(p->db->mutex);
59383   }
59384   return rc;
59385 }
59386 SQLITE_API int sqlite3_bind_text( 
59387   sqlite3_stmt *pStmt, 
59388   int i, 
59389   const char *zData, 
59390   int nData, 
59391   void (*xDel)(void*)
59392 ){
59393   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
59394 }
59395 #ifndef SQLITE_OMIT_UTF16
59396 SQLITE_API int sqlite3_bind_text16(
59397   sqlite3_stmt *pStmt, 
59398   int i, 
59399   const void *zData, 
59400   int nData, 
59401   void (*xDel)(void*)
59402 ){
59403   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
59404 }
59405 #endif /* SQLITE_OMIT_UTF16 */
59406 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
59407   int rc;
59408   switch( pValue->type ){
59409     case SQLITE_INTEGER: {
59410       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
59411       break;
59412     }
59413     case SQLITE_FLOAT: {
59414       rc = sqlite3_bind_double(pStmt, i, pValue->r);
59415       break;
59416     }
59417     case SQLITE_BLOB: {
59418       if( pValue->flags & MEM_Zero ){
59419         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
59420       }else{
59421         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
59422       }
59423       break;
59424     }
59425     case SQLITE_TEXT: {
59426       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
59427                               pValue->enc);
59428       break;
59429     }
59430     default: {
59431       rc = sqlite3_bind_null(pStmt, i);
59432       break;
59433     }
59434   }
59435   return rc;
59436 }
59437 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
59438   int rc;
59439   Vdbe *p = (Vdbe *)pStmt;
59440   rc = vdbeUnbind(p, i);
59441   if( rc==SQLITE_OK ){
59442     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
59443     sqlite3_mutex_leave(p->db->mutex);
59444   }
59445   return rc;
59446 }
59447
59448 /*
59449 ** Return the number of wildcards that can be potentially bound to.
59450 ** This routine is added to support DBD::SQLite.  
59451 */
59452 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
59453   Vdbe *p = (Vdbe*)pStmt;
59454   return p ? p->nVar : 0;
59455 }
59456
59457 /*
59458 ** Create a mapping from variable numbers to variable names
59459 ** in the Vdbe.azVar[] array, if such a mapping does not already
59460 ** exist.
59461 */
59462 static void createVarMap(Vdbe *p){
59463   if( !p->okVar ){
59464     int j;
59465     Op *pOp;
59466     sqlite3_mutex_enter(p->db->mutex);
59467     /* The race condition here is harmless.  If two threads call this
59468     ** routine on the same Vdbe at the same time, they both might end
59469     ** up initializing the Vdbe.azVar[] array.  That is a little extra
59470     ** work but it results in the same answer.
59471     */
59472     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
59473       if( pOp->opcode==OP_Variable ){
59474         assert( pOp->p1>0 && pOp->p1<=p->nVar );
59475         p->azVar[pOp->p1-1] = pOp->p4.z;
59476       }
59477     }
59478     p->okVar = 1;
59479     sqlite3_mutex_leave(p->db->mutex);
59480   }
59481 }
59482
59483 /*
59484 ** Return the name of a wildcard parameter.  Return NULL if the index
59485 ** is out of range or if the wildcard is unnamed.
59486 **
59487 ** The result is always UTF-8.
59488 */
59489 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
59490   Vdbe *p = (Vdbe*)pStmt;
59491   if( p==0 || i<1 || i>p->nVar ){
59492     return 0;
59493   }
59494   createVarMap(p);
59495   return p->azVar[i-1];
59496 }
59497
59498 /*
59499 ** Given a wildcard parameter name, return the index of the variable
59500 ** with that name.  If there is no variable with the given name,
59501 ** return 0.
59502 */
59503 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
59504   int i;
59505   if( p==0 ){
59506     return 0;
59507   }
59508   createVarMap(p); 
59509   if( zName ){
59510     for(i=0; i<p->nVar; i++){
59511       const char *z = p->azVar[i];
59512       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
59513         return i+1;
59514       }
59515     }
59516   }
59517   return 0;
59518 }
59519 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
59520   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
59521 }
59522
59523 /*
59524 ** Transfer all bindings from the first statement over to the second.
59525 */
59526 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
59527   Vdbe *pFrom = (Vdbe*)pFromStmt;
59528   Vdbe *pTo = (Vdbe*)pToStmt;
59529   int i;
59530   assert( pTo->db==pFrom->db );
59531   assert( pTo->nVar==pFrom->nVar );
59532   sqlite3_mutex_enter(pTo->db->mutex);
59533   for(i=0; i<pFrom->nVar; i++){
59534     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
59535   }
59536   sqlite3_mutex_leave(pTo->db->mutex);
59537   return SQLITE_OK;
59538 }
59539
59540 #ifndef SQLITE_OMIT_DEPRECATED
59541 /*
59542 ** Deprecated external interface.  Internal/core SQLite code
59543 ** should call sqlite3TransferBindings.
59544 **
59545 ** Is is misuse to call this routine with statements from different
59546 ** database connections.  But as this is a deprecated interface, we
59547 ** will not bother to check for that condition.
59548 **
59549 ** If the two statements contain a different number of bindings, then
59550 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
59551 ** SQLITE_OK is returned.
59552 */
59553 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
59554   Vdbe *pFrom = (Vdbe*)pFromStmt;
59555   Vdbe *pTo = (Vdbe*)pToStmt;
59556   if( pFrom->nVar!=pTo->nVar ){
59557     return SQLITE_ERROR;
59558   }
59559   if( pTo->isPrepareV2 && pTo->expmask ){
59560     pTo->expired = 1;
59561   }
59562   if( pFrom->isPrepareV2 && pFrom->expmask ){
59563     pFrom->expired = 1;
59564   }
59565   return sqlite3TransferBindings(pFromStmt, pToStmt);
59566 }
59567 #endif
59568
59569 /*
59570 ** Return the sqlite3* database handle to which the prepared statement given
59571 ** in the argument belongs.  This is the same database handle that was
59572 ** the first argument to the sqlite3_prepare() that was used to create
59573 ** the statement in the first place.
59574 */
59575 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
59576   return pStmt ? ((Vdbe*)pStmt)->db : 0;
59577 }
59578
59579 /*
59580 ** Return true if the prepared statement is guaranteed to not modify the
59581 ** database.
59582 */
59583 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
59584   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
59585 }
59586
59587 /*
59588 ** Return a pointer to the next prepared statement after pStmt associated
59589 ** with database connection pDb.  If pStmt is NULL, return the first
59590 ** prepared statement for the database connection.  Return NULL if there
59591 ** are no more.
59592 */
59593 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
59594   sqlite3_stmt *pNext;
59595   sqlite3_mutex_enter(pDb->mutex);
59596   if( pStmt==0 ){
59597     pNext = (sqlite3_stmt*)pDb->pVdbe;
59598   }else{
59599     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
59600   }
59601   sqlite3_mutex_leave(pDb->mutex);
59602   return pNext;
59603 }
59604
59605 /*
59606 ** Return the value of a status counter for a prepared statement
59607 */
59608 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
59609   Vdbe *pVdbe = (Vdbe*)pStmt;
59610   int v = pVdbe->aCounter[op-1];
59611   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
59612   return v;
59613 }
59614
59615 /************** End of vdbeapi.c *********************************************/
59616 /************** Begin file vdbetrace.c ***************************************/
59617 /*
59618 ** 2009 November 25
59619 **
59620 ** The author disclaims copyright to this source code.  In place of
59621 ** a legal notice, here is a blessing:
59622 **
59623 **    May you do good and not evil.
59624 **    May you find forgiveness for yourself and forgive others.
59625 **    May you share freely, never taking more than you give.
59626 **
59627 *************************************************************************
59628 **
59629 ** This file contains code used to insert the values of host parameters
59630 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
59631 */
59632
59633 #ifndef SQLITE_OMIT_TRACE
59634
59635 /*
59636 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
59637 ** bytes in this text up to but excluding the first character in
59638 ** a host parameter.  If the text contains no host parameters, return
59639 ** the total number of bytes in the text.
59640 */
59641 static int findNextHostParameter(const char *zSql, int *pnToken){
59642   int tokenType;
59643   int nTotal = 0;
59644   int n;
59645
59646   *pnToken = 0;
59647   while( zSql[0] ){
59648     n = sqlite3GetToken((u8*)zSql, &tokenType);
59649     assert( n>0 && tokenType!=TK_ILLEGAL );
59650     if( tokenType==TK_VARIABLE ){
59651       *pnToken = n;
59652       break;
59653     }
59654     nTotal += n;
59655     zSql += n;
59656   }
59657   return nTotal;
59658 }
59659
59660 /*
59661 ** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
59662 ** holds a copy of zRawSql but with host parameters expanded to their
59663 ** current bindings.
59664 **
59665 ** The calling function is responsible for making sure the memory returned
59666 ** is eventually freed.
59667 **
59668 ** ALGORITHM:  Scan the input string looking for host parameters in any of
59669 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
59670 ** string literals, quoted identifier names, and comments.  For text forms,
59671 ** the host parameter index is found by scanning the perpared
59672 ** statement for the corresponding OP_Variable opcode.  Once the host
59673 ** parameter index is known, locate the value in p->aVar[].  Then render
59674 ** the value as a literal in place of the host parameter name.
59675 */
59676 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
59677   Vdbe *p,                 /* The prepared statement being evaluated */
59678   const char *zRawSql      /* Raw text of the SQL statement */
59679 ){
59680   sqlite3 *db;             /* The database connection */
59681   int idx = 0;             /* Index of a host parameter */
59682   int nextIndex = 1;       /* Index of next ? host parameter */
59683   int n;                   /* Length of a token prefix */
59684   int nToken;              /* Length of the parameter token */
59685   int i;                   /* Loop counter */
59686   Mem *pVar;               /* Value of a host parameter */
59687   StrAccum out;            /* Accumulate the output here */
59688   char zBase[100];         /* Initial working space */
59689
59690   db = p->db;
59691   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
59692                       db->aLimit[SQLITE_LIMIT_LENGTH]);
59693   out.db = db;
59694   while( zRawSql[0] ){
59695     n = findNextHostParameter(zRawSql, &nToken);
59696     assert( n>0 );
59697     sqlite3StrAccumAppend(&out, zRawSql, n);
59698     zRawSql += n;
59699     assert( zRawSql[0] || nToken==0 );
59700     if( nToken==0 ) break;
59701     if( zRawSql[0]=='?' ){
59702       if( nToken>1 ){
59703         assert( sqlite3Isdigit(zRawSql[1]) );
59704         sqlite3GetInt32(&zRawSql[1], &idx);
59705       }else{
59706         idx = nextIndex;
59707       }
59708     }else{
59709       assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
59710       testcase( zRawSql[0]==':' );
59711       testcase( zRawSql[0]=='$' );
59712       testcase( zRawSql[0]=='@' );
59713       idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
59714       assert( idx>0 );
59715     }
59716     zRawSql += nToken;
59717     nextIndex = idx + 1;
59718     assert( idx>0 && idx<=p->nVar );
59719     pVar = &p->aVar[idx-1];
59720     if( pVar->flags & MEM_Null ){
59721       sqlite3StrAccumAppend(&out, "NULL", 4);
59722     }else if( pVar->flags & MEM_Int ){
59723       sqlite3XPrintf(&out, "%lld", pVar->u.i);
59724     }else if( pVar->flags & MEM_Real ){
59725       sqlite3XPrintf(&out, "%!.15g", pVar->r);
59726     }else if( pVar->flags & MEM_Str ){
59727 #ifndef SQLITE_OMIT_UTF16
59728       u8 enc = ENC(db);
59729       if( enc!=SQLITE_UTF8 ){
59730         Mem utf8;
59731         memset(&utf8, 0, sizeof(utf8));
59732         utf8.db = db;
59733         sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
59734         sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
59735         sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
59736         sqlite3VdbeMemRelease(&utf8);
59737       }else
59738 #endif
59739       {
59740         sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
59741       }
59742     }else if( pVar->flags & MEM_Zero ){
59743       sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
59744     }else{
59745       assert( pVar->flags & MEM_Blob );
59746       sqlite3StrAccumAppend(&out, "x'", 2);
59747       for(i=0; i<pVar->n; i++){
59748         sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
59749       }
59750       sqlite3StrAccumAppend(&out, "'", 1);
59751     }
59752   }
59753   return sqlite3StrAccumFinish(&out);
59754 }
59755
59756 #endif /* #ifndef SQLITE_OMIT_TRACE */
59757
59758 /************** End of vdbetrace.c *******************************************/
59759 /************** Begin file vdbe.c ********************************************/
59760 /*
59761 ** 2001 September 15
59762 **
59763 ** The author disclaims copyright to this source code.  In place of
59764 ** a legal notice, here is a blessing:
59765 **
59766 **    May you do good and not evil.
59767 **    May you find forgiveness for yourself and forgive others.
59768 **    May you share freely, never taking more than you give.
59769 **
59770 *************************************************************************
59771 ** The code in this file implements execution method of the 
59772 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
59773 ** handles housekeeping details such as creating and deleting
59774 ** VDBE instances.  This file is solely interested in executing
59775 ** the VDBE program.
59776 **
59777 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
59778 ** to a VDBE.
59779 **
59780 ** The SQL parser generates a program which is then executed by
59781 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
59782 ** similar in form to assembly language.  The program consists of
59783 ** a linear sequence of operations.  Each operation has an opcode 
59784 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
59785 ** is a null-terminated string.  Operand P5 is an unsigned character.
59786 ** Few opcodes use all 5 operands.
59787 **
59788 ** Computation results are stored on a set of registers numbered beginning
59789 ** with 1 and going up to Vdbe.nMem.  Each register can store
59790 ** either an integer, a null-terminated string, a floating point
59791 ** number, or the SQL "NULL" value.  An implicit conversion from one
59792 ** type to the other occurs as necessary.
59793 ** 
59794 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
59795 ** function which does the work of interpreting a VDBE program.
59796 ** But other routines are also provided to help in building up
59797 ** a program instruction by instruction.
59798 **
59799 ** Various scripts scan this source file in order to generate HTML
59800 ** documentation, headers files, or other derived files.  The formatting
59801 ** of the code in this file is, therefore, important.  See other comments
59802 ** in this file for details.  If in doubt, do not deviate from existing
59803 ** commenting and indentation practices when changing or adding code.
59804 */
59805
59806 /*
59807 ** Invoke this macro on memory cells just prior to changing the
59808 ** value of the cell.  This macro verifies that shallow copies are
59809 ** not misused.
59810 */
59811 #ifdef SQLITE_DEBUG
59812 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
59813 #else
59814 # define memAboutToChange(P,M)
59815 #endif
59816
59817 /*
59818 ** The following global variable is incremented every time a cursor
59819 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
59820 ** procedures use this information to make sure that indices are
59821 ** working correctly.  This variable has no function other than to
59822 ** help verify the correct operation of the library.
59823 */
59824 #ifdef SQLITE_TEST
59825 SQLITE_API int sqlite3_search_count = 0;
59826 #endif
59827
59828 /*
59829 ** When this global variable is positive, it gets decremented once before
59830 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
59831 ** field of the sqlite3 structure is set in order to simulate and interrupt.
59832 **
59833 ** This facility is used for testing purposes only.  It does not function
59834 ** in an ordinary build.
59835 */
59836 #ifdef SQLITE_TEST
59837 SQLITE_API int sqlite3_interrupt_count = 0;
59838 #endif
59839
59840 /*
59841 ** The next global variable is incremented each type the OP_Sort opcode
59842 ** is executed.  The test procedures use this information to make sure that
59843 ** sorting is occurring or not occurring at appropriate times.   This variable
59844 ** has no function other than to help verify the correct operation of the
59845 ** library.
59846 */
59847 #ifdef SQLITE_TEST
59848 SQLITE_API int sqlite3_sort_count = 0;
59849 #endif
59850
59851 /*
59852 ** The next global variable records the size of the largest MEM_Blob
59853 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
59854 ** use this information to make sure that the zero-blob functionality
59855 ** is working correctly.   This variable has no function other than to
59856 ** help verify the correct operation of the library.
59857 */
59858 #ifdef SQLITE_TEST
59859 SQLITE_API int sqlite3_max_blobsize = 0;
59860 static void updateMaxBlobsize(Mem *p){
59861   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
59862     sqlite3_max_blobsize = p->n;
59863   }
59864 }
59865 #endif
59866
59867 /*
59868 ** The next global variable is incremented each type the OP_Found opcode
59869 ** is executed. This is used to test whether or not the foreign key
59870 ** operation implemented using OP_FkIsZero is working. This variable
59871 ** has no function other than to help verify the correct operation of the
59872 ** library.
59873 */
59874 #ifdef SQLITE_TEST
59875 SQLITE_API int sqlite3_found_count = 0;
59876 #endif
59877
59878 /*
59879 ** Test a register to see if it exceeds the current maximum blob size.
59880 ** If it does, record the new maximum blob size.
59881 */
59882 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
59883 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
59884 #else
59885 # define UPDATE_MAX_BLOBSIZE(P)
59886 #endif
59887
59888 /*
59889 ** Convert the given register into a string if it isn't one
59890 ** already. Return non-zero if a malloc() fails.
59891 */
59892 #define Stringify(P, enc) \
59893    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
59894      { goto no_mem; }
59895
59896 /*
59897 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
59898 ** a pointer to a dynamically allocated string where some other entity
59899 ** is responsible for deallocating that string.  Because the register
59900 ** does not control the string, it might be deleted without the register
59901 ** knowing it.
59902 **
59903 ** This routine converts an ephemeral string into a dynamically allocated
59904 ** string that the register itself controls.  In other words, it
59905 ** converts an MEM_Ephem string into an MEM_Dyn string.
59906 */
59907 #define Deephemeralize(P) \
59908    if( ((P)->flags&MEM_Ephem)!=0 \
59909        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
59910
59911 /*
59912 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
59913 ** P if required.
59914 */
59915 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
59916
59917 /*
59918 ** Argument pMem points at a register that will be passed to a
59919 ** user-defined function or returned to the user as the result of a query.
59920 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
59921 ** routines.
59922 */
59923 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
59924   int flags = pMem->flags;
59925   if( flags & MEM_Null ){
59926     pMem->type = SQLITE_NULL;
59927   }
59928   else if( flags & MEM_Int ){
59929     pMem->type = SQLITE_INTEGER;
59930   }
59931   else if( flags & MEM_Real ){
59932     pMem->type = SQLITE_FLOAT;
59933   }
59934   else if( flags & MEM_Str ){
59935     pMem->type = SQLITE_TEXT;
59936   }else{
59937     pMem->type = SQLITE_BLOB;
59938   }
59939 }
59940
59941 /*
59942 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
59943 ** if we run out of memory.
59944 */
59945 static VdbeCursor *allocateCursor(
59946   Vdbe *p,              /* The virtual machine */
59947   int iCur,             /* Index of the new VdbeCursor */
59948   int nField,           /* Number of fields in the table or index */
59949   int iDb,              /* When database the cursor belongs to, or -1 */
59950   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
59951 ){
59952   /* Find the memory cell that will be used to store the blob of memory
59953   ** required for this VdbeCursor structure. It is convenient to use a 
59954   ** vdbe memory cell to manage the memory allocation required for a
59955   ** VdbeCursor structure for the following reasons:
59956   **
59957   **   * Sometimes cursor numbers are used for a couple of different
59958   **     purposes in a vdbe program. The different uses might require
59959   **     different sized allocations. Memory cells provide growable
59960   **     allocations.
59961   **
59962   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
59963   **     be freed lazily via the sqlite3_release_memory() API. This
59964   **     minimizes the number of malloc calls made by the system.
59965   **
59966   ** Memory cells for cursors are allocated at the top of the address
59967   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
59968   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
59969   */
59970   Mem *pMem = &p->aMem[p->nMem-iCur];
59971
59972   int nByte;
59973   VdbeCursor *pCx = 0;
59974   nByte = 
59975       ROUND8(sizeof(VdbeCursor)) + 
59976       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
59977       2*nField*sizeof(u32);
59978
59979   assert( iCur<p->nCursor );
59980   if( p->apCsr[iCur] ){
59981     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
59982     p->apCsr[iCur] = 0;
59983   }
59984   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
59985     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
59986     memset(pCx, 0, sizeof(VdbeCursor));
59987     pCx->iDb = iDb;
59988     pCx->nField = nField;
59989     if( nField ){
59990       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
59991     }
59992     if( isBtreeCursor ){
59993       pCx->pCursor = (BtCursor*)
59994           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
59995       sqlite3BtreeCursorZero(pCx->pCursor);
59996     }
59997   }
59998   return pCx;
59999 }
60000
60001 /*
60002 ** Try to convert a value into a numeric representation if we can
60003 ** do so without loss of information.  In other words, if the string
60004 ** looks like a number, convert it into a number.  If it does not
60005 ** look like a number, leave it alone.
60006 */
60007 static void applyNumericAffinity(Mem *pRec){
60008   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
60009     double rValue;
60010     i64 iValue;
60011     u8 enc = pRec->enc;
60012     if( (pRec->flags&MEM_Str)==0 ) return;
60013     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
60014     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
60015       pRec->u.i = iValue;
60016       pRec->flags |= MEM_Int;
60017     }else{
60018       pRec->r = rValue;
60019       pRec->flags |= MEM_Real;
60020     }
60021   }
60022 }
60023
60024 /*
60025 ** Processing is determine by the affinity parameter:
60026 **
60027 ** SQLITE_AFF_INTEGER:
60028 ** SQLITE_AFF_REAL:
60029 ** SQLITE_AFF_NUMERIC:
60030 **    Try to convert pRec to an integer representation or a 
60031 **    floating-point representation if an integer representation
60032 **    is not possible.  Note that the integer representation is
60033 **    always preferred, even if the affinity is REAL, because
60034 **    an integer representation is more space efficient on disk.
60035 **
60036 ** SQLITE_AFF_TEXT:
60037 **    Convert pRec to a text representation.
60038 **
60039 ** SQLITE_AFF_NONE:
60040 **    No-op.  pRec is unchanged.
60041 */
60042 static void applyAffinity(
60043   Mem *pRec,          /* The value to apply affinity to */
60044   char affinity,      /* The affinity to be applied */
60045   u8 enc              /* Use this text encoding */
60046 ){
60047   if( affinity==SQLITE_AFF_TEXT ){
60048     /* Only attempt the conversion to TEXT if there is an integer or real
60049     ** representation (blob and NULL do not get converted) but no string
60050     ** representation.
60051     */
60052     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
60053       sqlite3VdbeMemStringify(pRec, enc);
60054     }
60055     pRec->flags &= ~(MEM_Real|MEM_Int);
60056   }else if( affinity!=SQLITE_AFF_NONE ){
60057     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
60058              || affinity==SQLITE_AFF_NUMERIC );
60059     applyNumericAffinity(pRec);
60060     if( pRec->flags & MEM_Real ){
60061       sqlite3VdbeIntegerAffinity(pRec);
60062     }
60063   }
60064 }
60065
60066 /*
60067 ** Try to convert the type of a function argument or a result column
60068 ** into a numeric representation.  Use either INTEGER or REAL whichever
60069 ** is appropriate.  But only do the conversion if it is possible without
60070 ** loss of information and return the revised type of the argument.
60071 */
60072 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
60073   Mem *pMem = (Mem*)pVal;
60074   if( pMem->type==SQLITE_TEXT ){
60075     applyNumericAffinity(pMem);
60076     sqlite3VdbeMemStoreType(pMem);
60077   }
60078   return pMem->type;
60079 }
60080
60081 /*
60082 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
60083 ** not the internal Mem* type.
60084 */
60085 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
60086   sqlite3_value *pVal, 
60087   u8 affinity, 
60088   u8 enc
60089 ){
60090   applyAffinity((Mem *)pVal, affinity, enc);
60091 }
60092
60093 #ifdef SQLITE_DEBUG
60094 /*
60095 ** Write a nice string representation of the contents of cell pMem
60096 ** into buffer zBuf, length nBuf.
60097 */
60098 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
60099   char *zCsr = zBuf;
60100   int f = pMem->flags;
60101
60102   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
60103
60104   if( f&MEM_Blob ){
60105     int i;
60106     char c;
60107     if( f & MEM_Dyn ){
60108       c = 'z';
60109       assert( (f & (MEM_Static|MEM_Ephem))==0 );
60110     }else if( f & MEM_Static ){
60111       c = 't';
60112       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
60113     }else if( f & MEM_Ephem ){
60114       c = 'e';
60115       assert( (f & (MEM_Static|MEM_Dyn))==0 );
60116     }else{
60117       c = 's';
60118     }
60119
60120     sqlite3_snprintf(100, zCsr, "%c", c);
60121     zCsr += sqlite3Strlen30(zCsr);
60122     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
60123     zCsr += sqlite3Strlen30(zCsr);
60124     for(i=0; i<16 && i<pMem->n; i++){
60125       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
60126       zCsr += sqlite3Strlen30(zCsr);
60127     }
60128     for(i=0; i<16 && i<pMem->n; i++){
60129       char z = pMem->z[i];
60130       if( z<32 || z>126 ) *zCsr++ = '.';
60131       else *zCsr++ = z;
60132     }
60133
60134     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
60135     zCsr += sqlite3Strlen30(zCsr);
60136     if( f & MEM_Zero ){
60137       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
60138       zCsr += sqlite3Strlen30(zCsr);
60139     }
60140     *zCsr = '\0';
60141   }else if( f & MEM_Str ){
60142     int j, k;
60143     zBuf[0] = ' ';
60144     if( f & MEM_Dyn ){
60145       zBuf[1] = 'z';
60146       assert( (f & (MEM_Static|MEM_Ephem))==0 );
60147     }else if( f & MEM_Static ){
60148       zBuf[1] = 't';
60149       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
60150     }else if( f & MEM_Ephem ){
60151       zBuf[1] = 'e';
60152       assert( (f & (MEM_Static|MEM_Dyn))==0 );
60153     }else{
60154       zBuf[1] = 's';
60155     }
60156     k = 2;
60157     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
60158     k += sqlite3Strlen30(&zBuf[k]);
60159     zBuf[k++] = '[';
60160     for(j=0; j<15 && j<pMem->n; j++){
60161       u8 c = pMem->z[j];
60162       if( c>=0x20 && c<0x7f ){
60163         zBuf[k++] = c;
60164       }else{
60165         zBuf[k++] = '.';
60166       }
60167     }
60168     zBuf[k++] = ']';
60169     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
60170     k += sqlite3Strlen30(&zBuf[k]);
60171     zBuf[k++] = 0;
60172   }
60173 }
60174 #endif
60175
60176 #ifdef SQLITE_DEBUG
60177 /*
60178 ** Print the value of a register for tracing purposes:
60179 */
60180 static void memTracePrint(FILE *out, Mem *p){
60181   if( p->flags & MEM_Null ){
60182     fprintf(out, " NULL");
60183   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
60184     fprintf(out, " si:%lld", p->u.i);
60185   }else if( p->flags & MEM_Int ){
60186     fprintf(out, " i:%lld", p->u.i);
60187 #ifndef SQLITE_OMIT_FLOATING_POINT
60188   }else if( p->flags & MEM_Real ){
60189     fprintf(out, " r:%g", p->r);
60190 #endif
60191   }else if( p->flags & MEM_RowSet ){
60192     fprintf(out, " (rowset)");
60193   }else{
60194     char zBuf[200];
60195     sqlite3VdbeMemPrettyPrint(p, zBuf);
60196     fprintf(out, " ");
60197     fprintf(out, "%s", zBuf);
60198   }
60199 }
60200 static void registerTrace(FILE *out, int iReg, Mem *p){
60201   fprintf(out, "REG[%d] = ", iReg);
60202   memTracePrint(out, p);
60203   fprintf(out, "\n");
60204 }
60205 #endif
60206
60207 #ifdef SQLITE_DEBUG
60208 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
60209 #else
60210 #  define REGISTER_TRACE(R,M)
60211 #endif
60212
60213
60214 #ifdef VDBE_PROFILE
60215
60216 /* 
60217 ** hwtime.h contains inline assembler code for implementing 
60218 ** high-performance timing routines.
60219 */
60220 /************** Include hwtime.h in the middle of vdbe.c *********************/
60221 /************** Begin file hwtime.h ******************************************/
60222 /*
60223 ** 2008 May 27
60224 **
60225 ** The author disclaims copyright to this source code.  In place of
60226 ** a legal notice, here is a blessing:
60227 **
60228 **    May you do good and not evil.
60229 **    May you find forgiveness for yourself and forgive others.
60230 **    May you share freely, never taking more than you give.
60231 **
60232 ******************************************************************************
60233 **
60234 ** This file contains inline asm code for retrieving "high-performance"
60235 ** counters for x86 class CPUs.
60236 */
60237 #ifndef _HWTIME_H_
60238 #define _HWTIME_H_
60239
60240 /*
60241 ** The following routine only works on pentium-class (or newer) processors.
60242 ** It uses the RDTSC opcode to read the cycle count value out of the
60243 ** processor and returns that value.  This can be used for high-res
60244 ** profiling.
60245 */
60246 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
60247       (defined(i386) || defined(__i386__) || defined(_M_IX86))
60248
60249   #if defined(__GNUC__)
60250
60251   __inline__ sqlite_uint64 sqlite3Hwtime(void){
60252      unsigned int lo, hi;
60253      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
60254      return (sqlite_uint64)hi << 32 | lo;
60255   }
60256
60257   #elif defined(_MSC_VER)
60258
60259   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
60260      __asm {
60261         rdtsc
60262         ret       ; return value at EDX:EAX
60263      }
60264   }
60265
60266   #endif
60267
60268 #elif (defined(__GNUC__) && defined(__x86_64__))
60269
60270   __inline__ sqlite_uint64 sqlite3Hwtime(void){
60271       unsigned long val;
60272       __asm__ __volatile__ ("rdtsc" : "=A" (val));
60273       return val;
60274   }
60275  
60276 #elif (defined(__GNUC__) && defined(__ppc__))
60277
60278   __inline__ sqlite_uint64 sqlite3Hwtime(void){
60279       unsigned long long retval;
60280       unsigned long junk;
60281       __asm__ __volatile__ ("\n\
60282           1:      mftbu   %1\n\
60283                   mftb    %L0\n\
60284                   mftbu   %0\n\
60285                   cmpw    %0,%1\n\
60286                   bne     1b"
60287                   : "=r" (retval), "=r" (junk));
60288       return retval;
60289   }
60290
60291 #else
60292
60293   #error Need implementation of sqlite3Hwtime() for your platform.
60294
60295   /*
60296   ** To compile without implementing sqlite3Hwtime() for your platform,
60297   ** you can remove the above #error and use the following
60298   ** stub function.  You will lose timing support for many
60299   ** of the debugging and testing utilities, but it should at
60300   ** least compile and run.
60301   */
60302 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
60303
60304 #endif
60305
60306 #endif /* !defined(_HWTIME_H_) */
60307
60308 /************** End of hwtime.h **********************************************/
60309 /************** Continuing where we left off in vdbe.c ***********************/
60310
60311 #endif
60312
60313 /*
60314 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
60315 ** sqlite3_interrupt() routine has been called.  If it has been, then
60316 ** processing of the VDBE program is interrupted.
60317 **
60318 ** This macro added to every instruction that does a jump in order to
60319 ** implement a loop.  This test used to be on every single instruction,
60320 ** but that meant we more testing that we needed.  By only testing the
60321 ** flag on jump instructions, we get a (small) speed improvement.
60322 */
60323 #define CHECK_FOR_INTERRUPT \
60324    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
60325
60326
60327 #ifndef NDEBUG
60328 /*
60329 ** This function is only called from within an assert() expression. It
60330 ** checks that the sqlite3.nTransaction variable is correctly set to
60331 ** the number of non-transaction savepoints currently in the 
60332 ** linked list starting at sqlite3.pSavepoint.
60333 ** 
60334 ** Usage:
60335 **
60336 **     assert( checkSavepointCount(db) );
60337 */
60338 static int checkSavepointCount(sqlite3 *db){
60339   int n = 0;
60340   Savepoint *p;
60341   for(p=db->pSavepoint; p; p=p->pNext) n++;
60342   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
60343   return 1;
60344 }
60345 #endif
60346
60347 /*
60348 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
60349 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
60350 ** in memory obtained from sqlite3DbMalloc).
60351 */
60352 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
60353   sqlite3 *db = p->db;
60354   sqlite3DbFree(db, p->zErrMsg);
60355   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
60356   sqlite3_free(pVtab->zErrMsg);
60357   pVtab->zErrMsg = 0;
60358 }
60359
60360
60361 /*
60362 ** Execute as much of a VDBE program as we can then return.
60363 **
60364 ** sqlite3VdbeMakeReady() must be called before this routine in order to
60365 ** close the program with a final OP_Halt and to set up the callbacks
60366 ** and the error message pointer.
60367 **
60368 ** Whenever a row or result data is available, this routine will either
60369 ** invoke the result callback (if there is one) or return with
60370 ** SQLITE_ROW.
60371 **
60372 ** If an attempt is made to open a locked database, then this routine
60373 ** will either invoke the busy callback (if there is one) or it will
60374 ** return SQLITE_BUSY.
60375 **
60376 ** If an error occurs, an error message is written to memory obtained
60377 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
60378 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
60379 **
60380 ** If the callback ever returns non-zero, then the program exits
60381 ** immediately.  There will be no error message but the p->rc field is
60382 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
60383 **
60384 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
60385 ** routine to return SQLITE_ERROR.
60386 **
60387 ** Other fatal errors return SQLITE_ERROR.
60388 **
60389 ** After this routine has finished, sqlite3VdbeFinalize() should be
60390 ** used to clean up the mess that was left behind.
60391 */
60392 SQLITE_PRIVATE int sqlite3VdbeExec(
60393   Vdbe *p                    /* The VDBE */
60394 ){
60395   int pc=0;                  /* The program counter */
60396   Op *aOp = p->aOp;          /* Copy of p->aOp */
60397   Op *pOp;                   /* Current operation */
60398   int rc = SQLITE_OK;        /* Value to return */
60399   sqlite3 *db = p->db;       /* The database */
60400   u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
60401   u8 encoding = ENC(db);     /* The database encoding */
60402 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
60403   int checkProgress;         /* True if progress callbacks are enabled */
60404   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
60405 #endif
60406   Mem *aMem = p->aMem;       /* Copy of p->aMem */
60407   Mem *pIn1 = 0;             /* 1st input operand */
60408   Mem *pIn2 = 0;             /* 2nd input operand */
60409   Mem *pIn3 = 0;             /* 3rd input operand */
60410   Mem *pOut = 0;             /* Output operand */
60411   int iCompare = 0;          /* Result of last OP_Compare operation */
60412   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
60413 #ifdef VDBE_PROFILE
60414   u64 start;                 /* CPU clock count at start of opcode */
60415   int origPc;                /* Program counter at start of opcode */
60416 #endif
60417   /********************************************************************
60418   ** Automatically generated code
60419   **
60420   ** The following union is automatically generated by the
60421   ** vdbe-compress.tcl script.  The purpose of this union is to
60422   ** reduce the amount of stack space required by this function.
60423   ** See comments in the vdbe-compress.tcl script for details.
60424   */
60425   union vdbeExecUnion {
60426     struct OP_Yield_stack_vars {
60427       int pcDest;
60428     } aa;
60429     struct OP_Variable_stack_vars {
60430       Mem *pVar;       /* Value being transferred */
60431     } ab;
60432     struct OP_Move_stack_vars {
60433       char *zMalloc;   /* Holding variable for allocated memory */
60434       int n;           /* Number of registers left to copy */
60435       int p1;          /* Register to copy from */
60436       int p2;          /* Register to copy to */
60437     } ac;
60438     struct OP_ResultRow_stack_vars {
60439       Mem *pMem;
60440       int i;
60441     } ad;
60442     struct OP_Concat_stack_vars {
60443       i64 nByte;
60444     } ae;
60445     struct OP_Remainder_stack_vars {
60446       int flags;      /* Combined MEM_* flags from both inputs */
60447       i64 iA;         /* Integer value of left operand */
60448       i64 iB;         /* Integer value of right operand */
60449       double rA;      /* Real value of left operand */
60450       double rB;      /* Real value of right operand */
60451     } af;
60452     struct OP_Function_stack_vars {
60453       int i;
60454       Mem *pArg;
60455       sqlite3_context ctx;
60456       sqlite3_value **apVal;
60457       int n;
60458     } ag;
60459     struct OP_ShiftRight_stack_vars {
60460       i64 a;
60461       i64 b;
60462     } ah;
60463     struct OP_Ge_stack_vars {
60464       int res;            /* Result of the comparison of pIn1 against pIn3 */
60465       char affinity;      /* Affinity to use for comparison */
60466       u16 flags1;         /* Copy of initial value of pIn1->flags */
60467       u16 flags3;         /* Copy of initial value of pIn3->flags */
60468     } ai;
60469     struct OP_Compare_stack_vars {
60470       int n;
60471       int i;
60472       int p1;
60473       int p2;
60474       const KeyInfo *pKeyInfo;
60475       int idx;
60476       CollSeq *pColl;    /* Collating sequence to use on this term */
60477       int bRev;          /* True for DESCENDING sort order */
60478     } aj;
60479     struct OP_Or_stack_vars {
60480       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60481       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
60482     } ak;
60483     struct OP_IfNot_stack_vars {
60484       int c;
60485     } al;
60486     struct OP_Column_stack_vars {
60487       u32 payloadSize;   /* Number of bytes in the record */
60488       i64 payloadSize64; /* Number of bytes in the record */
60489       int p1;            /* P1 value of the opcode */
60490       int p2;            /* column number to retrieve */
60491       VdbeCursor *pC;    /* The VDBE cursor */
60492       char *zRec;        /* Pointer to complete record-data */
60493       BtCursor *pCrsr;   /* The BTree cursor */
60494       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
60495       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
60496       int nField;        /* number of fields in the record */
60497       int len;           /* The length of the serialized data for the column */
60498       int i;             /* Loop counter */
60499       char *zData;       /* Part of the record being decoded */
60500       Mem *pDest;        /* Where to write the extracted value */
60501       Mem sMem;          /* For storing the record being decoded */
60502       u8 *zIdx;          /* Index into header */
60503       u8 *zEndHdr;       /* Pointer to first byte after the header */
60504       u32 offset;        /* Offset into the data */
60505       u32 szField;       /* Number of bytes in the content of a field */
60506       int szHdr;         /* Size of the header size field at start of record */
60507       int avail;         /* Number of bytes of available data */
60508       Mem *pReg;         /* PseudoTable input register */
60509     } am;
60510     struct OP_Affinity_stack_vars {
60511       const char *zAffinity;   /* The affinity to be applied */
60512       char cAff;               /* A single character of affinity */
60513     } an;
60514     struct OP_MakeRecord_stack_vars {
60515       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
60516       Mem *pRec;             /* The new record */
60517       u64 nData;             /* Number of bytes of data space */
60518       int nHdr;              /* Number of bytes of header space */
60519       i64 nByte;             /* Data space required for this record */
60520       int nZero;             /* Number of zero bytes at the end of the record */
60521       int nVarint;           /* Number of bytes in a varint */
60522       u32 serial_type;       /* Type field */
60523       Mem *pData0;           /* First field to be combined into the record */
60524       Mem *pLast;            /* Last field of the record */
60525       int nField;            /* Number of fields in the record */
60526       char *zAffinity;       /* The affinity string for the record */
60527       int file_format;       /* File format to use for encoding */
60528       int i;                 /* Space used in zNewRecord[] */
60529       int len;               /* Length of a field */
60530     } ao;
60531     struct OP_Count_stack_vars {
60532       i64 nEntry;
60533       BtCursor *pCrsr;
60534     } ap;
60535     struct OP_Savepoint_stack_vars {
60536       int p1;                         /* Value of P1 operand */
60537       char *zName;                    /* Name of savepoint */
60538       int nName;
60539       Savepoint *pNew;
60540       Savepoint *pSavepoint;
60541       Savepoint *pTmp;
60542       int iSavepoint;
60543       int ii;
60544     } aq;
60545     struct OP_AutoCommit_stack_vars {
60546       int desiredAutoCommit;
60547       int iRollback;
60548       int turnOnAC;
60549     } ar;
60550     struct OP_Transaction_stack_vars {
60551       Btree *pBt;
60552     } as;
60553     struct OP_ReadCookie_stack_vars {
60554       int iMeta;
60555       int iDb;
60556       int iCookie;
60557     } at;
60558     struct OP_SetCookie_stack_vars {
60559       Db *pDb;
60560     } au;
60561     struct OP_VerifyCookie_stack_vars {
60562       int iMeta;
60563       Btree *pBt;
60564     } av;
60565     struct OP_OpenWrite_stack_vars {
60566       int nField;
60567       KeyInfo *pKeyInfo;
60568       int p2;
60569       int iDb;
60570       int wrFlag;
60571       Btree *pX;
60572       VdbeCursor *pCur;
60573       Db *pDb;
60574     } aw;
60575     struct OP_OpenEphemeral_stack_vars {
60576       VdbeCursor *pCx;
60577     } ax;
60578     struct OP_OpenPseudo_stack_vars {
60579       VdbeCursor *pCx;
60580     } ay;
60581     struct OP_SeekGt_stack_vars {
60582       int res;
60583       int oc;
60584       VdbeCursor *pC;
60585       UnpackedRecord r;
60586       int nField;
60587       i64 iKey;      /* The rowid we are to seek to */
60588     } az;
60589     struct OP_Seek_stack_vars {
60590       VdbeCursor *pC;
60591     } ba;
60592     struct OP_Found_stack_vars {
60593       int alreadyExists;
60594       VdbeCursor *pC;
60595       int res;
60596       UnpackedRecord *pIdxKey;
60597       UnpackedRecord r;
60598       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
60599     } bb;
60600     struct OP_IsUnique_stack_vars {
60601       u16 ii;
60602       VdbeCursor *pCx;
60603       BtCursor *pCrsr;
60604       u16 nField;
60605       Mem *aMx;
60606       UnpackedRecord r;                  /* B-Tree index search key */
60607       i64 R;                             /* Rowid stored in register P3 */
60608     } bc;
60609     struct OP_NotExists_stack_vars {
60610       VdbeCursor *pC;
60611       BtCursor *pCrsr;
60612       int res;
60613       u64 iKey;
60614     } bd;
60615     struct OP_NewRowid_stack_vars {
60616       i64 v;                 /* The new rowid */
60617       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
60618       int res;               /* Result of an sqlite3BtreeLast() */
60619       int cnt;               /* Counter to limit the number of searches */
60620       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
60621       VdbeFrame *pFrame;     /* Root frame of VDBE */
60622     } be;
60623     struct OP_InsertInt_stack_vars {
60624       Mem *pData;       /* MEM cell holding data for the record to be inserted */
60625       Mem *pKey;        /* MEM cell holding key  for the record */
60626       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
60627       VdbeCursor *pC;   /* Cursor to table into which insert is written */
60628       int nZero;        /* Number of zero-bytes to append */
60629       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
60630       const char *zDb;  /* database name - used by the update hook */
60631       const char *zTbl; /* Table name - used by the opdate hook */
60632       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
60633     } bf;
60634     struct OP_Delete_stack_vars {
60635       i64 iKey;
60636       VdbeCursor *pC;
60637     } bg;
60638     struct OP_RowData_stack_vars {
60639       VdbeCursor *pC;
60640       BtCursor *pCrsr;
60641       u32 n;
60642       i64 n64;
60643     } bh;
60644     struct OP_Rowid_stack_vars {
60645       VdbeCursor *pC;
60646       i64 v;
60647       sqlite3_vtab *pVtab;
60648       const sqlite3_module *pModule;
60649     } bi;
60650     struct OP_NullRow_stack_vars {
60651       VdbeCursor *pC;
60652     } bj;
60653     struct OP_Last_stack_vars {
60654       VdbeCursor *pC;
60655       BtCursor *pCrsr;
60656       int res;
60657     } bk;
60658     struct OP_Rewind_stack_vars {
60659       VdbeCursor *pC;
60660       BtCursor *pCrsr;
60661       int res;
60662     } bl;
60663     struct OP_Next_stack_vars {
60664       VdbeCursor *pC;
60665       BtCursor *pCrsr;
60666       int res;
60667     } bm;
60668     struct OP_IdxInsert_stack_vars {
60669       VdbeCursor *pC;
60670       BtCursor *pCrsr;
60671       int nKey;
60672       const char *zKey;
60673     } bn;
60674     struct OP_IdxDelete_stack_vars {
60675       VdbeCursor *pC;
60676       BtCursor *pCrsr;
60677       int res;
60678       UnpackedRecord r;
60679     } bo;
60680     struct OP_IdxRowid_stack_vars {
60681       BtCursor *pCrsr;
60682       VdbeCursor *pC;
60683       i64 rowid;
60684     } bp;
60685     struct OP_IdxGE_stack_vars {
60686       VdbeCursor *pC;
60687       int res;
60688       UnpackedRecord r;
60689     } bq;
60690     struct OP_Destroy_stack_vars {
60691       int iMoved;
60692       int iCnt;
60693       Vdbe *pVdbe;
60694       int iDb;
60695     } br;
60696     struct OP_Clear_stack_vars {
60697       int nChange;
60698     } bs;
60699     struct OP_CreateTable_stack_vars {
60700       int pgno;
60701       int flags;
60702       Db *pDb;
60703     } bt;
60704     struct OP_ParseSchema_stack_vars {
60705       int iDb;
60706       const char *zMaster;
60707       char *zSql;
60708       InitData initData;
60709     } bu;
60710     struct OP_IntegrityCk_stack_vars {
60711       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
60712       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
60713       int j;          /* Loop counter */
60714       int nErr;       /* Number of errors reported */
60715       char *z;        /* Text of the error report */
60716       Mem *pnErr;     /* Register keeping track of errors remaining */
60717     } bv;
60718     struct OP_RowSetRead_stack_vars {
60719       i64 val;
60720     } bw;
60721     struct OP_RowSetTest_stack_vars {
60722       int iSet;
60723       int exists;
60724     } bx;
60725     struct OP_Program_stack_vars {
60726       int nMem;               /* Number of memory registers for sub-program */
60727       int nByte;              /* Bytes of runtime space required for sub-program */
60728       Mem *pRt;               /* Register to allocate runtime space */
60729       Mem *pMem;              /* Used to iterate through memory cells */
60730       Mem *pEnd;              /* Last memory cell in new array */
60731       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
60732       SubProgram *pProgram;   /* Sub-program to execute */
60733       void *t;                /* Token identifying trigger */
60734     } by;
60735     struct OP_Param_stack_vars {
60736       VdbeFrame *pFrame;
60737       Mem *pIn;
60738     } bz;
60739     struct OP_MemMax_stack_vars {
60740       Mem *pIn1;
60741       VdbeFrame *pFrame;
60742     } ca;
60743     struct OP_AggStep_stack_vars {
60744       int n;
60745       int i;
60746       Mem *pMem;
60747       Mem *pRec;
60748       sqlite3_context ctx;
60749       sqlite3_value **apVal;
60750     } cb;
60751     struct OP_AggFinal_stack_vars {
60752       Mem *pMem;
60753     } cc;
60754     struct OP_JournalMode_stack_vars {
60755       Btree *pBt;                     /* Btree to change journal mode of */
60756       Pager *pPager;                  /* Pager associated with pBt */
60757       int eNew;                       /* New journal mode */
60758       int eOld;                       /* The old journal mode */
60759       const char *zFilename;          /* Name of database file for pPager */
60760     } cd;
60761     struct OP_IncrVacuum_stack_vars {
60762       Btree *pBt;
60763     } ce;
60764     struct OP_VBegin_stack_vars {
60765       VTable *pVTab;
60766     } cf;
60767     struct OP_VOpen_stack_vars {
60768       VdbeCursor *pCur;
60769       sqlite3_vtab_cursor *pVtabCursor;
60770       sqlite3_vtab *pVtab;
60771       sqlite3_module *pModule;
60772     } cg;
60773     struct OP_VFilter_stack_vars {
60774       int nArg;
60775       int iQuery;
60776       const sqlite3_module *pModule;
60777       Mem *pQuery;
60778       Mem *pArgc;
60779       sqlite3_vtab_cursor *pVtabCursor;
60780       sqlite3_vtab *pVtab;
60781       VdbeCursor *pCur;
60782       int res;
60783       int i;
60784       Mem **apArg;
60785     } ch;
60786     struct OP_VColumn_stack_vars {
60787       sqlite3_vtab *pVtab;
60788       const sqlite3_module *pModule;
60789       Mem *pDest;
60790       sqlite3_context sContext;
60791     } ci;
60792     struct OP_VNext_stack_vars {
60793       sqlite3_vtab *pVtab;
60794       const sqlite3_module *pModule;
60795       int res;
60796       VdbeCursor *pCur;
60797     } cj;
60798     struct OP_VRename_stack_vars {
60799       sqlite3_vtab *pVtab;
60800       Mem *pName;
60801     } ck;
60802     struct OP_VUpdate_stack_vars {
60803       sqlite3_vtab *pVtab;
60804       sqlite3_module *pModule;
60805       int nArg;
60806       int i;
60807       sqlite_int64 rowid;
60808       Mem **apArg;
60809       Mem *pX;
60810     } cl;
60811     struct OP_Trace_stack_vars {
60812       char *zTrace;
60813     } cm;
60814   } u;
60815   /* End automatically generated code
60816   ********************************************************************/
60817
60818   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
60819   sqlite3VdbeMutexArrayEnter(p);
60820   if( p->rc==SQLITE_NOMEM ){
60821     /* This happens if a malloc() inside a call to sqlite3_column_text() or
60822     ** sqlite3_column_text16() failed.  */
60823     goto no_mem;
60824   }
60825   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
60826   p->rc = SQLITE_OK;
60827   assert( p->explain==0 );
60828   p->pResultSet = 0;
60829   db->busyHandler.nBusy = 0;
60830   CHECK_FOR_INTERRUPT;
60831   sqlite3VdbeIOTraceSql(p);
60832 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
60833   checkProgress = db->xProgress!=0;
60834 #endif
60835 #ifdef SQLITE_DEBUG
60836   sqlite3BeginBenignMalloc();
60837   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
60838     int i;
60839     printf("VDBE Program Listing:\n");
60840     sqlite3VdbePrintSql(p);
60841     for(i=0; i<p->nOp; i++){
60842       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
60843     }
60844   }
60845   sqlite3EndBenignMalloc();
60846 #endif
60847   for(pc=p->pc; rc==SQLITE_OK; pc++){
60848     assert( pc>=0 && pc<p->nOp );
60849     if( db->mallocFailed ) goto no_mem;
60850 #ifdef VDBE_PROFILE
60851     origPc = pc;
60852     start = sqlite3Hwtime();
60853 #endif
60854     pOp = &aOp[pc];
60855
60856     /* Only allow tracing if SQLITE_DEBUG is defined.
60857     */
60858 #ifdef SQLITE_DEBUG
60859     if( p->trace ){
60860       if( pc==0 ){
60861         printf("VDBE Execution Trace:\n");
60862         sqlite3VdbePrintSql(p);
60863       }
60864       sqlite3VdbePrintOp(p->trace, pc, pOp);
60865     }
60866 #endif
60867       
60868
60869     /* Check to see if we need to simulate an interrupt.  This only happens
60870     ** if we have a special test build.
60871     */
60872 #ifdef SQLITE_TEST
60873     if( sqlite3_interrupt_count>0 ){
60874       sqlite3_interrupt_count--;
60875       if( sqlite3_interrupt_count==0 ){
60876         sqlite3_interrupt(db);
60877       }
60878     }
60879 #endif
60880
60881 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
60882     /* Call the progress callback if it is configured and the required number
60883     ** of VDBE ops have been executed (either since this invocation of
60884     ** sqlite3VdbeExec() or since last time the progress callback was called).
60885     ** If the progress callback returns non-zero, exit the virtual machine with
60886     ** a return code SQLITE_ABORT.
60887     */
60888     if( checkProgress ){
60889       if( db->nProgressOps==nProgressOps ){
60890         int prc;
60891         prc = db->xProgress(db->pProgressArg);
60892         if( prc!=0 ){
60893           rc = SQLITE_INTERRUPT;
60894           goto vdbe_error_halt;
60895         }
60896         nProgressOps = 0;
60897       }
60898       nProgressOps++;
60899     }
60900 #endif
60901
60902     /* On any opcode with the "out2-prerelase" tag, free any
60903     ** external allocations out of mem[p2] and set mem[p2] to be
60904     ** an undefined integer.  Opcodes will either fill in the integer
60905     ** value or convert mem[p2] to a different type.
60906     */
60907     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
60908     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
60909       assert( pOp->p2>0 );
60910       assert( pOp->p2<=p->nMem );
60911       pOut = &aMem[pOp->p2];
60912       memAboutToChange(p, pOut);
60913       sqlite3VdbeMemReleaseExternal(pOut);
60914       pOut->flags = MEM_Int;
60915     }
60916
60917     /* Sanity checking on other operands */
60918 #ifdef SQLITE_DEBUG
60919     if( (pOp->opflags & OPFLG_IN1)!=0 ){
60920       assert( pOp->p1>0 );
60921       assert( pOp->p1<=p->nMem );
60922       assert( memIsValid(&aMem[pOp->p1]) );
60923       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
60924     }
60925     if( (pOp->opflags & OPFLG_IN2)!=0 ){
60926       assert( pOp->p2>0 );
60927       assert( pOp->p2<=p->nMem );
60928       assert( memIsValid(&aMem[pOp->p2]) );
60929       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
60930     }
60931     if( (pOp->opflags & OPFLG_IN3)!=0 ){
60932       assert( pOp->p3>0 );
60933       assert( pOp->p3<=p->nMem );
60934       assert( memIsValid(&aMem[pOp->p3]) );
60935       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
60936     }
60937     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
60938       assert( pOp->p2>0 );
60939       assert( pOp->p2<=p->nMem );
60940       memAboutToChange(p, &aMem[pOp->p2]);
60941     }
60942     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
60943       assert( pOp->p3>0 );
60944       assert( pOp->p3<=p->nMem );
60945       memAboutToChange(p, &aMem[pOp->p3]);
60946     }
60947 #endif
60948   
60949     switch( pOp->opcode ){
60950
60951 /*****************************************************************************
60952 ** What follows is a massive switch statement where each case implements a
60953 ** separate instruction in the virtual machine.  If we follow the usual
60954 ** indentation conventions, each case should be indented by 6 spaces.  But
60955 ** that is a lot of wasted space on the left margin.  So the code within
60956 ** the switch statement will break with convention and be flush-left. Another
60957 ** big comment (similar to this one) will mark the point in the code where
60958 ** we transition back to normal indentation.
60959 **
60960 ** The formatting of each case is important.  The makefile for SQLite
60961 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
60962 ** file looking for lines that begin with "case OP_".  The opcodes.h files
60963 ** will be filled with #defines that give unique integer values to each
60964 ** opcode and the opcodes.c file is filled with an array of strings where
60965 ** each string is the symbolic name for the corresponding opcode.  If the
60966 ** case statement is followed by a comment of the form "/# same as ... #/"
60967 ** that comment is used to determine the particular value of the opcode.
60968 **
60969 ** Other keywords in the comment that follows each case are used to
60970 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
60971 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
60972 ** the mkopcodeh.awk script for additional information.
60973 **
60974 ** Documentation about VDBE opcodes is generated by scanning this file
60975 ** for lines of that contain "Opcode:".  That line and all subsequent
60976 ** comment lines are used in the generation of the opcode.html documentation
60977 ** file.
60978 **
60979 ** SUMMARY:
60980 **
60981 **     Formatting is important to scripts that scan this file.
60982 **     Do not deviate from the formatting style currently in use.
60983 **
60984 *****************************************************************************/
60985
60986 /* Opcode:  Goto * P2 * * *
60987 **
60988 ** An unconditional jump to address P2.
60989 ** The next instruction executed will be 
60990 ** the one at index P2 from the beginning of
60991 ** the program.
60992 */
60993 case OP_Goto: {             /* jump */
60994   CHECK_FOR_INTERRUPT;
60995   pc = pOp->p2 - 1;
60996   break;
60997 }
60998
60999 /* Opcode:  Gosub P1 P2 * * *
61000 **
61001 ** Write the current address onto register P1
61002 ** and then jump to address P2.
61003 */
61004 case OP_Gosub: {            /* jump, in1 */
61005   pIn1 = &aMem[pOp->p1];
61006   assert( (pIn1->flags & MEM_Dyn)==0 );
61007   memAboutToChange(p, pIn1);
61008   pIn1->flags = MEM_Int;
61009   pIn1->u.i = pc;
61010   REGISTER_TRACE(pOp->p1, pIn1);
61011   pc = pOp->p2 - 1;
61012   break;
61013 }
61014
61015 /* Opcode:  Return P1 * * * *
61016 **
61017 ** Jump to the next instruction after the address in register P1.
61018 */
61019 case OP_Return: {           /* in1 */
61020   pIn1 = &aMem[pOp->p1];
61021   assert( pIn1->flags & MEM_Int );
61022   pc = (int)pIn1->u.i;
61023   break;
61024 }
61025
61026 /* Opcode:  Yield P1 * * * *
61027 **
61028 ** Swap the program counter with the value in register P1.
61029 */
61030 case OP_Yield: {            /* in1 */
61031 #if 0  /* local variables moved into u.aa */
61032   int pcDest;
61033 #endif /* local variables moved into u.aa */
61034   pIn1 = &aMem[pOp->p1];
61035   assert( (pIn1->flags & MEM_Dyn)==0 );
61036   pIn1->flags = MEM_Int;
61037   u.aa.pcDest = (int)pIn1->u.i;
61038   pIn1->u.i = pc;
61039   REGISTER_TRACE(pOp->p1, pIn1);
61040   pc = u.aa.pcDest;
61041   break;
61042 }
61043
61044 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
61045 **
61046 ** Check the value in register P3.  If is is NULL then Halt using
61047 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
61048 ** value in register P3 is not NULL, then this routine is a no-op.
61049 */
61050 case OP_HaltIfNull: {      /* in3 */
61051   pIn3 = &aMem[pOp->p3];
61052   if( (pIn3->flags & MEM_Null)==0 ) break;
61053   /* Fall through into OP_Halt */
61054 }
61055
61056 /* Opcode:  Halt P1 P2 * P4 *
61057 **
61058 ** Exit immediately.  All open cursors, etc are closed
61059 ** automatically.
61060 **
61061 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
61062 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
61063 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
61064 ** whether or not to rollback the current transaction.  Do not rollback
61065 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
61066 ** then back out all changes that have occurred during this execution of the
61067 ** VDBE, but do not rollback the transaction. 
61068 **
61069 ** If P4 is not null then it is an error message string.
61070 **
61071 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
61072 ** every program.  So a jump past the last instruction of the program
61073 ** is the same as executing Halt.
61074 */
61075 case OP_Halt: {
61076   if( pOp->p1==SQLITE_OK && p->pFrame ){
61077     /* Halt the sub-program. Return control to the parent frame. */
61078     VdbeFrame *pFrame = p->pFrame;
61079     p->pFrame = pFrame->pParent;
61080     p->nFrame--;
61081     sqlite3VdbeSetChanges(db, p->nChange);
61082     pc = sqlite3VdbeFrameRestore(pFrame);
61083     if( pOp->p2==OE_Ignore ){
61084       /* Instruction pc is the OP_Program that invoked the sub-program 
61085       ** currently being halted. If the p2 instruction of this OP_Halt
61086       ** instruction is set to OE_Ignore, then the sub-program is throwing
61087       ** an IGNORE exception. In this case jump to the address specified
61088       ** as the p2 of the calling OP_Program.  */
61089       pc = p->aOp[pc].p2-1;
61090     }
61091     aOp = p->aOp;
61092     aMem = p->aMem;
61093     break;
61094   }
61095
61096   p->rc = pOp->p1;
61097   p->errorAction = (u8)pOp->p2;
61098   p->pc = pc;
61099   if( pOp->p4.z ){
61100     assert( p->rc!=SQLITE_OK );
61101     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
61102     testcase( sqlite3GlobalConfig.xLog!=0 );
61103     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
61104   }else if( p->rc ){
61105     testcase( sqlite3GlobalConfig.xLog!=0 );
61106     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
61107   }
61108   rc = sqlite3VdbeHalt(p);
61109   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
61110   if( rc==SQLITE_BUSY ){
61111     p->rc = rc = SQLITE_BUSY;
61112   }else{
61113     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
61114     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
61115     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
61116   }
61117   goto vdbe_return;
61118 }
61119
61120 /* Opcode: Integer P1 P2 * * *
61121 **
61122 ** The 32-bit integer value P1 is written into register P2.
61123 */
61124 case OP_Integer: {         /* out2-prerelease */
61125   pOut->u.i = pOp->p1;
61126   break;
61127 }
61128
61129 /* Opcode: Int64 * P2 * P4 *
61130 **
61131 ** P4 is a pointer to a 64-bit integer value.
61132 ** Write that value into register P2.
61133 */
61134 case OP_Int64: {           /* out2-prerelease */
61135   assert( pOp->p4.pI64!=0 );
61136   pOut->u.i = *pOp->p4.pI64;
61137   break;
61138 }
61139
61140 #ifndef SQLITE_OMIT_FLOATING_POINT
61141 /* Opcode: Real * P2 * P4 *
61142 **
61143 ** P4 is a pointer to a 64-bit floating point value.
61144 ** Write that value into register P2.
61145 */
61146 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
61147   pOut->flags = MEM_Real;
61148   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
61149   pOut->r = *pOp->p4.pReal;
61150   break;
61151 }
61152 #endif
61153
61154 /* Opcode: String8 * P2 * P4 *
61155 **
61156 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
61157 ** into an OP_String before it is executed for the first time.
61158 */
61159 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
61160   assert( pOp->p4.z!=0 );
61161   pOp->opcode = OP_String;
61162   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
61163
61164 #ifndef SQLITE_OMIT_UTF16
61165   if( encoding!=SQLITE_UTF8 ){
61166     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
61167     if( rc==SQLITE_TOOBIG ) goto too_big;
61168     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
61169     assert( pOut->zMalloc==pOut->z );
61170     assert( pOut->flags & MEM_Dyn );
61171     pOut->zMalloc = 0;
61172     pOut->flags |= MEM_Static;
61173     pOut->flags &= ~MEM_Dyn;
61174     if( pOp->p4type==P4_DYNAMIC ){
61175       sqlite3DbFree(db, pOp->p4.z);
61176     }
61177     pOp->p4type = P4_DYNAMIC;
61178     pOp->p4.z = pOut->z;
61179     pOp->p1 = pOut->n;
61180   }
61181 #endif
61182   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
61183     goto too_big;
61184   }
61185   /* Fall through to the next case, OP_String */
61186 }
61187   
61188 /* Opcode: String P1 P2 * P4 *
61189 **
61190 ** The string value P4 of length P1 (bytes) is stored in register P2.
61191 */
61192 case OP_String: {          /* out2-prerelease */
61193   assert( pOp->p4.z!=0 );
61194   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
61195   pOut->z = pOp->p4.z;
61196   pOut->n = pOp->p1;
61197   pOut->enc = encoding;
61198   UPDATE_MAX_BLOBSIZE(pOut);
61199   break;
61200 }
61201
61202 /* Opcode: Null * P2 * * *
61203 **
61204 ** Write a NULL into register P2.
61205 */
61206 case OP_Null: {           /* out2-prerelease */
61207   pOut->flags = MEM_Null;
61208   break;
61209 }
61210
61211
61212 /* Opcode: Blob P1 P2 * P4
61213 **
61214 ** P4 points to a blob of data P1 bytes long.  Store this
61215 ** blob in register P2.
61216 */
61217 case OP_Blob: {                /* out2-prerelease */
61218   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
61219   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
61220   pOut->enc = encoding;
61221   UPDATE_MAX_BLOBSIZE(pOut);
61222   break;
61223 }
61224
61225 /* Opcode: Variable P1 P2 * P4 *
61226 **
61227 ** Transfer the values of bound parameter P1 into register P2
61228 **
61229 ** If the parameter is named, then its name appears in P4 and P3==1.
61230 ** The P4 value is used by sqlite3_bind_parameter_name().
61231 */
61232 case OP_Variable: {            /* out2-prerelease */
61233 #if 0  /* local variables moved into u.ab */
61234   Mem *pVar;       /* Value being transferred */
61235 #endif /* local variables moved into u.ab */
61236
61237   assert( pOp->p1>0 && pOp->p1<=p->nVar );
61238   u.ab.pVar = &p->aVar[pOp->p1 - 1];
61239   if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
61240     goto too_big;
61241   }
61242   sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
61243   UPDATE_MAX_BLOBSIZE(pOut);
61244   break;
61245 }
61246
61247 /* Opcode: Move P1 P2 P3 * *
61248 **
61249 ** Move the values in register P1..P1+P3-1 over into
61250 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
61251 ** left holding a NULL.  It is an error for register ranges
61252 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
61253 */
61254 case OP_Move: {
61255 #if 0  /* local variables moved into u.ac */
61256   char *zMalloc;   /* Holding variable for allocated memory */
61257   int n;           /* Number of registers left to copy */
61258   int p1;          /* Register to copy from */
61259   int p2;          /* Register to copy to */
61260 #endif /* local variables moved into u.ac */
61261
61262   u.ac.n = pOp->p3;
61263   u.ac.p1 = pOp->p1;
61264   u.ac.p2 = pOp->p2;
61265   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
61266   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
61267
61268   pIn1 = &aMem[u.ac.p1];
61269   pOut = &aMem[u.ac.p2];
61270   while( u.ac.n-- ){
61271     assert( pOut<=&aMem[p->nMem] );
61272     assert( pIn1<=&aMem[p->nMem] );
61273     assert( memIsValid(pIn1) );
61274     memAboutToChange(p, pOut);
61275     u.ac.zMalloc = pOut->zMalloc;
61276     pOut->zMalloc = 0;
61277     sqlite3VdbeMemMove(pOut, pIn1);
61278     pIn1->zMalloc = u.ac.zMalloc;
61279     REGISTER_TRACE(u.ac.p2++, pOut);
61280     pIn1++;
61281     pOut++;
61282   }
61283   break;
61284 }
61285
61286 /* Opcode: Copy P1 P2 * * *
61287 **
61288 ** Make a copy of register P1 into register P2.
61289 **
61290 ** This instruction makes a deep copy of the value.  A duplicate
61291 ** is made of any string or blob constant.  See also OP_SCopy.
61292 */
61293 case OP_Copy: {             /* in1, out2 */
61294   pIn1 = &aMem[pOp->p1];
61295   pOut = &aMem[pOp->p2];
61296   assert( pOut!=pIn1 );
61297   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
61298   Deephemeralize(pOut);
61299   REGISTER_TRACE(pOp->p2, pOut);
61300   break;
61301 }
61302
61303 /* Opcode: SCopy P1 P2 * * *
61304 **
61305 ** Make a shallow copy of register P1 into register P2.
61306 **
61307 ** This instruction makes a shallow copy of the value.  If the value
61308 ** is a string or blob, then the copy is only a pointer to the
61309 ** original and hence if the original changes so will the copy.
61310 ** Worse, if the original is deallocated, the copy becomes invalid.
61311 ** Thus the program must guarantee that the original will not change
61312 ** during the lifetime of the copy.  Use OP_Copy to make a complete
61313 ** copy.
61314 */
61315 case OP_SCopy: {            /* in1, out2 */
61316   pIn1 = &aMem[pOp->p1];
61317   pOut = &aMem[pOp->p2];
61318   assert( pOut!=pIn1 );
61319   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
61320 #ifdef SQLITE_DEBUG
61321   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
61322 #endif
61323   REGISTER_TRACE(pOp->p2, pOut);
61324   break;
61325 }
61326
61327 /* Opcode: ResultRow P1 P2 * * *
61328 **
61329 ** The registers P1 through P1+P2-1 contain a single row of
61330 ** results. This opcode causes the sqlite3_step() call to terminate
61331 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
61332 ** structure to provide access to the top P1 values as the result
61333 ** row.
61334 */
61335 case OP_ResultRow: {
61336 #if 0  /* local variables moved into u.ad */
61337   Mem *pMem;
61338   int i;
61339 #endif /* local variables moved into u.ad */
61340   assert( p->nResColumn==pOp->p2 );
61341   assert( pOp->p1>0 );
61342   assert( pOp->p1+pOp->p2<=p->nMem+1 );
61343
61344   /* If this statement has violated immediate foreign key constraints, do
61345   ** not return the number of rows modified. And do not RELEASE the statement
61346   ** transaction. It needs to be rolled back.  */
61347   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
61348     assert( db->flags&SQLITE_CountRows );
61349     assert( p->usesStmtJournal );
61350     break;
61351   }
61352
61353   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
61354   ** DML statements invoke this opcode to return the number of rows
61355   ** modified to the user. This is the only way that a VM that
61356   ** opens a statement transaction may invoke this opcode.
61357   **
61358   ** In case this is such a statement, close any statement transaction
61359   ** opened by this VM before returning control to the user. This is to
61360   ** ensure that statement-transactions are always nested, not overlapping.
61361   ** If the open statement-transaction is not closed here, then the user
61362   ** may step another VM that opens its own statement transaction. This
61363   ** may lead to overlapping statement transactions.
61364   **
61365   ** The statement transaction is never a top-level transaction.  Hence
61366   ** the RELEASE call below can never fail.
61367   */
61368   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
61369   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
61370   if( NEVER(rc!=SQLITE_OK) ){
61371     break;
61372   }
61373
61374   /* Invalidate all ephemeral cursor row caches */
61375   p->cacheCtr = (p->cacheCtr + 2)|1;
61376
61377   /* Make sure the results of the current row are \000 terminated
61378   ** and have an assigned type.  The results are de-ephemeralized as
61379   ** as side effect.
61380   */
61381   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
61382   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
61383     assert( memIsValid(&u.ad.pMem[u.ad.i]) );
61384     Deephemeralize(&u.ad.pMem[u.ad.i]);
61385     assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
61386             || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
61387     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
61388     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
61389     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
61390   }
61391   if( db->mallocFailed ) goto no_mem;
61392
61393   /* Return SQLITE_ROW
61394   */
61395   p->pc = pc + 1;
61396   rc = SQLITE_ROW;
61397   goto vdbe_return;
61398 }
61399
61400 /* Opcode: Concat P1 P2 P3 * *
61401 **
61402 ** Add the text in register P1 onto the end of the text in
61403 ** register P2 and store the result in register P3.
61404 ** If either the P1 or P2 text are NULL then store NULL in P3.
61405 **
61406 **   P3 = P2 || P1
61407 **
61408 ** It is illegal for P1 and P3 to be the same register. Sometimes,
61409 ** if P3 is the same register as P2, the implementation is able
61410 ** to avoid a memcpy().
61411 */
61412 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
61413 #if 0  /* local variables moved into u.ae */
61414   i64 nByte;
61415 #endif /* local variables moved into u.ae */
61416
61417   pIn1 = &aMem[pOp->p1];
61418   pIn2 = &aMem[pOp->p2];
61419   pOut = &aMem[pOp->p3];
61420   assert( pIn1!=pOut );
61421   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
61422     sqlite3VdbeMemSetNull(pOut);
61423     break;
61424   }
61425   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
61426   Stringify(pIn1, encoding);
61427   Stringify(pIn2, encoding);
61428   u.ae.nByte = pIn1->n + pIn2->n;
61429   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
61430     goto too_big;
61431   }
61432   MemSetTypeFlag(pOut, MEM_Str);
61433   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
61434     goto no_mem;
61435   }
61436   if( pOut!=pIn2 ){
61437     memcpy(pOut->z, pIn2->z, pIn2->n);
61438   }
61439   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
61440   pOut->z[u.ae.nByte] = 0;
61441   pOut->z[u.ae.nByte+1] = 0;
61442   pOut->flags |= MEM_Term;
61443   pOut->n = (int)u.ae.nByte;
61444   pOut->enc = encoding;
61445   UPDATE_MAX_BLOBSIZE(pOut);
61446   break;
61447 }
61448
61449 /* Opcode: Add P1 P2 P3 * *
61450 **
61451 ** Add the value in register P1 to the value in register P2
61452 ** and store the result in register P3.
61453 ** If either input is NULL, the result is NULL.
61454 */
61455 /* Opcode: Multiply P1 P2 P3 * *
61456 **
61457 **
61458 ** Multiply the value in register P1 by the value in register P2
61459 ** and store the result in register P3.
61460 ** If either input is NULL, the result is NULL.
61461 */
61462 /* Opcode: Subtract P1 P2 P3 * *
61463 **
61464 ** Subtract the value in register P1 from the value in register P2
61465 ** and store the result in register P3.
61466 ** If either input is NULL, the result is NULL.
61467 */
61468 /* Opcode: Divide P1 P2 P3 * *
61469 **
61470 ** Divide the value in register P1 by the value in register P2
61471 ** and store the result in register P3 (P3=P2/P1). If the value in 
61472 ** register P1 is zero, then the result is NULL. If either input is 
61473 ** NULL, the result is NULL.
61474 */
61475 /* Opcode: Remainder P1 P2 P3 * *
61476 **
61477 ** Compute the remainder after integer division of the value in
61478 ** register P1 by the value in register P2 and store the result in P3. 
61479 ** If the value in register P2 is zero the result is NULL.
61480 ** If either operand is NULL, the result is NULL.
61481 */
61482 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
61483 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
61484 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
61485 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
61486 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
61487 #if 0  /* local variables moved into u.af */
61488   int flags;      /* Combined MEM_* flags from both inputs */
61489   i64 iA;         /* Integer value of left operand */
61490   i64 iB;         /* Integer value of right operand */
61491   double rA;      /* Real value of left operand */
61492   double rB;      /* Real value of right operand */
61493 #endif /* local variables moved into u.af */
61494
61495   pIn1 = &aMem[pOp->p1];
61496   applyNumericAffinity(pIn1);
61497   pIn2 = &aMem[pOp->p2];
61498   applyNumericAffinity(pIn2);
61499   pOut = &aMem[pOp->p3];
61500   u.af.flags = pIn1->flags | pIn2->flags;
61501   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
61502   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
61503     u.af.iA = pIn1->u.i;
61504     u.af.iB = pIn2->u.i;
61505     switch( pOp->opcode ){
61506       case OP_Add:         u.af.iB += u.af.iA;       break;
61507       case OP_Subtract:    u.af.iB -= u.af.iA;       break;
61508       case OP_Multiply:    u.af.iB *= u.af.iA;       break;
61509       case OP_Divide: {
61510         if( u.af.iA==0 ) goto arithmetic_result_is_null;
61511         /* Dividing the largest possible negative 64-bit integer (1<<63) by
61512         ** -1 returns an integer too large to store in a 64-bit data-type. On
61513         ** some architectures, the value overflows to (1<<63). On others,
61514         ** a SIGFPE is issued. The following statement normalizes this
61515         ** behavior so that all architectures behave as if integer
61516         ** overflow occurred.
61517         */
61518         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
61519         u.af.iB /= u.af.iA;
61520         break;
61521       }
61522       default: {
61523         if( u.af.iA==0 ) goto arithmetic_result_is_null;
61524         if( u.af.iA==-1 ) u.af.iA = 1;
61525         u.af.iB %= u.af.iA;
61526         break;
61527       }
61528     }
61529     pOut->u.i = u.af.iB;
61530     MemSetTypeFlag(pOut, MEM_Int);
61531   }else{
61532     u.af.rA = sqlite3VdbeRealValue(pIn1);
61533     u.af.rB = sqlite3VdbeRealValue(pIn2);
61534     switch( pOp->opcode ){
61535       case OP_Add:         u.af.rB += u.af.rA;       break;
61536       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
61537       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
61538       case OP_Divide: {
61539         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
61540         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
61541         u.af.rB /= u.af.rA;
61542         break;
61543       }
61544       default: {
61545         u.af.iA = (i64)u.af.rA;
61546         u.af.iB = (i64)u.af.rB;
61547         if( u.af.iA==0 ) goto arithmetic_result_is_null;
61548         if( u.af.iA==-1 ) u.af.iA = 1;
61549         u.af.rB = (double)(u.af.iB % u.af.iA);
61550         break;
61551       }
61552     }
61553 #ifdef SQLITE_OMIT_FLOATING_POINT
61554     pOut->u.i = u.af.rB;
61555     MemSetTypeFlag(pOut, MEM_Int);
61556 #else
61557     if( sqlite3IsNaN(u.af.rB) ){
61558       goto arithmetic_result_is_null;
61559     }
61560     pOut->r = u.af.rB;
61561     MemSetTypeFlag(pOut, MEM_Real);
61562     if( (u.af.flags & MEM_Real)==0 ){
61563       sqlite3VdbeIntegerAffinity(pOut);
61564     }
61565 #endif
61566   }
61567   break;
61568
61569 arithmetic_result_is_null:
61570   sqlite3VdbeMemSetNull(pOut);
61571   break;
61572 }
61573
61574 /* Opcode: CollSeq * * P4
61575 **
61576 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
61577 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
61578 ** be returned. This is used by the built-in min(), max() and nullif()
61579 ** functions.
61580 **
61581 ** The interface used by the implementation of the aforementioned functions
61582 ** to retrieve the collation sequence set by this opcode is not available
61583 ** publicly, only to user functions defined in func.c.
61584 */
61585 case OP_CollSeq: {
61586   assert( pOp->p4type==P4_COLLSEQ );
61587   break;
61588 }
61589
61590 /* Opcode: Function P1 P2 P3 P4 P5
61591 **
61592 ** Invoke a user function (P4 is a pointer to a Function structure that
61593 ** defines the function) with P5 arguments taken from register P2 and
61594 ** successors.  The result of the function is stored in register P3.
61595 ** Register P3 must not be one of the function inputs.
61596 **
61597 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
61598 ** function was determined to be constant at compile time. If the first
61599 ** argument was constant then bit 0 of P1 is set. This is used to determine
61600 ** whether meta data associated with a user function argument using the
61601 ** sqlite3_set_auxdata() API may be safely retained until the next
61602 ** invocation of this opcode.
61603 **
61604 ** See also: AggStep and AggFinal
61605 */
61606 case OP_Function: {
61607 #if 0  /* local variables moved into u.ag */
61608   int i;
61609   Mem *pArg;
61610   sqlite3_context ctx;
61611   sqlite3_value **apVal;
61612   int n;
61613 #endif /* local variables moved into u.ag */
61614
61615   u.ag.n = pOp->p5;
61616   u.ag.apVal = p->apArg;
61617   assert( u.ag.apVal || u.ag.n==0 );
61618   assert( pOp->p3>0 && pOp->p3<=p->nMem );
61619   pOut = &aMem[pOp->p3];
61620   memAboutToChange(p, pOut);
61621
61622   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
61623   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
61624   u.ag.pArg = &aMem[pOp->p2];
61625   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
61626     assert( memIsValid(u.ag.pArg) );
61627     u.ag.apVal[u.ag.i] = u.ag.pArg;
61628     Deephemeralize(u.ag.pArg);
61629     sqlite3VdbeMemStoreType(u.ag.pArg);
61630     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
61631   }
61632
61633   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
61634   if( pOp->p4type==P4_FUNCDEF ){
61635     u.ag.ctx.pFunc = pOp->p4.pFunc;
61636     u.ag.ctx.pVdbeFunc = 0;
61637   }else{
61638     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
61639     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
61640   }
61641
61642   u.ag.ctx.s.flags = MEM_Null;
61643   u.ag.ctx.s.db = db;
61644   u.ag.ctx.s.xDel = 0;
61645   u.ag.ctx.s.zMalloc = 0;
61646
61647   /* The output cell may already have a buffer allocated. Move
61648   ** the pointer to u.ag.ctx.s so in case the user-function can use
61649   ** the already allocated buffer instead of allocating a new one.
61650   */
61651   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
61652   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
61653
61654   u.ag.ctx.isError = 0;
61655   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
61656     assert( pOp>aOp );
61657     assert( pOp[-1].p4type==P4_COLLSEQ );
61658     assert( pOp[-1].opcode==OP_CollSeq );
61659     u.ag.ctx.pColl = pOp[-1].p4.pColl;
61660   }
61661   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
61662   if( db->mallocFailed ){
61663     /* Even though a malloc() has failed, the implementation of the
61664     ** user function may have called an sqlite3_result_XXX() function
61665     ** to return a value. The following call releases any resources
61666     ** associated with such a value.
61667     */
61668     sqlite3VdbeMemRelease(&u.ag.ctx.s);
61669     goto no_mem;
61670   }
61671
61672   /* If any auxiliary data functions have been called by this user function,
61673   ** immediately call the destructor for any non-static values.
61674   */
61675   if( u.ag.ctx.pVdbeFunc ){
61676     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
61677     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
61678     pOp->p4type = P4_VDBEFUNC;
61679   }
61680
61681   /* If the function returned an error, throw an exception */
61682   if( u.ag.ctx.isError ){
61683     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
61684     rc = u.ag.ctx.isError;
61685   }
61686
61687   /* Copy the result of the function into register P3 */
61688   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
61689   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
61690   if( sqlite3VdbeMemTooBig(pOut) ){
61691     goto too_big;
61692   }
61693   REGISTER_TRACE(pOp->p3, pOut);
61694   UPDATE_MAX_BLOBSIZE(pOut);
61695   break;
61696 }
61697
61698 /* Opcode: BitAnd P1 P2 P3 * *
61699 **
61700 ** Take the bit-wise AND of the values in register P1 and P2 and
61701 ** store the result in register P3.
61702 ** If either input is NULL, the result is NULL.
61703 */
61704 /* Opcode: BitOr P1 P2 P3 * *
61705 **
61706 ** Take the bit-wise OR of the values in register P1 and P2 and
61707 ** store the result in register P3.
61708 ** If either input is NULL, the result is NULL.
61709 */
61710 /* Opcode: ShiftLeft P1 P2 P3 * *
61711 **
61712 ** Shift the integer value in register P2 to the left by the
61713 ** number of bits specified by the integer in register P1.
61714 ** Store the result in register P3.
61715 ** If either input is NULL, the result is NULL.
61716 */
61717 /* Opcode: ShiftRight P1 P2 P3 * *
61718 **
61719 ** Shift the integer value in register P2 to the right by the
61720 ** number of bits specified by the integer in register P1.
61721 ** Store the result in register P3.
61722 ** If either input is NULL, the result is NULL.
61723 */
61724 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
61725 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
61726 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
61727 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
61728 #if 0  /* local variables moved into u.ah */
61729   i64 a;
61730   i64 b;
61731 #endif /* local variables moved into u.ah */
61732
61733   pIn1 = &aMem[pOp->p1];
61734   pIn2 = &aMem[pOp->p2];
61735   pOut = &aMem[pOp->p3];
61736   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
61737     sqlite3VdbeMemSetNull(pOut);
61738     break;
61739   }
61740   u.ah.a = sqlite3VdbeIntValue(pIn2);
61741   u.ah.b = sqlite3VdbeIntValue(pIn1);
61742   switch( pOp->opcode ){
61743     case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
61744     case OP_BitOr:       u.ah.a |= u.ah.b;     break;
61745     case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
61746     default:  assert( pOp->opcode==OP_ShiftRight );
61747                          u.ah.a >>= u.ah.b;    break;
61748   }
61749   pOut->u.i = u.ah.a;
61750   MemSetTypeFlag(pOut, MEM_Int);
61751   break;
61752 }
61753
61754 /* Opcode: AddImm  P1 P2 * * *
61755 ** 
61756 ** Add the constant P2 to the value in register P1.
61757 ** The result is always an integer.
61758 **
61759 ** To force any register to be an integer, just add 0.
61760 */
61761 case OP_AddImm: {            /* in1 */
61762   pIn1 = &aMem[pOp->p1];
61763   memAboutToChange(p, pIn1);
61764   sqlite3VdbeMemIntegerify(pIn1);
61765   pIn1->u.i += pOp->p2;
61766   break;
61767 }
61768
61769 /* Opcode: MustBeInt P1 P2 * * *
61770 ** 
61771 ** Force the value in register P1 to be an integer.  If the value
61772 ** in P1 is not an integer and cannot be converted into an integer
61773 ** without data loss, then jump immediately to P2, or if P2==0
61774 ** raise an SQLITE_MISMATCH exception.
61775 */
61776 case OP_MustBeInt: {            /* jump, in1 */
61777   pIn1 = &aMem[pOp->p1];
61778   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
61779   if( (pIn1->flags & MEM_Int)==0 ){
61780     if( pOp->p2==0 ){
61781       rc = SQLITE_MISMATCH;
61782       goto abort_due_to_error;
61783     }else{
61784       pc = pOp->p2 - 1;
61785     }
61786   }else{
61787     MemSetTypeFlag(pIn1, MEM_Int);
61788   }
61789   break;
61790 }
61791
61792 #ifndef SQLITE_OMIT_FLOATING_POINT
61793 /* Opcode: RealAffinity P1 * * * *
61794 **
61795 ** If register P1 holds an integer convert it to a real value.
61796 **
61797 ** This opcode is used when extracting information from a column that
61798 ** has REAL affinity.  Such column values may still be stored as
61799 ** integers, for space efficiency, but after extraction we want them
61800 ** to have only a real value.
61801 */
61802 case OP_RealAffinity: {                  /* in1 */
61803   pIn1 = &aMem[pOp->p1];
61804   if( pIn1->flags & MEM_Int ){
61805     sqlite3VdbeMemRealify(pIn1);
61806   }
61807   break;
61808 }
61809 #endif
61810
61811 #ifndef SQLITE_OMIT_CAST
61812 /* Opcode: ToText P1 * * * *
61813 **
61814 ** Force the value in register P1 to be text.
61815 ** If the value is numeric, convert it to a string using the
61816 ** equivalent of printf().  Blob values are unchanged and
61817 ** are afterwards simply interpreted as text.
61818 **
61819 ** A NULL value is not changed by this routine.  It remains NULL.
61820 */
61821 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
61822   pIn1 = &aMem[pOp->p1];
61823   memAboutToChange(p, pIn1);
61824   if( pIn1->flags & MEM_Null ) break;
61825   assert( MEM_Str==(MEM_Blob>>3) );
61826   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
61827   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
61828   rc = ExpandBlob(pIn1);
61829   assert( pIn1->flags & MEM_Str || db->mallocFailed );
61830   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
61831   UPDATE_MAX_BLOBSIZE(pIn1);
61832   break;
61833 }
61834
61835 /* Opcode: ToBlob P1 * * * *
61836 **
61837 ** Force the value in register P1 to be a BLOB.
61838 ** If the value is numeric, convert it to a string first.
61839 ** Strings are simply reinterpreted as blobs with no change
61840 ** to the underlying data.
61841 **
61842 ** A NULL value is not changed by this routine.  It remains NULL.
61843 */
61844 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
61845   pIn1 = &aMem[pOp->p1];
61846   if( pIn1->flags & MEM_Null ) break;
61847   if( (pIn1->flags & MEM_Blob)==0 ){
61848     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
61849     assert( pIn1->flags & MEM_Str || db->mallocFailed );
61850     MemSetTypeFlag(pIn1, MEM_Blob);
61851   }else{
61852     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
61853   }
61854   UPDATE_MAX_BLOBSIZE(pIn1);
61855   break;
61856 }
61857
61858 /* Opcode: ToNumeric P1 * * * *
61859 **
61860 ** Force the value in register P1 to be numeric (either an
61861 ** integer or a floating-point number.)
61862 ** If the value is text or blob, try to convert it to an using the
61863 ** equivalent of atoi() or atof() and store 0 if no such conversion 
61864 ** is possible.
61865 **
61866 ** A NULL value is not changed by this routine.  It remains NULL.
61867 */
61868 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
61869   pIn1 = &aMem[pOp->p1];
61870   sqlite3VdbeMemNumerify(pIn1);
61871   break;
61872 }
61873 #endif /* SQLITE_OMIT_CAST */
61874
61875 /* Opcode: ToInt P1 * * * *
61876 **
61877 ** Force the value in register P1 to be an integer.  If
61878 ** The value is currently a real number, drop its fractional part.
61879 ** If the value is text or blob, try to convert it to an integer using the
61880 ** equivalent of atoi() and store 0 if no such conversion is possible.
61881 **
61882 ** A NULL value is not changed by this routine.  It remains NULL.
61883 */
61884 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
61885   pIn1 = &aMem[pOp->p1];
61886   if( (pIn1->flags & MEM_Null)==0 ){
61887     sqlite3VdbeMemIntegerify(pIn1);
61888   }
61889   break;
61890 }
61891
61892 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
61893 /* Opcode: ToReal P1 * * * *
61894 **
61895 ** Force the value in register P1 to be a floating point number.
61896 ** If The value is currently an integer, convert it.
61897 ** If the value is text or blob, try to convert it to an integer using the
61898 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
61899 **
61900 ** A NULL value is not changed by this routine.  It remains NULL.
61901 */
61902 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
61903   pIn1 = &aMem[pOp->p1];
61904   memAboutToChange(p, pIn1);
61905   if( (pIn1->flags & MEM_Null)==0 ){
61906     sqlite3VdbeMemRealify(pIn1);
61907   }
61908   break;
61909 }
61910 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
61911
61912 /* Opcode: Lt P1 P2 P3 P4 P5
61913 **
61914 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
61915 ** jump to address P2.  
61916 **
61917 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
61918 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
61919 ** bit is clear then fall through if either operand is NULL.
61920 **
61921 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
61922 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
61923 ** to coerce both inputs according to this affinity before the
61924 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
61925 ** affinity is used. Note that the affinity conversions are stored
61926 ** back into the input registers P1 and P3.  So this opcode can cause
61927 ** persistent changes to registers P1 and P3.
61928 **
61929 ** Once any conversions have taken place, and neither value is NULL, 
61930 ** the values are compared. If both values are blobs then memcmp() is
61931 ** used to determine the results of the comparison.  If both values
61932 ** are text, then the appropriate collating function specified in
61933 ** P4 is  used to do the comparison.  If P4 is not specified then
61934 ** memcmp() is used to compare text string.  If both values are
61935 ** numeric, then a numeric comparison is used. If the two values
61936 ** are of different types, then numbers are considered less than
61937 ** strings and strings are considered less than blobs.
61938 **
61939 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
61940 ** store a boolean result (either 0, or 1, or NULL) in register P2.
61941 */
61942 /* Opcode: Ne P1 P2 P3 P4 P5
61943 **
61944 ** This works just like the Lt opcode except that the jump is taken if
61945 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
61946 ** additional information.
61947 **
61948 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
61949 ** true or false and is never NULL.  If both operands are NULL then the result
61950 ** of comparison is false.  If either operand is NULL then the result is true.
61951 ** If neither operand is NULL the the result is the same as it would be if
61952 ** the SQLITE_NULLEQ flag were omitted from P5.
61953 */
61954 /* Opcode: Eq P1 P2 P3 P4 P5
61955 **
61956 ** This works just like the Lt opcode except that the jump is taken if
61957 ** the operands in registers P1 and P3 are equal.
61958 ** See the Lt opcode for additional information.
61959 **
61960 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
61961 ** true or false and is never NULL.  If both operands are NULL then the result
61962 ** of comparison is true.  If either operand is NULL then the result is false.
61963 ** If neither operand is NULL the the result is the same as it would be if
61964 ** the SQLITE_NULLEQ flag were omitted from P5.
61965 */
61966 /* Opcode: Le P1 P2 P3 P4 P5
61967 **
61968 ** This works just like the Lt opcode except that the jump is taken if
61969 ** the content of register P3 is less than or equal to the content of
61970 ** register P1.  See the Lt opcode for additional information.
61971 */
61972 /* Opcode: Gt P1 P2 P3 P4 P5
61973 **
61974 ** This works just like the Lt opcode except that the jump is taken if
61975 ** the content of register P3 is greater than the content of
61976 ** register P1.  See the Lt opcode for additional information.
61977 */
61978 /* Opcode: Ge P1 P2 P3 P4 P5
61979 **
61980 ** This works just like the Lt opcode except that the jump is taken if
61981 ** the content of register P3 is greater than or equal to the content of
61982 ** register P1.  See the Lt opcode for additional information.
61983 */
61984 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
61985 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
61986 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
61987 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
61988 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
61989 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
61990 #if 0  /* local variables moved into u.ai */
61991   int res;            /* Result of the comparison of pIn1 against pIn3 */
61992   char affinity;      /* Affinity to use for comparison */
61993   u16 flags1;         /* Copy of initial value of pIn1->flags */
61994   u16 flags3;         /* Copy of initial value of pIn3->flags */
61995 #endif /* local variables moved into u.ai */
61996
61997   pIn1 = &aMem[pOp->p1];
61998   pIn3 = &aMem[pOp->p3];
61999   u.ai.flags1 = pIn1->flags;
62000   u.ai.flags3 = pIn3->flags;
62001   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
62002     /* One or both operands are NULL */
62003     if( pOp->p5 & SQLITE_NULLEQ ){
62004       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
62005       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
62006       ** or not both operands are null.
62007       */
62008       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
62009       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
62010     }else{
62011       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
62012       ** then the result is always NULL.
62013       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
62014       */
62015       if( pOp->p5 & SQLITE_STOREP2 ){
62016         pOut = &aMem[pOp->p2];
62017         MemSetTypeFlag(pOut, MEM_Null);
62018         REGISTER_TRACE(pOp->p2, pOut);
62019       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
62020         pc = pOp->p2-1;
62021       }
62022       break;
62023     }
62024   }else{
62025     /* Neither operand is NULL.  Do a comparison. */
62026     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
62027     if( u.ai.affinity ){
62028       applyAffinity(pIn1, u.ai.affinity, encoding);
62029       applyAffinity(pIn3, u.ai.affinity, encoding);
62030       if( db->mallocFailed ) goto no_mem;
62031     }
62032
62033     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
62034     ExpandBlob(pIn1);
62035     ExpandBlob(pIn3);
62036     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
62037   }
62038   switch( pOp->opcode ){
62039     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
62040     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
62041     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
62042     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
62043     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
62044     default:       u.ai.res = u.ai.res>=0;     break;
62045   }
62046
62047   if( pOp->p5 & SQLITE_STOREP2 ){
62048     pOut = &aMem[pOp->p2];
62049     memAboutToChange(p, pOut);
62050     MemSetTypeFlag(pOut, MEM_Int);
62051     pOut->u.i = u.ai.res;
62052     REGISTER_TRACE(pOp->p2, pOut);
62053   }else if( u.ai.res ){
62054     pc = pOp->p2-1;
62055   }
62056
62057   /* Undo any changes made by applyAffinity() to the input registers. */
62058   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
62059   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
62060   break;
62061 }
62062
62063 /* Opcode: Permutation * * * P4 *
62064 **
62065 ** Set the permutation used by the OP_Compare operator to be the array
62066 ** of integers in P4.
62067 **
62068 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
62069 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
62070 ** immediately prior to the OP_Compare.
62071 */
62072 case OP_Permutation: {
62073   assert( pOp->p4type==P4_INTARRAY );
62074   assert( pOp->p4.ai );
62075   aPermute = pOp->p4.ai;
62076   break;
62077 }
62078
62079 /* Opcode: Compare P1 P2 P3 P4 *
62080 **
62081 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
62082 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
62083 ** the comparison for use by the next OP_Jump instruct.
62084 **
62085 ** P4 is a KeyInfo structure that defines collating sequences and sort
62086 ** orders for the comparison.  The permutation applies to registers
62087 ** only.  The KeyInfo elements are used sequentially.
62088 **
62089 ** The comparison is a sort comparison, so NULLs compare equal,
62090 ** NULLs are less than numbers, numbers are less than strings,
62091 ** and strings are less than blobs.
62092 */
62093 case OP_Compare: {
62094 #if 0  /* local variables moved into u.aj */
62095   int n;
62096   int i;
62097   int p1;
62098   int p2;
62099   const KeyInfo *pKeyInfo;
62100   int idx;
62101   CollSeq *pColl;    /* Collating sequence to use on this term */
62102   int bRev;          /* True for DESCENDING sort order */
62103 #endif /* local variables moved into u.aj */
62104
62105   u.aj.n = pOp->p3;
62106   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
62107   assert( u.aj.n>0 );
62108   assert( u.aj.pKeyInfo!=0 );
62109   u.aj.p1 = pOp->p1;
62110   u.aj.p2 = pOp->p2;
62111 #if SQLITE_DEBUG
62112   if( aPermute ){
62113     int k, mx = 0;
62114     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
62115     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
62116     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
62117   }else{
62118     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
62119     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
62120   }
62121 #endif /* SQLITE_DEBUG */
62122   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
62123     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
62124     assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
62125     assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
62126     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
62127     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
62128     assert( u.aj.i<u.aj.pKeyInfo->nField );
62129     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
62130     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
62131     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
62132     if( iCompare ){
62133       if( u.aj.bRev ) iCompare = -iCompare;
62134       break;
62135     }
62136   }
62137   aPermute = 0;
62138   break;
62139 }
62140
62141 /* Opcode: Jump P1 P2 P3 * *
62142 **
62143 ** Jump to the instruction at address P1, P2, or P3 depending on whether
62144 ** in the most recent OP_Compare instruction the P1 vector was less than
62145 ** equal to, or greater than the P2 vector, respectively.
62146 */
62147 case OP_Jump: {             /* jump */
62148   if( iCompare<0 ){
62149     pc = pOp->p1 - 1;
62150   }else if( iCompare==0 ){
62151     pc = pOp->p2 - 1;
62152   }else{
62153     pc = pOp->p3 - 1;
62154   }
62155   break;
62156 }
62157
62158 /* Opcode: And P1 P2 P3 * *
62159 **
62160 ** Take the logical AND of the values in registers P1 and P2 and
62161 ** write the result into register P3.
62162 **
62163 ** If either P1 or P2 is 0 (false) then the result is 0 even if
62164 ** the other input is NULL.  A NULL and true or two NULLs give
62165 ** a NULL output.
62166 */
62167 /* Opcode: Or P1 P2 P3 * *
62168 **
62169 ** Take the logical OR of the values in register P1 and P2 and
62170 ** store the answer in register P3.
62171 **
62172 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
62173 ** even if the other input is NULL.  A NULL and false or two NULLs
62174 ** give a NULL output.
62175 */
62176 case OP_And:              /* same as TK_AND, in1, in2, out3 */
62177 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
62178 #if 0  /* local variables moved into u.ak */
62179   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62180   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
62181 #endif /* local variables moved into u.ak */
62182
62183   pIn1 = &aMem[pOp->p1];
62184   if( pIn1->flags & MEM_Null ){
62185     u.ak.v1 = 2;
62186   }else{
62187     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
62188   }
62189   pIn2 = &aMem[pOp->p2];
62190   if( pIn2->flags & MEM_Null ){
62191     u.ak.v2 = 2;
62192   }else{
62193     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
62194   }
62195   if( pOp->opcode==OP_And ){
62196     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
62197     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
62198   }else{
62199     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
62200     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
62201   }
62202   pOut = &aMem[pOp->p3];
62203   if( u.ak.v1==2 ){
62204     MemSetTypeFlag(pOut, MEM_Null);
62205   }else{
62206     pOut->u.i = u.ak.v1;
62207     MemSetTypeFlag(pOut, MEM_Int);
62208   }
62209   break;
62210 }
62211
62212 /* Opcode: Not P1 P2 * * *
62213 **
62214 ** Interpret the value in register P1 as a boolean value.  Store the
62215 ** boolean complement in register P2.  If the value in register P1 is 
62216 ** NULL, then a NULL is stored in P2.
62217 */
62218 case OP_Not: {                /* same as TK_NOT, in1, out2 */
62219   pIn1 = &aMem[pOp->p1];
62220   pOut = &aMem[pOp->p2];
62221   if( pIn1->flags & MEM_Null ){
62222     sqlite3VdbeMemSetNull(pOut);
62223   }else{
62224     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
62225   }
62226   break;
62227 }
62228
62229 /* Opcode: BitNot P1 P2 * * *
62230 **
62231 ** Interpret the content of register P1 as an integer.  Store the
62232 ** ones-complement of the P1 value into register P2.  If P1 holds
62233 ** a NULL then store a NULL in P2.
62234 */
62235 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
62236   pIn1 = &aMem[pOp->p1];
62237   pOut = &aMem[pOp->p2];
62238   if( pIn1->flags & MEM_Null ){
62239     sqlite3VdbeMemSetNull(pOut);
62240   }else{
62241     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
62242   }
62243   break;
62244 }
62245
62246 /* Opcode: If P1 P2 P3 * *
62247 **
62248 ** Jump to P2 if the value in register P1 is true.  The value is
62249 ** is considered true if it is numeric and non-zero.  If the value
62250 ** in P1 is NULL then take the jump if P3 is true.
62251 */
62252 /* Opcode: IfNot P1 P2 P3 * *
62253 **
62254 ** Jump to P2 if the value in register P1 is False.  The value is
62255 ** is considered true if it has a numeric value of zero.  If the value
62256 ** in P1 is NULL then take the jump if P3 is true.
62257 */
62258 case OP_If:                 /* jump, in1 */
62259 case OP_IfNot: {            /* jump, in1 */
62260 #if 0  /* local variables moved into u.al */
62261   int c;
62262 #endif /* local variables moved into u.al */
62263   pIn1 = &aMem[pOp->p1];
62264   if( pIn1->flags & MEM_Null ){
62265     u.al.c = pOp->p3;
62266   }else{
62267 #ifdef SQLITE_OMIT_FLOATING_POINT
62268     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
62269 #else
62270     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
62271 #endif
62272     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
62273   }
62274   if( u.al.c ){
62275     pc = pOp->p2-1;
62276   }
62277   break;
62278 }
62279
62280 /* Opcode: IsNull P1 P2 * * *
62281 **
62282 ** Jump to P2 if the value in register P1 is NULL.
62283 */
62284 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
62285   pIn1 = &aMem[pOp->p1];
62286   if( (pIn1->flags & MEM_Null)!=0 ){
62287     pc = pOp->p2 - 1;
62288   }
62289   break;
62290 }
62291
62292 /* Opcode: NotNull P1 P2 * * *
62293 **
62294 ** Jump to P2 if the value in register P1 is not NULL.  
62295 */
62296 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
62297   pIn1 = &aMem[pOp->p1];
62298   if( (pIn1->flags & MEM_Null)==0 ){
62299     pc = pOp->p2 - 1;
62300   }
62301   break;
62302 }
62303
62304 /* Opcode: Column P1 P2 P3 P4 P5
62305 **
62306 ** Interpret the data that cursor P1 points to as a structure built using
62307 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
62308 ** information about the format of the data.)  Extract the P2-th column
62309 ** from this record.  If there are less that (P2+1) 
62310 ** values in the record, extract a NULL.
62311 **
62312 ** The value extracted is stored in register P3.
62313 **
62314 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
62315 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
62316 ** the result.
62317 **
62318 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
62319 ** then the cache of the cursor is reset prior to extracting the column.
62320 ** The first OP_Column against a pseudo-table after the value of the content
62321 ** register has changed should have this bit set.
62322 */
62323 case OP_Column: {
62324 #if 0  /* local variables moved into u.am */
62325   u32 payloadSize;   /* Number of bytes in the record */
62326   i64 payloadSize64; /* Number of bytes in the record */
62327   int p1;            /* P1 value of the opcode */
62328   int p2;            /* column number to retrieve */
62329   VdbeCursor *pC;    /* The VDBE cursor */
62330   char *zRec;        /* Pointer to complete record-data */
62331   BtCursor *pCrsr;   /* The BTree cursor */
62332   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
62333   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
62334   int nField;        /* number of fields in the record */
62335   int len;           /* The length of the serialized data for the column */
62336   int i;             /* Loop counter */
62337   char *zData;       /* Part of the record being decoded */
62338   Mem *pDest;        /* Where to write the extracted value */
62339   Mem sMem;          /* For storing the record being decoded */
62340   u8 *zIdx;          /* Index into header */
62341   u8 *zEndHdr;       /* Pointer to first byte after the header */
62342   u32 offset;        /* Offset into the data */
62343   u32 szField;       /* Number of bytes in the content of a field */
62344   int szHdr;         /* Size of the header size field at start of record */
62345   int avail;         /* Number of bytes of available data */
62346   Mem *pReg;         /* PseudoTable input register */
62347 #endif /* local variables moved into u.am */
62348
62349
62350   u.am.p1 = pOp->p1;
62351   u.am.p2 = pOp->p2;
62352   u.am.pC = 0;
62353   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
62354   assert( u.am.p1<p->nCursor );
62355   assert( pOp->p3>0 && pOp->p3<=p->nMem );
62356   u.am.pDest = &aMem[pOp->p3];
62357   memAboutToChange(p, u.am.pDest);
62358   MemSetTypeFlag(u.am.pDest, MEM_Null);
62359   u.am.zRec = 0;
62360
62361   /* This block sets the variable u.am.payloadSize to be the total number of
62362   ** bytes in the record.
62363   **
62364   ** u.am.zRec is set to be the complete text of the record if it is available.
62365   ** The complete record text is always available for pseudo-tables
62366   ** If the record is stored in a cursor, the complete record text
62367   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
62368   ** If the data is unavailable,  u.am.zRec is set to NULL.
62369   **
62370   ** We also compute the number of columns in the record.  For cursors,
62371   ** the number of columns is stored in the VdbeCursor.nField element.
62372   */
62373   u.am.pC = p->apCsr[u.am.p1];
62374   assert( u.am.pC!=0 );
62375 #ifndef SQLITE_OMIT_VIRTUALTABLE
62376   assert( u.am.pC->pVtabCursor==0 );
62377 #endif
62378   u.am.pCrsr = u.am.pC->pCursor;
62379   if( u.am.pCrsr!=0 ){
62380     /* The record is stored in a B-Tree */
62381     rc = sqlite3VdbeCursorMoveto(u.am.pC);
62382     if( rc ) goto abort_due_to_error;
62383     if( u.am.pC->nullRow ){
62384       u.am.payloadSize = 0;
62385     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
62386       u.am.payloadSize = u.am.pC->payloadSize;
62387       u.am.zRec = (char*)u.am.pC->aRow;
62388     }else if( u.am.pC->isIndex ){
62389       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
62390       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
62391       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
62392       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
62393       ** payload size, so it is impossible for u.am.payloadSize64 to be
62394       ** larger than 32 bits. */
62395       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
62396       u.am.payloadSize = (u32)u.am.payloadSize64;
62397     }else{
62398       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
62399       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
62400       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
62401     }
62402   }else if( u.am.pC->pseudoTableReg>0 ){
62403     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
62404     assert( u.am.pReg->flags & MEM_Blob );
62405     assert( memIsValid(u.am.pReg) );
62406     u.am.payloadSize = u.am.pReg->n;
62407     u.am.zRec = u.am.pReg->z;
62408     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
62409     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
62410   }else{
62411     /* Consider the row to be NULL */
62412     u.am.payloadSize = 0;
62413   }
62414
62415   /* If u.am.payloadSize is 0, then just store a NULL */
62416   if( u.am.payloadSize==0 ){
62417     assert( u.am.pDest->flags&MEM_Null );
62418     goto op_column_out;
62419   }
62420   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
62421   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
62422     goto too_big;
62423   }
62424
62425   u.am.nField = u.am.pC->nField;
62426   assert( u.am.p2<u.am.nField );
62427
62428   /* Read and parse the table header.  Store the results of the parse
62429   ** into the record header cache fields of the cursor.
62430   */
62431   u.am.aType = u.am.pC->aType;
62432   if( u.am.pC->cacheStatus==p->cacheCtr ){
62433     u.am.aOffset = u.am.pC->aOffset;
62434   }else{
62435     assert(u.am.aType);
62436     u.am.avail = 0;
62437     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
62438     u.am.pC->payloadSize = u.am.payloadSize;
62439     u.am.pC->cacheStatus = p->cacheCtr;
62440
62441     /* Figure out how many bytes are in the header */
62442     if( u.am.zRec ){
62443       u.am.zData = u.am.zRec;
62444     }else{
62445       if( u.am.pC->isIndex ){
62446         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
62447       }else{
62448         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
62449       }
62450       /* If KeyFetch()/DataFetch() managed to get the entire payload,
62451       ** save the payload in the u.am.pC->aRow cache.  That will save us from
62452       ** having to make additional calls to fetch the content portion of
62453       ** the record.
62454       */
62455       assert( u.am.avail>=0 );
62456       if( u.am.payloadSize <= (u32)u.am.avail ){
62457         u.am.zRec = u.am.zData;
62458         u.am.pC->aRow = (u8*)u.am.zData;
62459       }else{
62460         u.am.pC->aRow = 0;
62461       }
62462     }
62463     /* The following assert is true in all cases accept when
62464     ** the database file has been corrupted externally.
62465     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
62466     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
62467
62468     /* Make sure a corrupt database has not given us an oversize header.
62469     ** Do this now to avoid an oversize memory allocation.
62470     **
62471     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
62472     ** types use so much data space that there can only be 4096 and 32 of
62473     ** them, respectively.  So the maximum header length results from a
62474     ** 3-byte type for each of the maximum of 32768 columns plus three
62475     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
62476     */
62477     if( u.am.offset > 98307 ){
62478       rc = SQLITE_CORRUPT_BKPT;
62479       goto op_column_out;
62480     }
62481
62482     /* Compute in u.am.len the number of bytes of data we need to read in order
62483     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
62484     ** u.am.nField might be significantly less than the true number of columns
62485     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
62486     ** We want to minimize u.am.len in order to limit the size of the memory
62487     ** allocation, especially if a corrupt database file has caused u.am.offset
62488     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
62489     ** still exceed Robson memory allocation limits on some configurations.
62490     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
62491     ** will likely be much smaller since u.am.nField will likely be less than
62492     ** 20 or so.  This insures that Robson memory allocation limits are
62493     ** not exceeded even for corrupt database files.
62494     */
62495     u.am.len = u.am.nField*5 + 3;
62496     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
62497
62498     /* The KeyFetch() or DataFetch() above are fast and will get the entire
62499     ** record header in most cases.  But they will fail to get the complete
62500     ** record header if the record header does not fit on a single page
62501     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
62502     ** acquire the complete header text.
62503     */
62504     if( !u.am.zRec && u.am.avail<u.am.len ){
62505       u.am.sMem.flags = 0;
62506       u.am.sMem.db = 0;
62507       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
62508       if( rc!=SQLITE_OK ){
62509         goto op_column_out;
62510       }
62511       u.am.zData = u.am.sMem.z;
62512     }
62513     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
62514     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
62515
62516     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
62517     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
62518     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
62519     ** of the record to the start of the data for the u.am.i-th column
62520     */
62521     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
62522       if( u.am.zIdx<u.am.zEndHdr ){
62523         u.am.aOffset[u.am.i] = u.am.offset;
62524         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
62525         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
62526         u.am.offset += u.am.szField;
62527         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
62528           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
62529           break;
62530         }
62531       }else{
62532         /* If u.am.i is less that u.am.nField, then there are less fields in this
62533         ** record than SetNumColumns indicated there are columns in the
62534         ** table. Set the u.am.offset for any extra columns not present in
62535         ** the record to 0. This tells code below to store a NULL
62536         ** instead of deserializing a value from the record.
62537         */
62538         u.am.aOffset[u.am.i] = 0;
62539       }
62540     }
62541     sqlite3VdbeMemRelease(&u.am.sMem);
62542     u.am.sMem.flags = MEM_Null;
62543
62544     /* If we have read more header data than was contained in the header,
62545     ** or if the end of the last field appears to be past the end of the
62546     ** record, or if the end of the last field appears to be before the end
62547     ** of the record (when all fields present), then we must be dealing
62548     ** with a corrupt database.
62549     */
62550     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
62551          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
62552       rc = SQLITE_CORRUPT_BKPT;
62553       goto op_column_out;
62554     }
62555   }
62556
62557   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
62558   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
62559   ** then there are not enough fields in the record to satisfy the
62560   ** request.  In this case, set the value NULL or to P4 if P4 is
62561   ** a pointer to a Mem object.
62562   */
62563   if( u.am.aOffset[u.am.p2] ){
62564     assert( rc==SQLITE_OK );
62565     if( u.am.zRec ){
62566       sqlite3VdbeMemReleaseExternal(u.am.pDest);
62567       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
62568     }else{
62569       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
62570       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
62571       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
62572       if( rc!=SQLITE_OK ){
62573         goto op_column_out;
62574       }
62575       u.am.zData = u.am.sMem.z;
62576       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
62577     }
62578     u.am.pDest->enc = encoding;
62579   }else{
62580     if( pOp->p4type==P4_MEM ){
62581       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
62582     }else{
62583       assert( u.am.pDest->flags&MEM_Null );
62584     }
62585   }
62586
62587   /* If we dynamically allocated space to hold the data (in the
62588   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
62589   ** dynamically allocated space over to the u.am.pDest structure.
62590   ** This prevents a memory copy.
62591   */
62592   if( u.am.sMem.zMalloc ){
62593     assert( u.am.sMem.z==u.am.sMem.zMalloc );
62594     assert( !(u.am.pDest->flags & MEM_Dyn) );
62595     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
62596     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
62597     u.am.pDest->flags |= MEM_Term;
62598     u.am.pDest->z = u.am.sMem.z;
62599     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
62600   }
62601
62602   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
62603
62604 op_column_out:
62605   UPDATE_MAX_BLOBSIZE(u.am.pDest);
62606   REGISTER_TRACE(pOp->p3, u.am.pDest);
62607   break;
62608 }
62609
62610 /* Opcode: Affinity P1 P2 * P4 *
62611 **
62612 ** Apply affinities to a range of P2 registers starting with P1.
62613 **
62614 ** P4 is a string that is P2 characters long. The nth character of the
62615 ** string indicates the column affinity that should be used for the nth
62616 ** memory cell in the range.
62617 */
62618 case OP_Affinity: {
62619 #if 0  /* local variables moved into u.an */
62620   const char *zAffinity;   /* The affinity to be applied */
62621   char cAff;               /* A single character of affinity */
62622 #endif /* local variables moved into u.an */
62623
62624   u.an.zAffinity = pOp->p4.z;
62625   assert( u.an.zAffinity!=0 );
62626   assert( u.an.zAffinity[pOp->p2]==0 );
62627   pIn1 = &aMem[pOp->p1];
62628   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
62629     assert( pIn1 <= &p->aMem[p->nMem] );
62630     assert( memIsValid(pIn1) );
62631     ExpandBlob(pIn1);
62632     applyAffinity(pIn1, u.an.cAff, encoding);
62633     pIn1++;
62634   }
62635   break;
62636 }
62637
62638 /* Opcode: MakeRecord P1 P2 P3 P4 *
62639 **
62640 ** Convert P2 registers beginning with P1 into the [record format]
62641 ** use as a data record in a database table or as a key
62642 ** in an index.  The OP_Column opcode can decode the record later.
62643 **
62644 ** P4 may be a string that is P2 characters long.  The nth character of the
62645 ** string indicates the column affinity that should be used for the nth
62646 ** field of the index key.
62647 **
62648 ** The mapping from character to affinity is given by the SQLITE_AFF_
62649 ** macros defined in sqliteInt.h.
62650 **
62651 ** If P4 is NULL then all index fields have the affinity NONE.
62652 */
62653 case OP_MakeRecord: {
62654 #if 0  /* local variables moved into u.ao */
62655   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
62656   Mem *pRec;             /* The new record */
62657   u64 nData;             /* Number of bytes of data space */
62658   int nHdr;              /* Number of bytes of header space */
62659   i64 nByte;             /* Data space required for this record */
62660   int nZero;             /* Number of zero bytes at the end of the record */
62661   int nVarint;           /* Number of bytes in a varint */
62662   u32 serial_type;       /* Type field */
62663   Mem *pData0;           /* First field to be combined into the record */
62664   Mem *pLast;            /* Last field of the record */
62665   int nField;            /* Number of fields in the record */
62666   char *zAffinity;       /* The affinity string for the record */
62667   int file_format;       /* File format to use for encoding */
62668   int i;                 /* Space used in zNewRecord[] */
62669   int len;               /* Length of a field */
62670 #endif /* local variables moved into u.ao */
62671
62672   /* Assuming the record contains N fields, the record format looks
62673   ** like this:
62674   **
62675   ** ------------------------------------------------------------------------
62676   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
62677   ** ------------------------------------------------------------------------
62678   **
62679   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
62680   ** and so froth.
62681   **
62682   ** Each type field is a varint representing the serial type of the
62683   ** corresponding data element (see sqlite3VdbeSerialType()). The
62684   ** hdr-size field is also a varint which is the offset from the beginning
62685   ** of the record to data0.
62686   */
62687   u.ao.nData = 0;         /* Number of bytes of data space */
62688   u.ao.nHdr = 0;          /* Number of bytes of header space */
62689   u.ao.nByte = 0;         /* Data space required for this record */
62690   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
62691   u.ao.nField = pOp->p1;
62692   u.ao.zAffinity = pOp->p4.z;
62693   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
62694   u.ao.pData0 = &aMem[u.ao.nField];
62695   u.ao.nField = pOp->p2;
62696   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
62697   u.ao.file_format = p->minWriteFileFormat;
62698
62699   /* Identify the output register */
62700   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
62701   pOut = &aMem[pOp->p3];
62702   memAboutToChange(p, pOut);
62703
62704   /* Loop through the elements that will make up the record to figure
62705   ** out how much space is required for the new record.
62706   */
62707   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
62708     assert( memIsValid(u.ao.pRec) );
62709     if( u.ao.zAffinity ){
62710       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
62711     }
62712     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
62713       sqlite3VdbeMemExpandBlob(u.ao.pRec);
62714     }
62715     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
62716     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
62717     u.ao.nData += u.ao.len;
62718     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
62719     if( u.ao.pRec->flags & MEM_Zero ){
62720       /* Only pure zero-filled BLOBs can be input to this Opcode.
62721       ** We do not allow blobs with a prefix and a zero-filled tail. */
62722       u.ao.nZero += u.ao.pRec->u.nZero;
62723     }else if( u.ao.len ){
62724       u.ao.nZero = 0;
62725     }
62726   }
62727
62728   /* Add the initial header varint and total the size */
62729   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
62730   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
62731     u.ao.nHdr++;
62732   }
62733   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
62734   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
62735     goto too_big;
62736   }
62737
62738   /* Make sure the output register has a buffer large enough to store
62739   ** the new record. The output register (pOp->p3) is not allowed to
62740   ** be one of the input registers (because the following call to
62741   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
62742   */
62743   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
62744     goto no_mem;
62745   }
62746   u.ao.zNewRecord = (u8 *)pOut->z;
62747
62748   /* Write the record */
62749   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
62750   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
62751     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
62752     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
62753   }
62754   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
62755     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
62756   }
62757   assert( u.ao.i==u.ao.nByte );
62758
62759   assert( pOp->p3>0 && pOp->p3<=p->nMem );
62760   pOut->n = (int)u.ao.nByte;
62761   pOut->flags = MEM_Blob | MEM_Dyn;
62762   pOut->xDel = 0;
62763   if( u.ao.nZero ){
62764     pOut->u.nZero = u.ao.nZero;
62765     pOut->flags |= MEM_Zero;
62766   }
62767   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
62768   REGISTER_TRACE(pOp->p3, pOut);
62769   UPDATE_MAX_BLOBSIZE(pOut);
62770   break;
62771 }
62772
62773 /* Opcode: Count P1 P2 * * *
62774 **
62775 ** Store the number of entries (an integer value) in the table or index 
62776 ** opened by cursor P1 in register P2
62777 */
62778 #ifndef SQLITE_OMIT_BTREECOUNT
62779 case OP_Count: {         /* out2-prerelease */
62780 #if 0  /* local variables moved into u.ap */
62781   i64 nEntry;
62782   BtCursor *pCrsr;
62783 #endif /* local variables moved into u.ap */
62784
62785   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
62786   if( u.ap.pCrsr ){
62787     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
62788   }else{
62789     u.ap.nEntry = 0;
62790   }
62791   pOut->u.i = u.ap.nEntry;
62792   break;
62793 }
62794 #endif
62795
62796 /* Opcode: Savepoint P1 * * P4 *
62797 **
62798 ** Open, release or rollback the savepoint named by parameter P4, depending
62799 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
62800 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
62801 */
62802 case OP_Savepoint: {
62803 #if 0  /* local variables moved into u.aq */
62804   int p1;                         /* Value of P1 operand */
62805   char *zName;                    /* Name of savepoint */
62806   int nName;
62807   Savepoint *pNew;
62808   Savepoint *pSavepoint;
62809   Savepoint *pTmp;
62810   int iSavepoint;
62811   int ii;
62812 #endif /* local variables moved into u.aq */
62813
62814   u.aq.p1 = pOp->p1;
62815   u.aq.zName = pOp->p4.z;
62816
62817   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
62818   ** transaction, then there cannot be any savepoints.
62819   */
62820   assert( db->pSavepoint==0 || db->autoCommit==0 );
62821   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
62822   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
62823   assert( checkSavepointCount(db) );
62824
62825   if( u.aq.p1==SAVEPOINT_BEGIN ){
62826     if( db->writeVdbeCnt>0 ){
62827       /* A new savepoint cannot be created if there are active write
62828       ** statements (i.e. open read/write incremental blob handles).
62829       */
62830       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
62831         "SQL statements in progress");
62832       rc = SQLITE_BUSY;
62833     }else{
62834       u.aq.nName = sqlite3Strlen30(u.aq.zName);
62835
62836       /* Create a new savepoint structure. */
62837       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
62838       if( u.aq.pNew ){
62839         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
62840         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
62841
62842         /* If there is no open transaction, then mark this as a special
62843         ** "transaction savepoint". */
62844         if( db->autoCommit ){
62845           db->autoCommit = 0;
62846           db->isTransactionSavepoint = 1;
62847         }else{
62848           db->nSavepoint++;
62849         }
62850
62851         /* Link the new savepoint into the database handle's list. */
62852         u.aq.pNew->pNext = db->pSavepoint;
62853         db->pSavepoint = u.aq.pNew;
62854         u.aq.pNew->nDeferredCons = db->nDeferredCons;
62855       }
62856     }
62857   }else{
62858     u.aq.iSavepoint = 0;
62859
62860     /* Find the named savepoint. If there is no such savepoint, then an
62861     ** an error is returned to the user.  */
62862     for(
62863       u.aq.pSavepoint = db->pSavepoint;
62864       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
62865       u.aq.pSavepoint = u.aq.pSavepoint->pNext
62866     ){
62867       u.aq.iSavepoint++;
62868     }
62869     if( !u.aq.pSavepoint ){
62870       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
62871       rc = SQLITE_ERROR;
62872     }else if(
62873         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
62874     ){
62875       /* It is not possible to release (commit) a savepoint if there are
62876       ** active write statements. It is not possible to rollback a savepoint
62877       ** if there are any active statements at all.
62878       */
62879       sqlite3SetString(&p->zErrMsg, db,
62880         "cannot %s savepoint - SQL statements in progress",
62881         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
62882       );
62883       rc = SQLITE_BUSY;
62884     }else{
62885
62886       /* Determine whether or not this is a transaction savepoint. If so,
62887       ** and this is a RELEASE command, then the current transaction
62888       ** is committed.
62889       */
62890       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
62891       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
62892         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
62893           goto vdbe_return;
62894         }
62895         db->autoCommit = 1;
62896         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
62897           p->pc = pc;
62898           db->autoCommit = 0;
62899           p->rc = rc = SQLITE_BUSY;
62900           goto vdbe_return;
62901         }
62902         db->isTransactionSavepoint = 0;
62903         rc = p->rc;
62904       }else{
62905         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
62906         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
62907           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
62908           if( rc!=SQLITE_OK ){
62909             goto abort_due_to_error;
62910           }
62911         }
62912         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
62913           sqlite3ExpirePreparedStatements(db);
62914           sqlite3ResetInternalSchema(db, 0);
62915           db->flags = (db->flags | SQLITE_InternChanges);
62916         }
62917       }
62918
62919       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
62920       ** savepoints nested inside of the savepoint being operated on. */
62921       while( db->pSavepoint!=u.aq.pSavepoint ){
62922         u.aq.pTmp = db->pSavepoint;
62923         db->pSavepoint = u.aq.pTmp->pNext;
62924         sqlite3DbFree(db, u.aq.pTmp);
62925         db->nSavepoint--;
62926       }
62927
62928       /* If it is a RELEASE, then destroy the savepoint being operated on
62929       ** too. If it is a ROLLBACK TO, then set the number of deferred
62930       ** constraint violations present in the database to the value stored
62931       ** when the savepoint was created.  */
62932       if( u.aq.p1==SAVEPOINT_RELEASE ){
62933         assert( u.aq.pSavepoint==db->pSavepoint );
62934         db->pSavepoint = u.aq.pSavepoint->pNext;
62935         sqlite3DbFree(db, u.aq.pSavepoint);
62936         if( !isTransaction ){
62937           db->nSavepoint--;
62938         }
62939       }else{
62940         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
62941       }
62942     }
62943   }
62944
62945   break;
62946 }
62947
62948 /* Opcode: AutoCommit P1 P2 * * *
62949 **
62950 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
62951 ** back any currently active btree transactions. If there are any active
62952 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
62953 ** there are active writing VMs or active VMs that use shared cache.
62954 **
62955 ** This instruction causes the VM to halt.
62956 */
62957 case OP_AutoCommit: {
62958 #if 0  /* local variables moved into u.ar */
62959   int desiredAutoCommit;
62960   int iRollback;
62961   int turnOnAC;
62962 #endif /* local variables moved into u.ar */
62963
62964   u.ar.desiredAutoCommit = pOp->p1;
62965   u.ar.iRollback = pOp->p2;
62966   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
62967   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
62968   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
62969   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
62970
62971   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
62972     /* If this instruction implements a ROLLBACK and other VMs are
62973     ** still running, and a transaction is active, return an error indicating
62974     ** that the other VMs must complete first.
62975     */
62976     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
62977         "SQL statements in progress");
62978     rc = SQLITE_BUSY;
62979   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
62980     /* If this instruction implements a COMMIT and other VMs are writing
62981     ** return an error indicating that the other VMs must complete first.
62982     */
62983     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
62984         "SQL statements in progress");
62985     rc = SQLITE_BUSY;
62986   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
62987     if( u.ar.iRollback ){
62988       assert( u.ar.desiredAutoCommit==1 );
62989       sqlite3RollbackAll(db);
62990       db->autoCommit = 1;
62991     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
62992       goto vdbe_return;
62993     }else{
62994       db->autoCommit = (u8)u.ar.desiredAutoCommit;
62995       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
62996         p->pc = pc;
62997         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
62998         p->rc = rc = SQLITE_BUSY;
62999         goto vdbe_return;
63000       }
63001     }
63002     assert( db->nStatement==0 );
63003     sqlite3CloseSavepoints(db);
63004     if( p->rc==SQLITE_OK ){
63005       rc = SQLITE_DONE;
63006     }else{
63007       rc = SQLITE_ERROR;
63008     }
63009     goto vdbe_return;
63010   }else{
63011     sqlite3SetString(&p->zErrMsg, db,
63012         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
63013         (u.ar.iRollback)?"cannot rollback - no transaction is active":
63014                    "cannot commit - no transaction is active"));
63015
63016     rc = SQLITE_ERROR;
63017   }
63018   break;
63019 }
63020
63021 /* Opcode: Transaction P1 P2 * * *
63022 **
63023 ** Begin a transaction.  The transaction ends when a Commit or Rollback
63024 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
63025 ** transaction might also be rolled back if an error is encountered.
63026 **
63027 ** P1 is the index of the database file on which the transaction is
63028 ** started.  Index 0 is the main database file and index 1 is the
63029 ** file used for temporary tables.  Indices of 2 or more are used for
63030 ** attached databases.
63031 **
63032 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
63033 ** obtained on the database file when a write-transaction is started.  No
63034 ** other process can start another write transaction while this transaction is
63035 ** underway.  Starting a write transaction also creates a rollback journal. A
63036 ** write transaction must be started before any changes can be made to the
63037 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
63038 ** on the file.
63039 **
63040 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
63041 ** true (this flag is set if the Vdbe may modify more than one row and may
63042 ** throw an ABORT exception), a statement transaction may also be opened.
63043 ** More specifically, a statement transaction is opened iff the database
63044 ** connection is currently not in autocommit mode, or if there are other
63045 ** active statements. A statement transaction allows the affects of this
63046 ** VDBE to be rolled back after an error without having to roll back the
63047 ** entire transaction. If no error is encountered, the statement transaction
63048 ** will automatically commit when the VDBE halts.
63049 **
63050 ** If P2 is zero, then a read-lock is obtained on the database file.
63051 */
63052 case OP_Transaction: {
63053 #if 0  /* local variables moved into u.as */
63054   Btree *pBt;
63055 #endif /* local variables moved into u.as */
63056
63057   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63058   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63059   u.as.pBt = db->aDb[pOp->p1].pBt;
63060
63061   if( u.as.pBt ){
63062     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
63063     if( rc==SQLITE_BUSY ){
63064       p->pc = pc;
63065       p->rc = rc = SQLITE_BUSY;
63066       goto vdbe_return;
63067     }
63068     if( rc!=SQLITE_OK ){
63069       goto abort_due_to_error;
63070     }
63071
63072     if( pOp->p2 && p->usesStmtJournal
63073      && (db->autoCommit==0 || db->activeVdbeCnt>1)
63074     ){
63075       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
63076       if( p->iStatement==0 ){
63077         assert( db->nStatement>=0 && db->nSavepoint>=0 );
63078         db->nStatement++;
63079         p->iStatement = db->nSavepoint + db->nStatement;
63080       }
63081       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
63082
63083       /* Store the current value of the database handles deferred constraint
63084       ** counter. If the statement transaction needs to be rolled back,
63085       ** the value of this counter needs to be restored too.  */
63086       p->nStmtDefCons = db->nDeferredCons;
63087     }
63088   }
63089   break;
63090 }
63091
63092 /* Opcode: ReadCookie P1 P2 P3 * *
63093 **
63094 ** Read cookie number P3 from database P1 and write it into register P2.
63095 ** P3==1 is the schema version.  P3==2 is the database format.
63096 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
63097 ** the main database file and P1==1 is the database file used to store
63098 ** temporary tables.
63099 **
63100 ** There must be a read-lock on the database (either a transaction
63101 ** must be started or there must be an open cursor) before
63102 ** executing this instruction.
63103 */
63104 case OP_ReadCookie: {               /* out2-prerelease */
63105 #if 0  /* local variables moved into u.at */
63106   int iMeta;
63107   int iDb;
63108   int iCookie;
63109 #endif /* local variables moved into u.at */
63110
63111   u.at.iDb = pOp->p1;
63112   u.at.iCookie = pOp->p3;
63113   assert( pOp->p3<SQLITE_N_BTREE_META );
63114   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
63115   assert( db->aDb[u.at.iDb].pBt!=0 );
63116   assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
63117
63118   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
63119   pOut->u.i = u.at.iMeta;
63120   break;
63121 }
63122
63123 /* Opcode: SetCookie P1 P2 P3 * *
63124 **
63125 ** Write the content of register P3 (interpreted as an integer)
63126 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
63127 ** P2==2 is the database format. P2==3 is the recommended pager cache 
63128 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
63129 ** database file used to store temporary tables.
63130 **
63131 ** A transaction must be started before executing this opcode.
63132 */
63133 case OP_SetCookie: {       /* in3 */
63134 #if 0  /* local variables moved into u.au */
63135   Db *pDb;
63136 #endif /* local variables moved into u.au */
63137   assert( pOp->p2<SQLITE_N_BTREE_META );
63138   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63139   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63140   u.au.pDb = &db->aDb[pOp->p1];
63141   assert( u.au.pDb->pBt!=0 );
63142   pIn3 = &aMem[pOp->p3];
63143   sqlite3VdbeMemIntegerify(pIn3);
63144   /* See note about index shifting on OP_ReadCookie */
63145   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
63146   if( pOp->p2==BTREE_SCHEMA_VERSION ){
63147     /* When the schema cookie changes, record the new cookie internally */
63148     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
63149     db->flags |= SQLITE_InternChanges;
63150   }else if( pOp->p2==BTREE_FILE_FORMAT ){
63151     /* Record changes in the file format */
63152     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
63153   }
63154   if( pOp->p1==1 ){
63155     /* Invalidate all prepared statements whenever the TEMP database
63156     ** schema is changed.  Ticket #1644 */
63157     sqlite3ExpirePreparedStatements(db);
63158     p->expired = 0;
63159   }
63160   break;
63161 }
63162
63163 /* Opcode: VerifyCookie P1 P2 *
63164 **
63165 ** Check the value of global database parameter number 0 (the
63166 ** schema version) and make sure it is equal to P2.  
63167 ** P1 is the database number which is 0 for the main database file
63168 ** and 1 for the file holding temporary tables and some higher number
63169 ** for auxiliary databases.
63170 **
63171 ** The cookie changes its value whenever the database schema changes.
63172 ** This operation is used to detect when that the cookie has changed
63173 ** and that the current process needs to reread the schema.
63174 **
63175 ** Either a transaction needs to have been started or an OP_Open needs
63176 ** to be executed (to establish a read lock) before this opcode is
63177 ** invoked.
63178 */
63179 case OP_VerifyCookie: {
63180 #if 0  /* local variables moved into u.av */
63181   int iMeta;
63182   Btree *pBt;
63183 #endif /* local variables moved into u.av */
63184   assert( pOp->p1>=0 && pOp->p1<db->nDb );
63185   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
63186   u.av.pBt = db->aDb[pOp->p1].pBt;
63187   if( u.av.pBt ){
63188     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
63189   }else{
63190     u.av.iMeta = 0;
63191   }
63192   if( u.av.iMeta!=pOp->p2 ){
63193     sqlite3DbFree(db, p->zErrMsg);
63194     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
63195     /* If the schema-cookie from the database file matches the cookie
63196     ** stored with the in-memory representation of the schema, do
63197     ** not reload the schema from the database file.
63198     **
63199     ** If virtual-tables are in use, this is not just an optimization.
63200     ** Often, v-tables store their data in other SQLite tables, which
63201     ** are queried from within xNext() and other v-table methods using
63202     ** prepared queries. If such a query is out-of-date, we do not want to
63203     ** discard the database schema, as the user code implementing the
63204     ** v-table would have to be ready for the sqlite3_vtab structure itself
63205     ** to be invalidated whenever sqlite3_step() is called from within
63206     ** a v-table method.
63207     */
63208     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
63209       sqlite3ResetInternalSchema(db, pOp->p1);
63210     }
63211
63212     sqlite3ExpirePreparedStatements(db);
63213     rc = SQLITE_SCHEMA;
63214   }
63215   break;
63216 }
63217
63218 /* Opcode: OpenRead P1 P2 P3 P4 P5
63219 **
63220 ** Open a read-only cursor for the database table whose root page is
63221 ** P2 in a database file.  The database file is determined by P3. 
63222 ** P3==0 means the main database, P3==1 means the database used for 
63223 ** temporary tables, and P3>1 means used the corresponding attached
63224 ** database.  Give the new cursor an identifier of P1.  The P1
63225 ** values need not be contiguous but all P1 values should be small integers.
63226 ** It is an error for P1 to be negative.
63227 **
63228 ** If P5!=0 then use the content of register P2 as the root page, not
63229 ** the value of P2 itself.
63230 **
63231 ** There will be a read lock on the database whenever there is an
63232 ** open cursor.  If the database was unlocked prior to this instruction
63233 ** then a read lock is acquired as part of this instruction.  A read
63234 ** lock allows other processes to read the database but prohibits
63235 ** any other process from modifying the database.  The read lock is
63236 ** released when all cursors are closed.  If this instruction attempts
63237 ** to get a read lock but fails, the script terminates with an
63238 ** SQLITE_BUSY error code.
63239 **
63240 ** The P4 value may be either an integer (P4_INT32) or a pointer to
63241 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
63242 ** structure, then said structure defines the content and collating 
63243 ** sequence of the index being opened. Otherwise, if P4 is an integer 
63244 ** value, it is set to the number of columns in the table.
63245 **
63246 ** See also OpenWrite.
63247 */
63248 /* Opcode: OpenWrite P1 P2 P3 P4 P5
63249 **
63250 ** Open a read/write cursor named P1 on the table or index whose root
63251 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
63252 ** root page.
63253 **
63254 ** The P4 value may be either an integer (P4_INT32) or a pointer to
63255 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
63256 ** structure, then said structure defines the content and collating 
63257 ** sequence of the index being opened. Otherwise, if P4 is an integer 
63258 ** value, it is set to the number of columns in the table, or to the
63259 ** largest index of any column of the table that is actually used.
63260 **
63261 ** This instruction works just like OpenRead except that it opens the cursor
63262 ** in read/write mode.  For a given table, there can be one or more read-only
63263 ** cursors or a single read/write cursor but not both.
63264 **
63265 ** See also OpenRead.
63266 */
63267 case OP_OpenRead:
63268 case OP_OpenWrite: {
63269 #if 0  /* local variables moved into u.aw */
63270   int nField;
63271   KeyInfo *pKeyInfo;
63272   int p2;
63273   int iDb;
63274   int wrFlag;
63275   Btree *pX;
63276   VdbeCursor *pCur;
63277   Db *pDb;
63278 #endif /* local variables moved into u.aw */
63279
63280   if( p->expired ){
63281     rc = SQLITE_ABORT;
63282     break;
63283   }
63284
63285   u.aw.nField = 0;
63286   u.aw.pKeyInfo = 0;
63287   u.aw.p2 = pOp->p2;
63288   u.aw.iDb = pOp->p3;
63289   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
63290   assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
63291   u.aw.pDb = &db->aDb[u.aw.iDb];
63292   u.aw.pX = u.aw.pDb->pBt;
63293   assert( u.aw.pX!=0 );
63294   if( pOp->opcode==OP_OpenWrite ){
63295     u.aw.wrFlag = 1;
63296     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
63297       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
63298     }
63299   }else{
63300     u.aw.wrFlag = 0;
63301   }
63302   if( pOp->p5 ){
63303     assert( u.aw.p2>0 );
63304     assert( u.aw.p2<=p->nMem );
63305     pIn2 = &aMem[u.aw.p2];
63306     assert( memIsValid(pIn2) );
63307     assert( (pIn2->flags & MEM_Int)!=0 );
63308     sqlite3VdbeMemIntegerify(pIn2);
63309     u.aw.p2 = (int)pIn2->u.i;
63310     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
63311     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
63312     ** If there were a failure, the prepared statement would have halted
63313     ** before reaching this instruction. */
63314     if( NEVER(u.aw.p2<2) ) {
63315       rc = SQLITE_CORRUPT_BKPT;
63316       goto abort_due_to_error;
63317     }
63318   }
63319   if( pOp->p4type==P4_KEYINFO ){
63320     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
63321     u.aw.pKeyInfo->enc = ENC(p->db);
63322     u.aw.nField = u.aw.pKeyInfo->nField+1;
63323   }else if( pOp->p4type==P4_INT32 ){
63324     u.aw.nField = pOp->p4.i;
63325   }
63326   assert( pOp->p1>=0 );
63327   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
63328   if( u.aw.pCur==0 ) goto no_mem;
63329   u.aw.pCur->nullRow = 1;
63330   u.aw.pCur->isOrdered = 1;
63331   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
63332   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
63333
63334   /* Since it performs no memory allocation or IO, the only values that
63335   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
63336   ** SQLITE_EMPTY is only returned when attempting to open the table
63337   ** rooted at page 1 of a zero-byte database.  */
63338   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
63339   if( rc==SQLITE_EMPTY ){
63340     u.aw.pCur->pCursor = 0;
63341     rc = SQLITE_OK;
63342   }
63343
63344   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
63345   ** SQLite used to check if the root-page flags were sane at this point
63346   ** and report database corruption if they were not, but this check has
63347   ** since moved into the btree layer.  */
63348   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
63349   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
63350   break;
63351 }
63352
63353 /* Opcode: OpenEphemeral P1 P2 * P4 *
63354 **
63355 ** Open a new cursor P1 to a transient table.
63356 ** The cursor is always opened read/write even if 
63357 ** the main database is read-only.  The ephemeral
63358 ** table is deleted automatically when the cursor is closed.
63359 **
63360 ** P2 is the number of columns in the ephemeral table.
63361 ** The cursor points to a BTree table if P4==0 and to a BTree index
63362 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
63363 ** that defines the format of keys in the index.
63364 **
63365 ** This opcode was once called OpenTemp.  But that created
63366 ** confusion because the term "temp table", might refer either
63367 ** to a TEMP table at the SQL level, or to a table opened by
63368 ** this opcode.  Then this opcode was call OpenVirtual.  But
63369 ** that created confusion with the whole virtual-table idea.
63370 */
63371 /* Opcode: OpenAutoindex P1 P2 * P4 *
63372 **
63373 ** This opcode works the same as OP_OpenEphemeral.  It has a
63374 ** different name to distinguish its use.  Tables created using
63375 ** by this opcode will be used for automatically created transient
63376 ** indices in joins.
63377 */
63378 case OP_OpenAutoindex: 
63379 case OP_OpenEphemeral: {
63380 #if 0  /* local variables moved into u.ax */
63381   VdbeCursor *pCx;
63382 #endif /* local variables moved into u.ax */
63383   static const int vfsFlags =
63384       SQLITE_OPEN_READWRITE |
63385       SQLITE_OPEN_CREATE |
63386       SQLITE_OPEN_EXCLUSIVE |
63387       SQLITE_OPEN_DELETEONCLOSE |
63388       SQLITE_OPEN_TRANSIENT_DB;
63389
63390   assert( pOp->p1>=0 );
63391   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
63392   if( u.ax.pCx==0 ) goto no_mem;
63393   u.ax.pCx->nullRow = 1;
63394   rc = sqlite3BtreeOpen(0, db, &u.ax.pCx->pBt,
63395                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
63396   if( rc==SQLITE_OK ){
63397     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
63398   }
63399   if( rc==SQLITE_OK ){
63400     /* If a transient index is required, create it by calling
63401     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
63402     ** opening it. If a transient table is required, just use the
63403     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
63404     */
63405     if( pOp->p4.pKeyInfo ){
63406       int pgno;
63407       assert( pOp->p4type==P4_KEYINFO );
63408       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY);
63409       if( rc==SQLITE_OK ){
63410         assert( pgno==MASTER_ROOT+1 );
63411         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
63412                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
63413         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
63414         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
63415       }
63416       u.ax.pCx->isTable = 0;
63417     }else{
63418       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
63419       u.ax.pCx->isTable = 1;
63420     }
63421   }
63422   u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
63423   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
63424   break;
63425 }
63426
63427 /* Opcode: OpenPseudo P1 P2 P3 * *
63428 **
63429 ** Open a new cursor that points to a fake table that contains a single
63430 ** row of data.  The content of that one row in the content of memory
63431 ** register P2.  In other words, cursor P1 becomes an alias for the 
63432 ** MEM_Blob content contained in register P2.
63433 **
63434 ** A pseudo-table created by this opcode is used to hold a single
63435 ** row output from the sorter so that the row can be decomposed into
63436 ** individual columns using the OP_Column opcode.  The OP_Column opcode
63437 ** is the only cursor opcode that works with a pseudo-table.
63438 **
63439 ** P3 is the number of fields in the records that will be stored by
63440 ** the pseudo-table.
63441 */
63442 case OP_OpenPseudo: {
63443 #if 0  /* local variables moved into u.ay */
63444   VdbeCursor *pCx;
63445 #endif /* local variables moved into u.ay */
63446
63447   assert( pOp->p1>=0 );
63448   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
63449   if( u.ay.pCx==0 ) goto no_mem;
63450   u.ay.pCx->nullRow = 1;
63451   u.ay.pCx->pseudoTableReg = pOp->p2;
63452   u.ay.pCx->isTable = 1;
63453   u.ay.pCx->isIndex = 0;
63454   break;
63455 }
63456
63457 /* Opcode: Close P1 * * * *
63458 **
63459 ** Close a cursor previously opened as P1.  If P1 is not
63460 ** currently open, this instruction is a no-op.
63461 */
63462 case OP_Close: {
63463   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63464   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
63465   p->apCsr[pOp->p1] = 0;
63466   break;
63467 }
63468
63469 /* Opcode: SeekGe P1 P2 P3 P4 *
63470 **
63471 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63472 ** use the value in register P3 as the key.  If cursor P1 refers 
63473 ** to an SQL index, then P3 is the first in an array of P4 registers 
63474 ** that are used as an unpacked index key. 
63475 **
63476 ** Reposition cursor P1 so that  it points to the smallest entry that 
63477 ** is greater than or equal to the key value. If there are no records 
63478 ** greater than or equal to the key and P2 is not zero, then jump to P2.
63479 **
63480 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
63481 */
63482 /* Opcode: SeekGt P1 P2 P3 P4 *
63483 **
63484 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63485 ** use the value in register P3 as a key. If cursor P1 refers 
63486 ** to an SQL index, then P3 is the first in an array of P4 registers 
63487 ** that are used as an unpacked index key. 
63488 **
63489 ** Reposition cursor P1 so that  it points to the smallest entry that 
63490 ** is greater than the key value. If there are no records greater than 
63491 ** the key and P2 is not zero, then jump to P2.
63492 **
63493 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
63494 */
63495 /* Opcode: SeekLt P1 P2 P3 P4 * 
63496 **
63497 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63498 ** use the value in register P3 as a key. If cursor P1 refers 
63499 ** to an SQL index, then P3 is the first in an array of P4 registers 
63500 ** that are used as an unpacked index key. 
63501 **
63502 ** Reposition cursor P1 so that  it points to the largest entry that 
63503 ** is less than the key value. If there are no records less than 
63504 ** the key and P2 is not zero, then jump to P2.
63505 **
63506 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
63507 */
63508 /* Opcode: SeekLe P1 P2 P3 P4 *
63509 **
63510 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
63511 ** use the value in register P3 as a key. If cursor P1 refers 
63512 ** to an SQL index, then P3 is the first in an array of P4 registers 
63513 ** that are used as an unpacked index key. 
63514 **
63515 ** Reposition cursor P1 so that it points to the largest entry that 
63516 ** is less than or equal to the key value. If there are no records 
63517 ** less than or equal to the key and P2 is not zero, then jump to P2.
63518 **
63519 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
63520 */
63521 case OP_SeekLt:         /* jump, in3 */
63522 case OP_SeekLe:         /* jump, in3 */
63523 case OP_SeekGe:         /* jump, in3 */
63524 case OP_SeekGt: {       /* jump, in3 */
63525 #if 0  /* local variables moved into u.az */
63526   int res;
63527   int oc;
63528   VdbeCursor *pC;
63529   UnpackedRecord r;
63530   int nField;
63531   i64 iKey;      /* The rowid we are to seek to */
63532 #endif /* local variables moved into u.az */
63533
63534   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63535   assert( pOp->p2!=0 );
63536   u.az.pC = p->apCsr[pOp->p1];
63537   assert( u.az.pC!=0 );
63538   assert( u.az.pC->pseudoTableReg==0 );
63539   assert( OP_SeekLe == OP_SeekLt+1 );
63540   assert( OP_SeekGe == OP_SeekLt+2 );
63541   assert( OP_SeekGt == OP_SeekLt+3 );
63542   assert( u.az.pC->isOrdered );
63543   if( u.az.pC->pCursor!=0 ){
63544     u.az.oc = pOp->opcode;
63545     u.az.pC->nullRow = 0;
63546     if( u.az.pC->isTable ){
63547       /* The input value in P3 might be of any type: integer, real, string,
63548       ** blob, or NULL.  But it needs to be an integer before we can do
63549       ** the seek, so covert it. */
63550       pIn3 = &aMem[pOp->p3];
63551       applyNumericAffinity(pIn3);
63552       u.az.iKey = sqlite3VdbeIntValue(pIn3);
63553       u.az.pC->rowidIsValid = 0;
63554
63555       /* If the P3 value could not be converted into an integer without
63556       ** loss of information, then special processing is required... */
63557       if( (pIn3->flags & MEM_Int)==0 ){
63558         if( (pIn3->flags & MEM_Real)==0 ){
63559           /* If the P3 value cannot be converted into any kind of a number,
63560           ** then the seek is not possible, so jump to P2 */
63561           pc = pOp->p2 - 1;
63562           break;
63563         }
63564         /* If we reach this point, then the P3 value must be a floating
63565         ** point number. */
63566         assert( (pIn3->flags & MEM_Real)!=0 );
63567
63568         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
63569           /* The P3 value is too large in magnitude to be expressed as an
63570           ** integer. */
63571           u.az.res = 1;
63572           if( pIn3->r<0 ){
63573             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
63574               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
63575               if( rc!=SQLITE_OK ) goto abort_due_to_error;
63576             }
63577           }else{
63578             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
63579               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
63580               if( rc!=SQLITE_OK ) goto abort_due_to_error;
63581             }
63582           }
63583           if( u.az.res ){
63584             pc = pOp->p2 - 1;
63585           }
63586           break;
63587         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
63588           /* Use the ceiling() function to convert real->int */
63589           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
63590         }else{
63591           /* Use the floor() function to convert real->int */
63592           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
63593           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
63594         }
63595       }
63596       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
63597       if( rc!=SQLITE_OK ){
63598         goto abort_due_to_error;
63599       }
63600       if( u.az.res==0 ){
63601         u.az.pC->rowidIsValid = 1;
63602         u.az.pC->lastRowid = u.az.iKey;
63603       }
63604     }else{
63605       u.az.nField = pOp->p4.i;
63606       assert( pOp->p4type==P4_INT32 );
63607       assert( u.az.nField>0 );
63608       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
63609       u.az.r.nField = (u16)u.az.nField;
63610
63611       /* The next line of code computes as follows, only faster:
63612       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
63613       **     u.az.r.flags = UNPACKED_INCRKEY;
63614       **   }else{
63615       **     u.az.r.flags = 0;
63616       **   }
63617       */
63618       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
63619       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
63620       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
63621       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
63622       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
63623
63624       u.az.r.aMem = &aMem[pOp->p3];
63625 #ifdef SQLITE_DEBUG
63626       { int i; for(i=0; i<u.az.r.nField; i++) assert( memIsValid(&u.az.r.aMem[i]) ); }
63627 #endif
63628       ExpandBlob(u.az.r.aMem);
63629       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
63630       if( rc!=SQLITE_OK ){
63631         goto abort_due_to_error;
63632       }
63633       u.az.pC->rowidIsValid = 0;
63634     }
63635     u.az.pC->deferredMoveto = 0;
63636     u.az.pC->cacheStatus = CACHE_STALE;
63637 #ifdef SQLITE_TEST
63638     sqlite3_search_count++;
63639 #endif
63640     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
63641       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
63642         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
63643         if( rc!=SQLITE_OK ) goto abort_due_to_error;
63644         u.az.pC->rowidIsValid = 0;
63645       }else{
63646         u.az.res = 0;
63647       }
63648     }else{
63649       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
63650       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
63651         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
63652         if( rc!=SQLITE_OK ) goto abort_due_to_error;
63653         u.az.pC->rowidIsValid = 0;
63654       }else{
63655         /* u.az.res might be negative because the table is empty.  Check to
63656         ** see if this is the case.
63657         */
63658         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
63659       }
63660     }
63661     assert( pOp->p2>0 );
63662     if( u.az.res ){
63663       pc = pOp->p2 - 1;
63664     }
63665   }else{
63666     /* This happens when attempting to open the sqlite3_master table
63667     ** for read access returns SQLITE_EMPTY. In this case always
63668     ** take the jump (since there are no records in the table).
63669     */
63670     pc = pOp->p2 - 1;
63671   }
63672   break;
63673 }
63674
63675 /* Opcode: Seek P1 P2 * * *
63676 **
63677 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
63678 ** for P1 to move so that it points to the rowid given by P2.
63679 **
63680 ** This is actually a deferred seek.  Nothing actually happens until
63681 ** the cursor is used to read a record.  That way, if no reads
63682 ** occur, no unnecessary I/O happens.
63683 */
63684 case OP_Seek: {    /* in2 */
63685 #if 0  /* local variables moved into u.ba */
63686   VdbeCursor *pC;
63687 #endif /* local variables moved into u.ba */
63688
63689   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63690   u.ba.pC = p->apCsr[pOp->p1];
63691   assert( u.ba.pC!=0 );
63692   if( ALWAYS(u.ba.pC->pCursor!=0) ){
63693     assert( u.ba.pC->isTable );
63694     u.ba.pC->nullRow = 0;
63695     pIn2 = &aMem[pOp->p2];
63696     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
63697     u.ba.pC->rowidIsValid = 0;
63698     u.ba.pC->deferredMoveto = 1;
63699   }
63700   break;
63701 }
63702   
63703
63704 /* Opcode: Found P1 P2 P3 P4 *
63705 **
63706 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
63707 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
63708 ** record.
63709 **
63710 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
63711 ** is a prefix of any entry in P1 then a jump is made to P2 and
63712 ** P1 is left pointing at the matching entry.
63713 */
63714 /* Opcode: NotFound P1 P2 P3 P4 *
63715 **
63716 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
63717 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
63718 ** record.
63719 ** 
63720 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
63721 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
63722 ** does contain an entry whose prefix matches the P3/P4 record then control
63723 ** falls through to the next instruction and P1 is left pointing at the
63724 ** matching entry.
63725 **
63726 ** See also: Found, NotExists, IsUnique
63727 */
63728 case OP_NotFound:       /* jump, in3 */
63729 case OP_Found: {        /* jump, in3 */
63730 #if 0  /* local variables moved into u.bb */
63731   int alreadyExists;
63732   VdbeCursor *pC;
63733   int res;
63734   UnpackedRecord *pIdxKey;
63735   UnpackedRecord r;
63736   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
63737 #endif /* local variables moved into u.bb */
63738
63739 #ifdef SQLITE_TEST
63740   sqlite3_found_count++;
63741 #endif
63742
63743   u.bb.alreadyExists = 0;
63744   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63745   assert( pOp->p4type==P4_INT32 );
63746   u.bb.pC = p->apCsr[pOp->p1];
63747   assert( u.bb.pC!=0 );
63748   pIn3 = &aMem[pOp->p3];
63749   if( ALWAYS(u.bb.pC->pCursor!=0) ){
63750
63751     assert( u.bb.pC->isTable==0 );
63752     if( pOp->p4.i>0 ){
63753       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
63754       u.bb.r.nField = (u16)pOp->p4.i;
63755       u.bb.r.aMem = pIn3;
63756 #ifdef SQLITE_DEBUG
63757       { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
63758 #endif
63759       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
63760       u.bb.pIdxKey = &u.bb.r;
63761     }else{
63762       assert( pIn3->flags & MEM_Blob );
63763       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
63764       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
63765                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
63766       if( u.bb.pIdxKey==0 ){
63767         goto no_mem;
63768       }
63769       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
63770     }
63771     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
63772     if( pOp->p4.i==0 ){
63773       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
63774     }
63775     if( rc!=SQLITE_OK ){
63776       break;
63777     }
63778     u.bb.alreadyExists = (u.bb.res==0);
63779     u.bb.pC->deferredMoveto = 0;
63780     u.bb.pC->cacheStatus = CACHE_STALE;
63781   }
63782   if( pOp->opcode==OP_Found ){
63783     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
63784   }else{
63785     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
63786   }
63787   break;
63788 }
63789
63790 /* Opcode: IsUnique P1 P2 P3 P4 *
63791 **
63792 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
63793 ** no data and where the key are records generated by OP_MakeRecord with
63794 ** the list field being the integer ROWID of the entry that the index
63795 ** entry refers to.
63796 **
63797 ** The P3 register contains an integer record number. Call this record 
63798 ** number R. Register P4 is the first in a set of N contiguous registers
63799 ** that make up an unpacked index key that can be used with cursor P1.
63800 ** The value of N can be inferred from the cursor. N includes the rowid
63801 ** value appended to the end of the index record. This rowid value may
63802 ** or may not be the same as R.
63803 **
63804 ** If any of the N registers beginning with register P4 contains a NULL
63805 ** value, jump immediately to P2.
63806 **
63807 ** Otherwise, this instruction checks if cursor P1 contains an entry
63808 ** where the first (N-1) fields match but the rowid value at the end
63809 ** of the index entry is not R. If there is no such entry, control jumps
63810 ** to instruction P2. Otherwise, the rowid of the conflicting index
63811 ** entry is copied to register P3 and control falls through to the next
63812 ** instruction.
63813 **
63814 ** See also: NotFound, NotExists, Found
63815 */
63816 case OP_IsUnique: {        /* jump, in3 */
63817 #if 0  /* local variables moved into u.bc */
63818   u16 ii;
63819   VdbeCursor *pCx;
63820   BtCursor *pCrsr;
63821   u16 nField;
63822   Mem *aMx;
63823   UnpackedRecord r;                  /* B-Tree index search key */
63824   i64 R;                             /* Rowid stored in register P3 */
63825 #endif /* local variables moved into u.bc */
63826
63827   pIn3 = &aMem[pOp->p3];
63828   u.bc.aMx = &aMem[pOp->p4.i];
63829   /* Assert that the values of parameters P1 and P4 are in range. */
63830   assert( pOp->p4type==P4_INT32 );
63831   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
63832   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63833
63834   /* Find the index cursor. */
63835   u.bc.pCx = p->apCsr[pOp->p1];
63836   assert( u.bc.pCx->deferredMoveto==0 );
63837   u.bc.pCx->seekResult = 0;
63838   u.bc.pCx->cacheStatus = CACHE_STALE;
63839   u.bc.pCrsr = u.bc.pCx->pCursor;
63840
63841   /* If any of the values are NULL, take the jump. */
63842   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
63843   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
63844     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
63845       pc = pOp->p2 - 1;
63846       u.bc.pCrsr = 0;
63847       break;
63848     }
63849   }
63850   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
63851
63852   if( u.bc.pCrsr!=0 ){
63853     /* Populate the index search key. */
63854     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
63855     u.bc.r.nField = u.bc.nField + 1;
63856     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
63857     u.bc.r.aMem = u.bc.aMx;
63858 #ifdef SQLITE_DEBUG
63859     { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
63860 #endif
63861
63862     /* Extract the value of u.bc.R from register P3. */
63863     sqlite3VdbeMemIntegerify(pIn3);
63864     u.bc.R = pIn3->u.i;
63865
63866     /* Search the B-Tree index. If no conflicting record is found, jump
63867     ** to P2. Otherwise, copy the rowid of the conflicting record to
63868     ** register P3 and fall through to the next instruction.  */
63869     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
63870     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
63871       pc = pOp->p2 - 1;
63872     }else{
63873       pIn3->u.i = u.bc.r.rowid;
63874     }
63875   }
63876   break;
63877 }
63878
63879 /* Opcode: NotExists P1 P2 P3 * *
63880 **
63881 ** Use the content of register P3 as a integer key.  If a record 
63882 ** with that key does not exist in table of P1, then jump to P2. 
63883 ** If the record does exist, then fall through.  The cursor is left 
63884 ** pointing to the record if it exists.
63885 **
63886 ** The difference between this operation and NotFound is that this
63887 ** operation assumes the key is an integer and that P1 is a table whereas
63888 ** NotFound assumes key is a blob constructed from MakeRecord and
63889 ** P1 is an index.
63890 **
63891 ** See also: Found, NotFound, IsUnique
63892 */
63893 case OP_NotExists: {        /* jump, in3 */
63894 #if 0  /* local variables moved into u.bd */
63895   VdbeCursor *pC;
63896   BtCursor *pCrsr;
63897   int res;
63898   u64 iKey;
63899 #endif /* local variables moved into u.bd */
63900
63901   pIn3 = &aMem[pOp->p3];
63902   assert( pIn3->flags & MEM_Int );
63903   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63904   u.bd.pC = p->apCsr[pOp->p1];
63905   assert( u.bd.pC!=0 );
63906   assert( u.bd.pC->isTable );
63907   assert( u.bd.pC->pseudoTableReg==0 );
63908   u.bd.pCrsr = u.bd.pC->pCursor;
63909   if( u.bd.pCrsr!=0 ){
63910     u.bd.res = 0;
63911     u.bd.iKey = pIn3->u.i;
63912     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
63913     u.bd.pC->lastRowid = pIn3->u.i;
63914     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
63915     u.bd.pC->nullRow = 0;
63916     u.bd.pC->cacheStatus = CACHE_STALE;
63917     u.bd.pC->deferredMoveto = 0;
63918     if( u.bd.res!=0 ){
63919       pc = pOp->p2 - 1;
63920       assert( u.bd.pC->rowidIsValid==0 );
63921     }
63922     u.bd.pC->seekResult = u.bd.res;
63923   }else{
63924     /* This happens when an attempt to open a read cursor on the
63925     ** sqlite_master table returns SQLITE_EMPTY.
63926     */
63927     pc = pOp->p2 - 1;
63928     assert( u.bd.pC->rowidIsValid==0 );
63929     u.bd.pC->seekResult = 0;
63930   }
63931   break;
63932 }
63933
63934 /* Opcode: Sequence P1 P2 * * *
63935 **
63936 ** Find the next available sequence number for cursor P1.
63937 ** Write the sequence number into register P2.
63938 ** The sequence number on the cursor is incremented after this
63939 ** instruction.  
63940 */
63941 case OP_Sequence: {           /* out2-prerelease */
63942   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63943   assert( p->apCsr[pOp->p1]!=0 );
63944   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
63945   break;
63946 }
63947
63948
63949 /* Opcode: NewRowid P1 P2 P3 * *
63950 **
63951 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
63952 ** The record number is not previously used as a key in the database
63953 ** table that cursor P1 points to.  The new record number is written
63954 ** written to register P2.
63955 **
63956 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
63957 ** the largest previously generated record number. No new record numbers are
63958 ** allowed to be less than this value. When this value reaches its maximum, 
63959 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
63960 ** generated record number. This P3 mechanism is used to help implement the
63961 ** AUTOINCREMENT feature.
63962 */
63963 case OP_NewRowid: {           /* out2-prerelease */
63964 #if 0  /* local variables moved into u.be */
63965   i64 v;                 /* The new rowid */
63966   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
63967   int res;               /* Result of an sqlite3BtreeLast() */
63968   int cnt;               /* Counter to limit the number of searches */
63969   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
63970   VdbeFrame *pFrame;     /* Root frame of VDBE */
63971 #endif /* local variables moved into u.be */
63972
63973   u.be.v = 0;
63974   u.be.res = 0;
63975   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
63976   u.be.pC = p->apCsr[pOp->p1];
63977   assert( u.be.pC!=0 );
63978   if( NEVER(u.be.pC->pCursor==0) ){
63979     /* The zero initialization above is all that is needed */
63980   }else{
63981     /* The next rowid or record number (different terms for the same
63982     ** thing) is obtained in a two-step algorithm.
63983     **
63984     ** First we attempt to find the largest existing rowid and add one
63985     ** to that.  But if the largest existing rowid is already the maximum
63986     ** positive integer, we have to fall through to the second
63987     ** probabilistic algorithm
63988     **
63989     ** The second algorithm is to select a rowid at random and see if
63990     ** it already exists in the table.  If it does not exist, we have
63991     ** succeeded.  If the random rowid does exist, we select a new one
63992     ** and try again, up to 100 times.
63993     */
63994     assert( u.be.pC->isTable );
63995     u.be.cnt = 0;
63996
63997 #ifdef SQLITE_32BIT_ROWID
63998 #   define MAX_ROWID 0x7fffffff
63999 #else
64000     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
64001     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
64002     ** to provide the constant while making all compilers happy.
64003     */
64004 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
64005 #endif
64006
64007     if( !u.be.pC->useRandomRowid ){
64008       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
64009       if( u.be.v==0 ){
64010         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
64011         if( rc!=SQLITE_OK ){
64012           goto abort_due_to_error;
64013         }
64014         if( u.be.res ){
64015           u.be.v = 1;   /* IMP: R-61914-48074 */
64016         }else{
64017           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
64018           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
64019           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
64020           if( u.be.v==MAX_ROWID ){
64021             u.be.pC->useRandomRowid = 1;
64022           }else{
64023             u.be.v++;   /* IMP: R-29538-34987 */
64024           }
64025         }
64026       }
64027
64028 #ifndef SQLITE_OMIT_AUTOINCREMENT
64029       if( pOp->p3 ){
64030         /* Assert that P3 is a valid memory cell. */
64031         assert( pOp->p3>0 );
64032         if( p->pFrame ){
64033           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
64034           /* Assert that P3 is a valid memory cell. */
64035           assert( pOp->p3<=u.be.pFrame->nMem );
64036           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
64037         }else{
64038           /* Assert that P3 is a valid memory cell. */
64039           assert( pOp->p3<=p->nMem );
64040           u.be.pMem = &aMem[pOp->p3];
64041           memAboutToChange(p, u.be.pMem);
64042         }
64043         assert( memIsValid(u.be.pMem) );
64044
64045         REGISTER_TRACE(pOp->p3, u.be.pMem);
64046         sqlite3VdbeMemIntegerify(u.be.pMem);
64047         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
64048         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
64049           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
64050           goto abort_due_to_error;
64051         }
64052         if( u.be.v<u.be.pMem->u.i+1 ){
64053           u.be.v = u.be.pMem->u.i + 1;
64054         }
64055         u.be.pMem->u.i = u.be.v;
64056       }
64057 #endif
64058
64059       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
64060     }
64061     if( u.be.pC->useRandomRowid ){
64062       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
64063       ** largest possible integer (9223372036854775807) then the database
64064       ** engine starts picking positive candidate ROWIDs at random until
64065       ** it finds one that is not previously used. */
64066       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
64067                              ** an AUTOINCREMENT table. */
64068       /* on the first attempt, simply do one more than previous */
64069       u.be.v = db->lastRowid;
64070       u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
64071       u.be.v++; /* ensure non-zero */
64072       u.be.cnt = 0;
64073       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v,
64074                                                  0, &u.be.res))==SQLITE_OK)
64075             && (u.be.res==0)
64076             && (++u.be.cnt<100)){
64077         /* collision - try another random rowid */
64078         sqlite3_randomness(sizeof(u.be.v), &u.be.v);
64079         if( u.be.cnt<5 ){
64080           /* try "small" random rowids for the initial attempts */
64081           u.be.v &= 0xffffff;
64082         }else{
64083           u.be.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
64084         }
64085         u.be.v++; /* ensure non-zero */
64086       }
64087       if( rc==SQLITE_OK && u.be.res==0 ){
64088         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
64089         goto abort_due_to_error;
64090       }
64091       assert( u.be.v>0 );  /* EV: R-40812-03570 */
64092     }
64093     u.be.pC->rowidIsValid = 0;
64094     u.be.pC->deferredMoveto = 0;
64095     u.be.pC->cacheStatus = CACHE_STALE;
64096   }
64097   pOut->u.i = u.be.v;
64098   break;
64099 }
64100
64101 /* Opcode: Insert P1 P2 P3 P4 P5
64102 **
64103 ** Write an entry into the table of cursor P1.  A new entry is
64104 ** created if it doesn't already exist or the data for an existing
64105 ** entry is overwritten.  The data is the value MEM_Blob stored in register
64106 ** number P2. The key is stored in register P3. The key must
64107 ** be a MEM_Int.
64108 **
64109 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
64110 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
64111 ** then rowid is stored for subsequent return by the
64112 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
64113 **
64114 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
64115 ** the last seek operation (OP_NotExists) was a success, then this
64116 ** operation will not attempt to find the appropriate row before doing
64117 ** the insert but will instead overwrite the row that the cursor is
64118 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
64119 ** has already positioned the cursor correctly.  This is an optimization
64120 ** that boosts performance by avoiding redundant seeks.
64121 **
64122 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
64123 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
64124 ** is part of an INSERT operation.  The difference is only important to
64125 ** the update hook.
64126 **
64127 ** Parameter P4 may point to a string containing the table-name, or
64128 ** may be NULL. If it is not NULL, then the update-hook 
64129 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
64130 **
64131 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
64132 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
64133 ** and register P2 becomes ephemeral.  If the cursor is changed, the
64134 ** value of register P2 will then change.  Make sure this does not
64135 ** cause any problems.)
64136 **
64137 ** This instruction only works on tables.  The equivalent instruction
64138 ** for indices is OP_IdxInsert.
64139 */
64140 /* Opcode: InsertInt P1 P2 P3 P4 P5
64141 **
64142 ** This works exactly like OP_Insert except that the key is the
64143 ** integer value P3, not the value of the integer stored in register P3.
64144 */
64145 case OP_Insert: 
64146 case OP_InsertInt: {
64147 #if 0  /* local variables moved into u.bf */
64148   Mem *pData;       /* MEM cell holding data for the record to be inserted */
64149   Mem *pKey;        /* MEM cell holding key  for the record */
64150   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
64151   VdbeCursor *pC;   /* Cursor to table into which insert is written */
64152   int nZero;        /* Number of zero-bytes to append */
64153   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
64154   const char *zDb;  /* database name - used by the update hook */
64155   const char *zTbl; /* Table name - used by the opdate hook */
64156   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
64157 #endif /* local variables moved into u.bf */
64158
64159   u.bf.pData = &aMem[pOp->p2];
64160   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64161   assert( memIsValid(u.bf.pData) );
64162   u.bf.pC = p->apCsr[pOp->p1];
64163   assert( u.bf.pC!=0 );
64164   assert( u.bf.pC->pCursor!=0 );
64165   assert( u.bf.pC->pseudoTableReg==0 );
64166   assert( u.bf.pC->isTable );
64167   REGISTER_TRACE(pOp->p2, u.bf.pData);
64168
64169   if( pOp->opcode==OP_Insert ){
64170     u.bf.pKey = &aMem[pOp->p3];
64171     assert( u.bf.pKey->flags & MEM_Int );
64172     assert( memIsValid(u.bf.pKey) );
64173     REGISTER_TRACE(pOp->p3, u.bf.pKey);
64174     u.bf.iKey = u.bf.pKey->u.i;
64175   }else{
64176     assert( pOp->opcode==OP_InsertInt );
64177     u.bf.iKey = pOp->p3;
64178   }
64179
64180   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
64181   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
64182   if( u.bf.pData->flags & MEM_Null ){
64183     u.bf.pData->z = 0;
64184     u.bf.pData->n = 0;
64185   }else{
64186     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
64187   }
64188   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
64189   if( u.bf.pData->flags & MEM_Zero ){
64190     u.bf.nZero = u.bf.pData->u.nZero;
64191   }else{
64192     u.bf.nZero = 0;
64193   }
64194   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
64195   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
64196                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
64197                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
64198   );
64199   u.bf.pC->rowidIsValid = 0;
64200   u.bf.pC->deferredMoveto = 0;
64201   u.bf.pC->cacheStatus = CACHE_STALE;
64202
64203   /* Invoke the update-hook if required. */
64204   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
64205     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
64206     u.bf.zTbl = pOp->p4.z;
64207     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
64208     assert( u.bf.pC->isTable );
64209     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
64210     assert( u.bf.pC->iDb>=0 );
64211   }
64212   break;
64213 }
64214
64215 /* Opcode: Delete P1 P2 * P4 *
64216 **
64217 ** Delete the record at which the P1 cursor is currently pointing.
64218 **
64219 ** The cursor will be left pointing at either the next or the previous
64220 ** record in the table. If it is left pointing at the next record, then
64221 ** the next Next instruction will be a no-op.  Hence it is OK to delete
64222 ** a record from within an Next loop.
64223 **
64224 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
64225 ** incremented (otherwise not).
64226 **
64227 ** P1 must not be pseudo-table.  It has to be a real table with
64228 ** multiple rows.
64229 **
64230 ** If P4 is not NULL, then it is the name of the table that P1 is
64231 ** pointing to.  The update hook will be invoked, if it exists.
64232 ** If P4 is not NULL then the P1 cursor must have been positioned
64233 ** using OP_NotFound prior to invoking this opcode.
64234 */
64235 case OP_Delete: {
64236 #if 0  /* local variables moved into u.bg */
64237   i64 iKey;
64238   VdbeCursor *pC;
64239 #endif /* local variables moved into u.bg */
64240
64241   u.bg.iKey = 0;
64242   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64243   u.bg.pC = p->apCsr[pOp->p1];
64244   assert( u.bg.pC!=0 );
64245   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
64246
64247   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
64248   ** row being deleted.
64249   */
64250   if( db->xUpdateCallback && pOp->p4.z ){
64251     assert( u.bg.pC->isTable );
64252     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
64253     u.bg.iKey = u.bg.pC->lastRowid;
64254   }
64255
64256   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
64257   ** OP_Column on the same table without any intervening operations that
64258   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
64259   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
64260   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
64261   ** to guard against future changes to the code generator.
64262   **/
64263   assert( u.bg.pC->deferredMoveto==0 );
64264   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
64265   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
64266
64267   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
64268   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
64269   u.bg.pC->cacheStatus = CACHE_STALE;
64270
64271   /* Invoke the update-hook if required. */
64272   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
64273     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
64274     const char *zTbl = pOp->p4.z;
64275     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
64276     assert( u.bg.pC->iDb>=0 );
64277   }
64278   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
64279   break;
64280 }
64281 /* Opcode: ResetCount * * * * *
64282 **
64283 ** The value of the change counter is copied to the database handle
64284 ** change counter (returned by subsequent calls to sqlite3_changes()).
64285 ** Then the VMs internal change counter resets to 0.
64286 ** This is used by trigger programs.
64287 */
64288 case OP_ResetCount: {
64289   sqlite3VdbeSetChanges(db, p->nChange);
64290   p->nChange = 0;
64291   break;
64292 }
64293
64294 /* Opcode: RowData P1 P2 * * *
64295 **
64296 ** Write into register P2 the complete row data for cursor P1.
64297 ** There is no interpretation of the data.  
64298 ** It is just copied onto the P2 register exactly as 
64299 ** it is found in the database file.
64300 **
64301 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
64302 ** of a real table, not a pseudo-table.
64303 */
64304 /* Opcode: RowKey P1 P2 * * *
64305 **
64306 ** Write into register P2 the complete row key for cursor P1.
64307 ** There is no interpretation of the data.  
64308 ** The key is copied onto the P3 register exactly as 
64309 ** it is found in the database file.
64310 **
64311 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
64312 ** of a real table, not a pseudo-table.
64313 */
64314 case OP_RowKey:
64315 case OP_RowData: {
64316 #if 0  /* local variables moved into u.bh */
64317   VdbeCursor *pC;
64318   BtCursor *pCrsr;
64319   u32 n;
64320   i64 n64;
64321 #endif /* local variables moved into u.bh */
64322
64323   pOut = &aMem[pOp->p2];
64324   memAboutToChange(p, pOut);
64325
64326   /* Note that RowKey and RowData are really exactly the same instruction */
64327   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64328   u.bh.pC = p->apCsr[pOp->p1];
64329   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
64330   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
64331   assert( u.bh.pC!=0 );
64332   assert( u.bh.pC->nullRow==0 );
64333   assert( u.bh.pC->pseudoTableReg==0 );
64334   assert( u.bh.pC->pCursor!=0 );
64335   u.bh.pCrsr = u.bh.pC->pCursor;
64336   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
64337
64338   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
64339   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
64340   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
64341   ** a no-op and can never fail.  But we leave it in place as a safety.
64342   */
64343   assert( u.bh.pC->deferredMoveto==0 );
64344   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
64345   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
64346
64347   if( u.bh.pC->isIndex ){
64348     assert( !u.bh.pC->isTable );
64349     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
64350     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
64351     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64352       goto too_big;
64353     }
64354     u.bh.n = (u32)u.bh.n64;
64355   }else{
64356     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
64357     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
64358     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
64359       goto too_big;
64360     }
64361   }
64362   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
64363     goto no_mem;
64364   }
64365   pOut->n = u.bh.n;
64366   MemSetTypeFlag(pOut, MEM_Blob);
64367   if( u.bh.pC->isIndex ){
64368     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
64369   }else{
64370     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
64371   }
64372   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
64373   UPDATE_MAX_BLOBSIZE(pOut);
64374   break;
64375 }
64376
64377 /* Opcode: Rowid P1 P2 * * *
64378 **
64379 ** Store in register P2 an integer which is the key of the table entry that
64380 ** P1 is currently point to.
64381 **
64382 ** P1 can be either an ordinary table or a virtual table.  There used to
64383 ** be a separate OP_VRowid opcode for use with virtual tables, but this
64384 ** one opcode now works for both table types.
64385 */
64386 case OP_Rowid: {                 /* out2-prerelease */
64387 #if 0  /* local variables moved into u.bi */
64388   VdbeCursor *pC;
64389   i64 v;
64390   sqlite3_vtab *pVtab;
64391   const sqlite3_module *pModule;
64392 #endif /* local variables moved into u.bi */
64393
64394   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64395   u.bi.pC = p->apCsr[pOp->p1];
64396   assert( u.bi.pC!=0 );
64397   assert( u.bi.pC->pseudoTableReg==0 );
64398   if( u.bi.pC->nullRow ){
64399     pOut->flags = MEM_Null;
64400     break;
64401   }else if( u.bi.pC->deferredMoveto ){
64402     u.bi.v = u.bi.pC->movetoTarget;
64403 #ifndef SQLITE_OMIT_VIRTUALTABLE
64404   }else if( u.bi.pC->pVtabCursor ){
64405     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
64406     u.bi.pModule = u.bi.pVtab->pModule;
64407     assert( u.bi.pModule->xRowid );
64408     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
64409     importVtabErrMsg(p, u.bi.pVtab);
64410 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64411   }else{
64412     assert( u.bi.pC->pCursor!=0 );
64413     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
64414     if( rc ) goto abort_due_to_error;
64415     if( u.bi.pC->rowidIsValid ){
64416       u.bi.v = u.bi.pC->lastRowid;
64417     }else{
64418       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
64419       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
64420     }
64421   }
64422   pOut->u.i = u.bi.v;
64423   break;
64424 }
64425
64426 /* Opcode: NullRow P1 * * * *
64427 **
64428 ** Move the cursor P1 to a null row.  Any OP_Column operations
64429 ** that occur while the cursor is on the null row will always
64430 ** write a NULL.
64431 */
64432 case OP_NullRow: {
64433 #if 0  /* local variables moved into u.bj */
64434   VdbeCursor *pC;
64435 #endif /* local variables moved into u.bj */
64436
64437   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64438   u.bj.pC = p->apCsr[pOp->p1];
64439   assert( u.bj.pC!=0 );
64440   u.bj.pC->nullRow = 1;
64441   u.bj.pC->rowidIsValid = 0;
64442   if( u.bj.pC->pCursor ){
64443     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
64444   }
64445   break;
64446 }
64447
64448 /* Opcode: Last P1 P2 * * *
64449 **
64450 ** The next use of the Rowid or Column or Next instruction for P1 
64451 ** will refer to the last entry in the database table or index.
64452 ** If the table or index is empty and P2>0, then jump immediately to P2.
64453 ** If P2 is 0 or if the table or index is not empty, fall through
64454 ** to the following instruction.
64455 */
64456 case OP_Last: {        /* jump */
64457 #if 0  /* local variables moved into u.bk */
64458   VdbeCursor *pC;
64459   BtCursor *pCrsr;
64460   int res;
64461 #endif /* local variables moved into u.bk */
64462
64463   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64464   u.bk.pC = p->apCsr[pOp->p1];
64465   assert( u.bk.pC!=0 );
64466   u.bk.pCrsr = u.bk.pC->pCursor;
64467   if( u.bk.pCrsr==0 ){
64468     u.bk.res = 1;
64469   }else{
64470     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
64471   }
64472   u.bk.pC->nullRow = (u8)u.bk.res;
64473   u.bk.pC->deferredMoveto = 0;
64474   u.bk.pC->rowidIsValid = 0;
64475   u.bk.pC->cacheStatus = CACHE_STALE;
64476   if( pOp->p2>0 && u.bk.res ){
64477     pc = pOp->p2 - 1;
64478   }
64479   break;
64480 }
64481
64482
64483 /* Opcode: Sort P1 P2 * * *
64484 **
64485 ** This opcode does exactly the same thing as OP_Rewind except that
64486 ** it increments an undocumented global variable used for testing.
64487 **
64488 ** Sorting is accomplished by writing records into a sorting index,
64489 ** then rewinding that index and playing it back from beginning to
64490 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
64491 ** rewinding so that the global variable will be incremented and
64492 ** regression tests can determine whether or not the optimizer is
64493 ** correctly optimizing out sorts.
64494 */
64495 case OP_Sort: {        /* jump */
64496 #ifdef SQLITE_TEST
64497   sqlite3_sort_count++;
64498   sqlite3_search_count--;
64499 #endif
64500   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
64501   /* Fall through into OP_Rewind */
64502 }
64503 /* Opcode: Rewind P1 P2 * * *
64504 **
64505 ** The next use of the Rowid or Column or Next instruction for P1 
64506 ** will refer to the first entry in the database table or index.
64507 ** If the table or index is empty and P2>0, then jump immediately to P2.
64508 ** If P2 is 0 or if the table or index is not empty, fall through
64509 ** to the following instruction.
64510 */
64511 case OP_Rewind: {        /* jump */
64512 #if 0  /* local variables moved into u.bl */
64513   VdbeCursor *pC;
64514   BtCursor *pCrsr;
64515   int res;
64516 #endif /* local variables moved into u.bl */
64517
64518   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64519   u.bl.pC = p->apCsr[pOp->p1];
64520   assert( u.bl.pC!=0 );
64521   u.bl.res = 1;
64522   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
64523     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
64524     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
64525     u.bl.pC->deferredMoveto = 0;
64526     u.bl.pC->cacheStatus = CACHE_STALE;
64527     u.bl.pC->rowidIsValid = 0;
64528   }
64529   u.bl.pC->nullRow = (u8)u.bl.res;
64530   assert( pOp->p2>0 && pOp->p2<p->nOp );
64531   if( u.bl.res ){
64532     pc = pOp->p2 - 1;
64533   }
64534   break;
64535 }
64536
64537 /* Opcode: Next P1 P2 * * P5
64538 **
64539 ** Advance cursor P1 so that it points to the next key/data pair in its
64540 ** table or index.  If there are no more key/value pairs then fall through
64541 ** to the following instruction.  But if the cursor advance was successful,
64542 ** jump immediately to P2.
64543 **
64544 ** The P1 cursor must be for a real table, not a pseudo-table.
64545 **
64546 ** If P5 is positive and the jump is taken, then event counter
64547 ** number P5-1 in the prepared statement is incremented.
64548 **
64549 ** See also: Prev
64550 */
64551 /* Opcode: Prev P1 P2 * * P5
64552 **
64553 ** Back up cursor P1 so that it points to the previous key/data pair in its
64554 ** table or index.  If there is no previous key/value pairs then fall through
64555 ** to the following instruction.  But if the cursor backup was successful,
64556 ** jump immediately to P2.
64557 **
64558 ** The P1 cursor must be for a real table, not a pseudo-table.
64559 **
64560 ** If P5 is positive and the jump is taken, then event counter
64561 ** number P5-1 in the prepared statement is incremented.
64562 */
64563 case OP_Prev:          /* jump */
64564 case OP_Next: {        /* jump */
64565 #if 0  /* local variables moved into u.bm */
64566   VdbeCursor *pC;
64567   BtCursor *pCrsr;
64568   int res;
64569 #endif /* local variables moved into u.bm */
64570
64571   CHECK_FOR_INTERRUPT;
64572   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64573   assert( pOp->p5<=ArraySize(p->aCounter) );
64574   u.bm.pC = p->apCsr[pOp->p1];
64575   if( u.bm.pC==0 ){
64576     break;  /* See ticket #2273 */
64577   }
64578   u.bm.pCrsr = u.bm.pC->pCursor;
64579   if( u.bm.pCrsr==0 ){
64580     u.bm.pC->nullRow = 1;
64581     break;
64582   }
64583   u.bm.res = 1;
64584   assert( u.bm.pC->deferredMoveto==0 );
64585   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
64586                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
64587   u.bm.pC->nullRow = (u8)u.bm.res;
64588   u.bm.pC->cacheStatus = CACHE_STALE;
64589   if( u.bm.res==0 ){
64590     pc = pOp->p2 - 1;
64591     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
64592 #ifdef SQLITE_TEST
64593     sqlite3_search_count++;
64594 #endif
64595   }
64596   u.bm.pC->rowidIsValid = 0;
64597   break;
64598 }
64599
64600 /* Opcode: IdxInsert P1 P2 P3 * P5
64601 **
64602 ** Register P2 holds a SQL index key made using the
64603 ** MakeRecord instructions.  This opcode writes that key
64604 ** into the index P1.  Data for the entry is nil.
64605 **
64606 ** P3 is a flag that provides a hint to the b-tree layer that this
64607 ** insert is likely to be an append.
64608 **
64609 ** This instruction only works for indices.  The equivalent instruction
64610 ** for tables is OP_Insert.
64611 */
64612 case OP_IdxInsert: {        /* in2 */
64613 #if 0  /* local variables moved into u.bn */
64614   VdbeCursor *pC;
64615   BtCursor *pCrsr;
64616   int nKey;
64617   const char *zKey;
64618 #endif /* local variables moved into u.bn */
64619
64620   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64621   u.bn.pC = p->apCsr[pOp->p1];
64622   assert( u.bn.pC!=0 );
64623   pIn2 = &aMem[pOp->p2];
64624   assert( pIn2->flags & MEM_Blob );
64625   u.bn.pCrsr = u.bn.pC->pCursor;
64626   if( ALWAYS(u.bn.pCrsr!=0) ){
64627     assert( u.bn.pC->isTable==0 );
64628     rc = ExpandBlob(pIn2);
64629     if( rc==SQLITE_OK ){
64630       u.bn.nKey = pIn2->n;
64631       u.bn.zKey = pIn2->z;
64632       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
64633           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
64634       );
64635       assert( u.bn.pC->deferredMoveto==0 );
64636       u.bn.pC->cacheStatus = CACHE_STALE;
64637     }
64638   }
64639   break;
64640 }
64641
64642 /* Opcode: IdxDelete P1 P2 P3 * *
64643 **
64644 ** The content of P3 registers starting at register P2 form
64645 ** an unpacked index key. This opcode removes that entry from the 
64646 ** index opened by cursor P1.
64647 */
64648 case OP_IdxDelete: {
64649 #if 0  /* local variables moved into u.bo */
64650   VdbeCursor *pC;
64651   BtCursor *pCrsr;
64652   int res;
64653   UnpackedRecord r;
64654 #endif /* local variables moved into u.bo */
64655
64656   assert( pOp->p3>0 );
64657   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
64658   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64659   u.bo.pC = p->apCsr[pOp->p1];
64660   assert( u.bo.pC!=0 );
64661   u.bo.pCrsr = u.bo.pC->pCursor;
64662   if( ALWAYS(u.bo.pCrsr!=0) ){
64663     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
64664     u.bo.r.nField = (u16)pOp->p3;
64665     u.bo.r.flags = 0;
64666     u.bo.r.aMem = &aMem[pOp->p2];
64667 #ifdef SQLITE_DEBUG
64668     { int i; for(i=0; i<u.bo.r.nField; i++) assert( memIsValid(&u.bo.r.aMem[i]) ); }
64669 #endif
64670     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
64671     if( rc==SQLITE_OK && u.bo.res==0 ){
64672       rc = sqlite3BtreeDelete(u.bo.pCrsr);
64673     }
64674     assert( u.bo.pC->deferredMoveto==0 );
64675     u.bo.pC->cacheStatus = CACHE_STALE;
64676   }
64677   break;
64678 }
64679
64680 /* Opcode: IdxRowid P1 P2 * * *
64681 **
64682 ** Write into register P2 an integer which is the last entry in the record at
64683 ** the end of the index key pointed to by cursor P1.  This integer should be
64684 ** the rowid of the table entry to which this index entry points.
64685 **
64686 ** See also: Rowid, MakeRecord.
64687 */
64688 case OP_IdxRowid: {              /* out2-prerelease */
64689 #if 0  /* local variables moved into u.bp */
64690   BtCursor *pCrsr;
64691   VdbeCursor *pC;
64692   i64 rowid;
64693 #endif /* local variables moved into u.bp */
64694
64695   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64696   u.bp.pC = p->apCsr[pOp->p1];
64697   assert( u.bp.pC!=0 );
64698   u.bp.pCrsr = u.bp.pC->pCursor;
64699   pOut->flags = MEM_Null;
64700   if( ALWAYS(u.bp.pCrsr!=0) ){
64701     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
64702     if( NEVER(rc) ) goto abort_due_to_error;
64703     assert( u.bp.pC->deferredMoveto==0 );
64704     assert( u.bp.pC->isTable==0 );
64705     if( !u.bp.pC->nullRow ){
64706       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
64707       if( rc!=SQLITE_OK ){
64708         goto abort_due_to_error;
64709       }
64710       pOut->u.i = u.bp.rowid;
64711       pOut->flags = MEM_Int;
64712     }
64713   }
64714   break;
64715 }
64716
64717 /* Opcode: IdxGE P1 P2 P3 P4 P5
64718 **
64719 ** The P4 register values beginning with P3 form an unpacked index 
64720 ** key that omits the ROWID.  Compare this key value against the index 
64721 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
64722 **
64723 ** If the P1 index entry is greater than or equal to the key value
64724 ** then jump to P2.  Otherwise fall through to the next instruction.
64725 **
64726 ** If P5 is non-zero then the key value is increased by an epsilon 
64727 ** prior to the comparison.  This make the opcode work like IdxGT except
64728 ** that if the key from register P3 is a prefix of the key in the cursor,
64729 ** the result is false whereas it would be true with IdxGT.
64730 */
64731 /* Opcode: IdxLT P1 P2 P3 P4 P5
64732 **
64733 ** The P4 register values beginning with P3 form an unpacked index 
64734 ** key that omits the ROWID.  Compare this key value against the index 
64735 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
64736 **
64737 ** If the P1 index entry is less than the key value then jump to P2.
64738 ** Otherwise fall through to the next instruction.
64739 **
64740 ** If P5 is non-zero then the key value is increased by an epsilon prior 
64741 ** to the comparison.  This makes the opcode work like IdxLE.
64742 */
64743 case OP_IdxLT:          /* jump */
64744 case OP_IdxGE: {        /* jump */
64745 #if 0  /* local variables moved into u.bq */
64746   VdbeCursor *pC;
64747   int res;
64748   UnpackedRecord r;
64749 #endif /* local variables moved into u.bq */
64750
64751   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
64752   u.bq.pC = p->apCsr[pOp->p1];
64753   assert( u.bq.pC!=0 );
64754   assert( u.bq.pC->isOrdered );
64755   if( ALWAYS(u.bq.pC->pCursor!=0) ){
64756     assert( u.bq.pC->deferredMoveto==0 );
64757     assert( pOp->p5==0 || pOp->p5==1 );
64758     assert( pOp->p4type==P4_INT32 );
64759     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
64760     u.bq.r.nField = (u16)pOp->p4.i;
64761     if( pOp->p5 ){
64762       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
64763     }else{
64764       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
64765     }
64766     u.bq.r.aMem = &aMem[pOp->p3];
64767 #ifdef SQLITE_DEBUG
64768     { int i; for(i=0; i<u.bq.r.nField; i++) assert( memIsValid(&u.bq.r.aMem[i]) ); }
64769 #endif
64770     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
64771     if( pOp->opcode==OP_IdxLT ){
64772       u.bq.res = -u.bq.res;
64773     }else{
64774       assert( pOp->opcode==OP_IdxGE );
64775       u.bq.res++;
64776     }
64777     if( u.bq.res>0 ){
64778       pc = pOp->p2 - 1 ;
64779     }
64780   }
64781   break;
64782 }
64783
64784 /* Opcode: Destroy P1 P2 P3 * *
64785 **
64786 ** Delete an entire database table or index whose root page in the database
64787 ** file is given by P1.
64788 **
64789 ** The table being destroyed is in the main database file if P3==0.  If
64790 ** P3==1 then the table to be clear is in the auxiliary database file
64791 ** that is used to store tables create using CREATE TEMPORARY TABLE.
64792 **
64793 ** If AUTOVACUUM is enabled then it is possible that another root page
64794 ** might be moved into the newly deleted root page in order to keep all
64795 ** root pages contiguous at the beginning of the database.  The former
64796 ** value of the root page that moved - its value before the move occurred -
64797 ** is stored in register P2.  If no page 
64798 ** movement was required (because the table being dropped was already 
64799 ** the last one in the database) then a zero is stored in register P2.
64800 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
64801 **
64802 ** See also: Clear
64803 */
64804 case OP_Destroy: {     /* out2-prerelease */
64805 #if 0  /* local variables moved into u.br */
64806   int iMoved;
64807   int iCnt;
64808   Vdbe *pVdbe;
64809   int iDb;
64810 #endif /* local variables moved into u.br */
64811 #ifndef SQLITE_OMIT_VIRTUALTABLE
64812   u.br.iCnt = 0;
64813   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
64814     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
64815       u.br.iCnt++;
64816     }
64817   }
64818 #else
64819   u.br.iCnt = db->activeVdbeCnt;
64820 #endif
64821   pOut->flags = MEM_Null;
64822   if( u.br.iCnt>1 ){
64823     rc = SQLITE_LOCKED;
64824     p->errorAction = OE_Abort;
64825   }else{
64826     u.br.iDb = pOp->p3;
64827     assert( u.br.iCnt==1 );
64828     assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
64829     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
64830     pOut->flags = MEM_Int;
64831     pOut->u.i = u.br.iMoved;
64832 #ifndef SQLITE_OMIT_AUTOVACUUM
64833     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
64834       sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
64835       resetSchemaOnFault = 1;
64836     }
64837 #endif
64838   }
64839   break;
64840 }
64841
64842 /* Opcode: Clear P1 P2 P3
64843 **
64844 ** Delete all contents of the database table or index whose root page
64845 ** in the database file is given by P1.  But, unlike Destroy, do not
64846 ** remove the table or index from the database file.
64847 **
64848 ** The table being clear is in the main database file if P2==0.  If
64849 ** P2==1 then the table to be clear is in the auxiliary database file
64850 ** that is used to store tables create using CREATE TEMPORARY TABLE.
64851 **
64852 ** If the P3 value is non-zero, then the table referred to must be an
64853 ** intkey table (an SQL table, not an index). In this case the row change 
64854 ** count is incremented by the number of rows in the table being cleared. 
64855 ** If P3 is greater than zero, then the value stored in register P3 is
64856 ** also incremented by the number of rows in the table being cleared.
64857 **
64858 ** See also: Destroy
64859 */
64860 case OP_Clear: {
64861 #if 0  /* local variables moved into u.bs */
64862   int nChange;
64863 #endif /* local variables moved into u.bs */
64864
64865   u.bs.nChange = 0;
64866   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
64867   rc = sqlite3BtreeClearTable(
64868       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
64869   );
64870   if( pOp->p3 ){
64871     p->nChange += u.bs.nChange;
64872     if( pOp->p3>0 ){
64873       assert( memIsValid(&aMem[pOp->p3]) );
64874       memAboutToChange(p, &aMem[pOp->p3]);
64875       aMem[pOp->p3].u.i += u.bs.nChange;
64876     }
64877   }
64878   break;
64879 }
64880
64881 /* Opcode: CreateTable P1 P2 * * *
64882 **
64883 ** Allocate a new table in the main database file if P1==0 or in the
64884 ** auxiliary database file if P1==1 or in an attached database if
64885 ** P1>1.  Write the root page number of the new table into
64886 ** register P2
64887 **
64888 ** The difference between a table and an index is this:  A table must
64889 ** have a 4-byte integer key and can have arbitrary data.  An index
64890 ** has an arbitrary key but no data.
64891 **
64892 ** See also: CreateIndex
64893 */
64894 /* Opcode: CreateIndex P1 P2 * * *
64895 **
64896 ** Allocate a new index in the main database file if P1==0 or in the
64897 ** auxiliary database file if P1==1 or in an attached database if
64898 ** P1>1.  Write the root page number of the new table into
64899 ** register P2.
64900 **
64901 ** See documentation on OP_CreateTable for additional information.
64902 */
64903 case OP_CreateIndex:            /* out2-prerelease */
64904 case OP_CreateTable: {          /* out2-prerelease */
64905 #if 0  /* local variables moved into u.bt */
64906   int pgno;
64907   int flags;
64908   Db *pDb;
64909 #endif /* local variables moved into u.bt */
64910
64911   u.bt.pgno = 0;
64912   assert( pOp->p1>=0 && pOp->p1<db->nDb );
64913   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
64914   u.bt.pDb = &db->aDb[pOp->p1];
64915   assert( u.bt.pDb->pBt!=0 );
64916   if( pOp->opcode==OP_CreateTable ){
64917     /* u.bt.flags = BTREE_INTKEY; */
64918     u.bt.flags = BTREE_INTKEY;
64919   }else{
64920     u.bt.flags = BTREE_BLOBKEY;
64921   }
64922   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
64923   pOut->u.i = u.bt.pgno;
64924   break;
64925 }
64926
64927 /* Opcode: ParseSchema P1 P2 * P4 *
64928 **
64929 ** Read and parse all entries from the SQLITE_MASTER table of database P1
64930 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
64931 ** the parsing if P2 is true.  If P2 is false, then this routine is a
64932 ** no-op if the schema is not currently loaded.  In other words, if P2
64933 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
64934 ** schema is already loaded into the symbol table.
64935 **
64936 ** This opcode invokes the parser to create a new virtual machine,
64937 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
64938 */
64939 case OP_ParseSchema: {
64940 #if 0  /* local variables moved into u.bu */
64941   int iDb;
64942   const char *zMaster;
64943   char *zSql;
64944   InitData initData;
64945 #endif /* local variables moved into u.bu */
64946
64947   u.bu.iDb = pOp->p1;
64948   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
64949
64950   /* If pOp->p2 is 0, then this opcode is being executed to read a
64951   ** single row, for example the row corresponding to a new index
64952   ** created by this VDBE, from the sqlite_master table. It only
64953   ** does this if the corresponding in-memory schema is currently
64954   ** loaded. Otherwise, the new index definition can be loaded along
64955   ** with the rest of the schema when it is required.
64956   **
64957   ** Although the mutex on the BtShared object that corresponds to
64958   ** database u.bu.iDb (the database containing the sqlite_master table
64959   ** read by this instruction) is currently held, it is necessary to
64960   ** obtain the mutexes on all attached databases before checking if
64961   ** the schema of u.bu.iDb is loaded. This is because, at the start of
64962   ** the sqlite3_exec() call below, SQLite will invoke
64963   ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
64964   ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
64965   ** this happens, then some other thread may delete the in-memory
64966   ** schema of database u.bu.iDb before the SQL statement runs. The schema
64967   ** will not be reloaded becuase the db->init.busy flag is set. This
64968   ** can result in a "no such table: sqlite_master" or "malformed
64969   ** database schema" error being returned to the user.
64970   */
64971   assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
64972   sqlite3BtreeEnterAll(db);
64973   if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
64974     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
64975     u.bu.initData.db = db;
64976     u.bu.initData.iDb = pOp->p1;
64977     u.bu.initData.pzErrMsg = &p->zErrMsg;
64978     u.bu.zSql = sqlite3MPrintf(db,
64979        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
64980        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
64981     if( u.bu.zSql==0 ){
64982       rc = SQLITE_NOMEM;
64983     }else{
64984       assert( db->init.busy==0 );
64985       db->init.busy = 1;
64986       u.bu.initData.rc = SQLITE_OK;
64987       assert( !db->mallocFailed );
64988       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
64989       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
64990       sqlite3DbFree(db, u.bu.zSql);
64991       db->init.busy = 0;
64992     }
64993   }
64994   sqlite3BtreeLeaveAll(db);
64995   if( rc==SQLITE_NOMEM ){
64996     goto no_mem;
64997   }
64998   break;
64999 }
65000
65001 #if !defined(SQLITE_OMIT_ANALYZE)
65002 /* Opcode: LoadAnalysis P1 * * * *
65003 **
65004 ** Read the sqlite_stat1 table for database P1 and load the content
65005 ** of that table into the internal index hash table.  This will cause
65006 ** the analysis to be used when preparing all subsequent queries.
65007 */
65008 case OP_LoadAnalysis: {
65009   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65010   rc = sqlite3AnalysisLoad(db, pOp->p1);
65011   break;  
65012 }
65013 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
65014
65015 /* Opcode: DropTable P1 * * P4 *
65016 **
65017 ** Remove the internal (in-memory) data structures that describe
65018 ** the table named P4 in database P1.  This is called after a table
65019 ** is dropped in order to keep the internal representation of the
65020 ** schema consistent with what is on disk.
65021 */
65022 case OP_DropTable: {
65023   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
65024   break;
65025 }
65026
65027 /* Opcode: DropIndex P1 * * P4 *
65028 **
65029 ** Remove the internal (in-memory) data structures that describe
65030 ** the index named P4 in database P1.  This is called after an index
65031 ** is dropped in order to keep the internal representation of the
65032 ** schema consistent with what is on disk.
65033 */
65034 case OP_DropIndex: {
65035   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
65036   break;
65037 }
65038
65039 /* Opcode: DropTrigger P1 * * P4 *
65040 **
65041 ** Remove the internal (in-memory) data structures that describe
65042 ** the trigger named P4 in database P1.  This is called after a trigger
65043 ** is dropped in order to keep the internal representation of the
65044 ** schema consistent with what is on disk.
65045 */
65046 case OP_DropTrigger: {
65047   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
65048   break;
65049 }
65050
65051
65052 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
65053 /* Opcode: IntegrityCk P1 P2 P3 * P5
65054 **
65055 ** Do an analysis of the currently open database.  Store in
65056 ** register P1 the text of an error message describing any problems.
65057 ** If no problems are found, store a NULL in register P1.
65058 **
65059 ** The register P3 contains the maximum number of allowed errors.
65060 ** At most reg(P3) errors will be reported.
65061 ** In other words, the analysis stops as soon as reg(P1) errors are 
65062 ** seen.  Reg(P1) is updated with the number of errors remaining.
65063 **
65064 ** The root page numbers of all tables in the database are integer
65065 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
65066 ** total.
65067 **
65068 ** If P5 is not zero, the check is done on the auxiliary database
65069 ** file, not the main database file.
65070 **
65071 ** This opcode is used to implement the integrity_check pragma.
65072 */
65073 case OP_IntegrityCk: {
65074 #if 0  /* local variables moved into u.bv */
65075   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
65076   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
65077   int j;          /* Loop counter */
65078   int nErr;       /* Number of errors reported */
65079   char *z;        /* Text of the error report */
65080   Mem *pnErr;     /* Register keeping track of errors remaining */
65081 #endif /* local variables moved into u.bv */
65082
65083   u.bv.nRoot = pOp->p2;
65084   assert( u.bv.nRoot>0 );
65085   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
65086   if( u.bv.aRoot==0 ) goto no_mem;
65087   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65088   u.bv.pnErr = &aMem[pOp->p3];
65089   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
65090   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
65091   pIn1 = &aMem[pOp->p1];
65092   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
65093     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
65094   }
65095   u.bv.aRoot[u.bv.j] = 0;
65096   assert( pOp->p5<db->nDb );
65097   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
65098   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
65099                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
65100   sqlite3DbFree(db, u.bv.aRoot);
65101   u.bv.pnErr->u.i -= u.bv.nErr;
65102   sqlite3VdbeMemSetNull(pIn1);
65103   if( u.bv.nErr==0 ){
65104     assert( u.bv.z==0 );
65105   }else if( u.bv.z==0 ){
65106     goto no_mem;
65107   }else{
65108     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
65109   }
65110   UPDATE_MAX_BLOBSIZE(pIn1);
65111   sqlite3VdbeChangeEncoding(pIn1, encoding);
65112   break;
65113 }
65114 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
65115
65116 /* Opcode: RowSetAdd P1 P2 * * *
65117 **
65118 ** Insert the integer value held by register P2 into a boolean index
65119 ** held in register P1.
65120 **
65121 ** An assertion fails if P2 is not an integer.
65122 */
65123 case OP_RowSetAdd: {       /* in1, in2 */
65124   pIn1 = &aMem[pOp->p1];
65125   pIn2 = &aMem[pOp->p2];
65126   assert( (pIn2->flags & MEM_Int)!=0 );
65127   if( (pIn1->flags & MEM_RowSet)==0 ){
65128     sqlite3VdbeMemSetRowSet(pIn1);
65129     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
65130   }
65131   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
65132   break;
65133 }
65134
65135 /* Opcode: RowSetRead P1 P2 P3 * *
65136 **
65137 ** Extract the smallest value from boolean index P1 and put that value into
65138 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
65139 ** unchanged and jump to instruction P2.
65140 */
65141 case OP_RowSetRead: {       /* jump, in1, out3 */
65142 #if 0  /* local variables moved into u.bw */
65143   i64 val;
65144 #endif /* local variables moved into u.bw */
65145   CHECK_FOR_INTERRUPT;
65146   pIn1 = &aMem[pOp->p1];
65147   if( (pIn1->flags & MEM_RowSet)==0
65148    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
65149   ){
65150     /* The boolean index is empty */
65151     sqlite3VdbeMemSetNull(pIn1);
65152     pc = pOp->p2 - 1;
65153   }else{
65154     /* A value was pulled from the index */
65155     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
65156   }
65157   break;
65158 }
65159
65160 /* Opcode: RowSetTest P1 P2 P3 P4
65161 **
65162 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
65163 ** contains a RowSet object and that RowSet object contains
65164 ** the value held in P3, jump to register P2. Otherwise, insert the
65165 ** integer in P3 into the RowSet and continue on to the
65166 ** next opcode.
65167 **
65168 ** The RowSet object is optimized for the case where successive sets
65169 ** of integers, where each set contains no duplicates. Each set
65170 ** of values is identified by a unique P4 value. The first set
65171 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
65172 ** non-negative.  For non-negative values of P4 only the lower 4
65173 ** bits are significant.
65174 **
65175 ** This allows optimizations: (a) when P4==0 there is no need to test
65176 ** the rowset object for P3, as it is guaranteed not to contain it,
65177 ** (b) when P4==-1 there is no need to insert the value, as it will
65178 ** never be tested for, and (c) when a value that is part of set X is
65179 ** inserted, there is no need to search to see if the same value was
65180 ** previously inserted as part of set X (only if it was previously
65181 ** inserted as part of some other set).
65182 */
65183 case OP_RowSetTest: {                     /* jump, in1, in3 */
65184 #if 0  /* local variables moved into u.bx */
65185   int iSet;
65186   int exists;
65187 #endif /* local variables moved into u.bx */
65188
65189   pIn1 = &aMem[pOp->p1];
65190   pIn3 = &aMem[pOp->p3];
65191   u.bx.iSet = pOp->p4.i;
65192   assert( pIn3->flags&MEM_Int );
65193
65194   /* If there is anything other than a rowset object in memory cell P1,
65195   ** delete it now and initialize P1 with an empty rowset
65196   */
65197   if( (pIn1->flags & MEM_RowSet)==0 ){
65198     sqlite3VdbeMemSetRowSet(pIn1);
65199     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
65200   }
65201
65202   assert( pOp->p4type==P4_INT32 );
65203   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
65204   if( u.bx.iSet ){
65205     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
65206                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
65207                                pIn3->u.i);
65208     if( u.bx.exists ){
65209       pc = pOp->p2 - 1;
65210       break;
65211     }
65212   }
65213   if( u.bx.iSet>=0 ){
65214     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
65215   }
65216   break;
65217 }
65218
65219
65220 #ifndef SQLITE_OMIT_TRIGGER
65221
65222 /* Opcode: Program P1 P2 P3 P4 *
65223 **
65224 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
65225 **
65226 ** P1 contains the address of the memory cell that contains the first memory 
65227 ** cell in an array of values used as arguments to the sub-program. P2 
65228 ** contains the address to jump to if the sub-program throws an IGNORE 
65229 ** exception using the RAISE() function. Register P3 contains the address 
65230 ** of a memory cell in this (the parent) VM that is used to allocate the 
65231 ** memory required by the sub-vdbe at runtime.
65232 **
65233 ** P4 is a pointer to the VM containing the trigger program.
65234 */
65235 case OP_Program: {        /* jump */
65236 #if 0  /* local variables moved into u.by */
65237   int nMem;               /* Number of memory registers for sub-program */
65238   int nByte;              /* Bytes of runtime space required for sub-program */
65239   Mem *pRt;               /* Register to allocate runtime space */
65240   Mem *pMem;              /* Used to iterate through memory cells */
65241   Mem *pEnd;              /* Last memory cell in new array */
65242   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
65243   SubProgram *pProgram;   /* Sub-program to execute */
65244   void *t;                /* Token identifying trigger */
65245 #endif /* local variables moved into u.by */
65246
65247   u.by.pProgram = pOp->p4.pProgram;
65248   u.by.pRt = &aMem[pOp->p3];
65249   assert( memIsValid(u.by.pRt) );
65250   assert( u.by.pProgram->nOp>0 );
65251
65252   /* If the p5 flag is clear, then recursive invocation of triggers is
65253   ** disabled for backwards compatibility (p5 is set if this sub-program
65254   ** is really a trigger, not a foreign key action, and the flag set
65255   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
65256   **
65257   ** It is recursive invocation of triggers, at the SQL level, that is
65258   ** disabled. In some cases a single trigger may generate more than one
65259   ** SubProgram (if the trigger may be executed with more than one different
65260   ** ON CONFLICT algorithm). SubProgram structures associated with a
65261   ** single trigger all have the same value for the SubProgram.token
65262   ** variable.  */
65263   if( pOp->p5 ){
65264     u.by.t = u.by.pProgram->token;
65265     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
65266     if( u.by.pFrame ) break;
65267   }
65268
65269   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
65270     rc = SQLITE_ERROR;
65271     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
65272     break;
65273   }
65274
65275   /* Register u.by.pRt is used to store the memory required to save the state
65276   ** of the current program, and the memory required at runtime to execute
65277   ** the trigger program. If this trigger has been fired before, then u.by.pRt
65278   ** is already allocated. Otherwise, it must be initialized.  */
65279   if( (u.by.pRt->flags&MEM_Frame)==0 ){
65280     /* SubProgram.nMem is set to the number of memory cells used by the
65281     ** program stored in SubProgram.aOp. As well as these, one memory
65282     ** cell is required for each cursor used by the program. Set local
65283     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
65284     */
65285     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
65286     u.by.nByte = ROUND8(sizeof(VdbeFrame))
65287               + u.by.nMem * sizeof(Mem)
65288               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
65289     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
65290     if( !u.by.pFrame ){
65291       goto no_mem;
65292     }
65293     sqlite3VdbeMemRelease(u.by.pRt);
65294     u.by.pRt->flags = MEM_Frame;
65295     u.by.pRt->u.pFrame = u.by.pFrame;
65296
65297     u.by.pFrame->v = p;
65298     u.by.pFrame->nChildMem = u.by.nMem;
65299     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
65300     u.by.pFrame->pc = pc;
65301     u.by.pFrame->aMem = p->aMem;
65302     u.by.pFrame->nMem = p->nMem;
65303     u.by.pFrame->apCsr = p->apCsr;
65304     u.by.pFrame->nCursor = p->nCursor;
65305     u.by.pFrame->aOp = p->aOp;
65306     u.by.pFrame->nOp = p->nOp;
65307     u.by.pFrame->token = u.by.pProgram->token;
65308
65309     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
65310     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
65311       u.by.pMem->flags = MEM_Null;
65312       u.by.pMem->db = db;
65313     }
65314   }else{
65315     u.by.pFrame = u.by.pRt->u.pFrame;
65316     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
65317     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
65318     assert( pc==u.by.pFrame->pc );
65319   }
65320
65321   p->nFrame++;
65322   u.by.pFrame->pParent = p->pFrame;
65323   u.by.pFrame->lastRowid = db->lastRowid;
65324   u.by.pFrame->nChange = p->nChange;
65325   p->nChange = 0;
65326   p->pFrame = u.by.pFrame;
65327   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
65328   p->nMem = u.by.pFrame->nChildMem;
65329   p->nCursor = (u16)u.by.pFrame->nChildCsr;
65330   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
65331   p->aOp = aOp = u.by.pProgram->aOp;
65332   p->nOp = u.by.pProgram->nOp;
65333   pc = -1;
65334
65335   break;
65336 }
65337
65338 /* Opcode: Param P1 P2 * * *
65339 **
65340 ** This opcode is only ever present in sub-programs called via the 
65341 ** OP_Program instruction. Copy a value currently stored in a memory 
65342 ** cell of the calling (parent) frame to cell P2 in the current frames 
65343 ** address space. This is used by trigger programs to access the new.* 
65344 ** and old.* values.
65345 **
65346 ** The address of the cell in the parent frame is determined by adding
65347 ** the value of the P1 argument to the value of the P1 argument to the
65348 ** calling OP_Program instruction.
65349 */
65350 case OP_Param: {           /* out2-prerelease */
65351 #if 0  /* local variables moved into u.bz */
65352   VdbeFrame *pFrame;
65353   Mem *pIn;
65354 #endif /* local variables moved into u.bz */
65355   u.bz.pFrame = p->pFrame;
65356   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
65357   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
65358   break;
65359 }
65360
65361 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
65362
65363 #ifndef SQLITE_OMIT_FOREIGN_KEY
65364 /* Opcode: FkCounter P1 P2 * * *
65365 **
65366 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
65367 ** If P1 is non-zero, the database constraint counter is incremented 
65368 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
65369 ** statement counter is incremented (immediate foreign key constraints).
65370 */
65371 case OP_FkCounter: {
65372   if( pOp->p1 ){
65373     db->nDeferredCons += pOp->p2;
65374   }else{
65375     p->nFkConstraint += pOp->p2;
65376   }
65377   break;
65378 }
65379
65380 /* Opcode: FkIfZero P1 P2 * * *
65381 **
65382 ** This opcode tests if a foreign key constraint-counter is currently zero.
65383 ** If so, jump to instruction P2. Otherwise, fall through to the next 
65384 ** instruction.
65385 **
65386 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
65387 ** is zero (the one that counts deferred constraint violations). If P1 is
65388 ** zero, the jump is taken if the statement constraint-counter is zero
65389 ** (immediate foreign key constraint violations).
65390 */
65391 case OP_FkIfZero: {         /* jump */
65392   if( pOp->p1 ){
65393     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
65394   }else{
65395     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
65396   }
65397   break;
65398 }
65399 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
65400
65401 #ifndef SQLITE_OMIT_AUTOINCREMENT
65402 /* Opcode: MemMax P1 P2 * * *
65403 **
65404 ** P1 is a register in the root frame of this VM (the root frame is
65405 ** different from the current frame if this instruction is being executed
65406 ** within a sub-program). Set the value of register P1 to the maximum of 
65407 ** its current value and the value in register P2.
65408 **
65409 ** This instruction throws an error if the memory cell is not initially
65410 ** an integer.
65411 */
65412 case OP_MemMax: {        /* in2 */
65413 #if 0  /* local variables moved into u.ca */
65414   Mem *pIn1;
65415   VdbeFrame *pFrame;
65416 #endif /* local variables moved into u.ca */
65417   if( p->pFrame ){
65418     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
65419     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
65420   }else{
65421     u.ca.pIn1 = &aMem[pOp->p1];
65422   }
65423   assert( memIsValid(u.ca.pIn1) );
65424   sqlite3VdbeMemIntegerify(u.ca.pIn1);
65425   pIn2 = &aMem[pOp->p2];
65426   sqlite3VdbeMemIntegerify(pIn2);
65427   if( u.ca.pIn1->u.i<pIn2->u.i){
65428     u.ca.pIn1->u.i = pIn2->u.i;
65429   }
65430   break;
65431 }
65432 #endif /* SQLITE_OMIT_AUTOINCREMENT */
65433
65434 /* Opcode: IfPos P1 P2 * * *
65435 **
65436 ** If the value of register P1 is 1 or greater, jump to P2.
65437 **
65438 ** It is illegal to use this instruction on a register that does
65439 ** not contain an integer.  An assertion fault will result if you try.
65440 */
65441 case OP_IfPos: {        /* jump, in1 */
65442   pIn1 = &aMem[pOp->p1];
65443   assert( pIn1->flags&MEM_Int );
65444   if( pIn1->u.i>0 ){
65445      pc = pOp->p2 - 1;
65446   }
65447   break;
65448 }
65449
65450 /* Opcode: IfNeg P1 P2 * * *
65451 **
65452 ** If the value of register P1 is less than zero, jump to P2. 
65453 **
65454 ** It is illegal to use this instruction on a register that does
65455 ** not contain an integer.  An assertion fault will result if you try.
65456 */
65457 case OP_IfNeg: {        /* jump, in1 */
65458   pIn1 = &aMem[pOp->p1];
65459   assert( pIn1->flags&MEM_Int );
65460   if( pIn1->u.i<0 ){
65461      pc = pOp->p2 - 1;
65462   }
65463   break;
65464 }
65465
65466 /* Opcode: IfZero P1 P2 P3 * *
65467 **
65468 ** The register P1 must contain an integer.  Add literal P3 to the
65469 ** value in register P1.  If the result is exactly 0, jump to P2. 
65470 **
65471 ** It is illegal to use this instruction on a register that does
65472 ** not contain an integer.  An assertion fault will result if you try.
65473 */
65474 case OP_IfZero: {        /* jump, in1 */
65475   pIn1 = &aMem[pOp->p1];
65476   assert( pIn1->flags&MEM_Int );
65477   pIn1->u.i += pOp->p3;
65478   if( pIn1->u.i==0 ){
65479      pc = pOp->p2 - 1;
65480   }
65481   break;
65482 }
65483
65484 /* Opcode: AggStep * P2 P3 P4 P5
65485 **
65486 ** Execute the step function for an aggregate.  The
65487 ** function has P5 arguments.   P4 is a pointer to the FuncDef
65488 ** structure that specifies the function.  Use register
65489 ** P3 as the accumulator.
65490 **
65491 ** The P5 arguments are taken from register P2 and its
65492 ** successors.
65493 */
65494 case OP_AggStep: {
65495 #if 0  /* local variables moved into u.cb */
65496   int n;
65497   int i;
65498   Mem *pMem;
65499   Mem *pRec;
65500   sqlite3_context ctx;
65501   sqlite3_value **apVal;
65502 #endif /* local variables moved into u.cb */
65503
65504   u.cb.n = pOp->p5;
65505   assert( u.cb.n>=0 );
65506   u.cb.pRec = &aMem[pOp->p2];
65507   u.cb.apVal = p->apArg;
65508   assert( u.cb.apVal || u.cb.n==0 );
65509   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
65510     assert( memIsValid(u.cb.pRec) );
65511     u.cb.apVal[u.cb.i] = u.cb.pRec;
65512     memAboutToChange(p, u.cb.pRec);
65513     sqlite3VdbeMemStoreType(u.cb.pRec);
65514   }
65515   u.cb.ctx.pFunc = pOp->p4.pFunc;
65516   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65517   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
65518   u.cb.pMem->n++;
65519   u.cb.ctx.s.flags = MEM_Null;
65520   u.cb.ctx.s.z = 0;
65521   u.cb.ctx.s.zMalloc = 0;
65522   u.cb.ctx.s.xDel = 0;
65523   u.cb.ctx.s.db = db;
65524   u.cb.ctx.isError = 0;
65525   u.cb.ctx.pColl = 0;
65526   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
65527     assert( pOp>p->aOp );
65528     assert( pOp[-1].p4type==P4_COLLSEQ );
65529     assert( pOp[-1].opcode==OP_CollSeq );
65530     u.cb.ctx.pColl = pOp[-1].p4.pColl;
65531   }
65532   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal); /* IMP: R-24505-23230 */
65533   if( u.cb.ctx.isError ){
65534     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
65535     rc = u.cb.ctx.isError;
65536   }
65537   sqlite3VdbeMemRelease(&u.cb.ctx.s);
65538   break;
65539 }
65540
65541 /* Opcode: AggFinal P1 P2 * P4 *
65542 **
65543 ** Execute the finalizer function for an aggregate.  P1 is
65544 ** the memory location that is the accumulator for the aggregate.
65545 **
65546 ** P2 is the number of arguments that the step function takes and
65547 ** P4 is a pointer to the FuncDef for this function.  The P2
65548 ** argument is not used by this opcode.  It is only there to disambiguate
65549 ** functions that can take varying numbers of arguments.  The
65550 ** P4 argument is only needed for the degenerate case where
65551 ** the step function was not previously called.
65552 */
65553 case OP_AggFinal: {
65554 #if 0  /* local variables moved into u.cc */
65555   Mem *pMem;
65556 #endif /* local variables moved into u.cc */
65557   assert( pOp->p1>0 && pOp->p1<=p->nMem );
65558   u.cc.pMem = &aMem[pOp->p1];
65559   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
65560   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
65561   if( rc ){
65562     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
65563   }
65564   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
65565   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
65566   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
65567     goto too_big;
65568   }
65569   break;
65570 }
65571
65572 #ifndef SQLITE_OMIT_WAL
65573 /* Opcode: Checkpoint P1 * * * *
65574 **
65575 ** Checkpoint database P1. This is a no-op if P1 is not currently in
65576 ** WAL mode.
65577 */
65578 case OP_Checkpoint: {
65579   rc = sqlite3Checkpoint(db, pOp->p1);
65580   break;
65581 };  
65582 #endif
65583
65584 #ifndef SQLITE_OMIT_PRAGMA
65585 /* Opcode: JournalMode P1 P2 P3 * P5
65586 **
65587 ** Change the journal mode of database P1 to P3. P3 must be one of the
65588 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
65589 ** modes (delete, truncate, persist, off and memory), this is a simple
65590 ** operation. No IO is required.
65591 **
65592 ** If changing into or out of WAL mode the procedure is more complicated.
65593 **
65594 ** Write a string containing the final journal-mode to register P2.
65595 */
65596 case OP_JournalMode: {    /* out2-prerelease */
65597 #if 0  /* local variables moved into u.cd */
65598   Btree *pBt;                     /* Btree to change journal mode of */
65599   Pager *pPager;                  /* Pager associated with pBt */
65600   int eNew;                       /* New journal mode */
65601   int eOld;                       /* The old journal mode */
65602   const char *zFilename;          /* Name of database file for pPager */
65603 #endif /* local variables moved into u.cd */
65604
65605   u.cd.eNew = pOp->p3;
65606   assert( u.cd.eNew==PAGER_JOURNALMODE_DELETE
65607        || u.cd.eNew==PAGER_JOURNALMODE_TRUNCATE
65608        || u.cd.eNew==PAGER_JOURNALMODE_PERSIST
65609        || u.cd.eNew==PAGER_JOURNALMODE_OFF
65610        || u.cd.eNew==PAGER_JOURNALMODE_MEMORY
65611        || u.cd.eNew==PAGER_JOURNALMODE_WAL
65612        || u.cd.eNew==PAGER_JOURNALMODE_QUERY
65613   );
65614   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65615
65616   /* This opcode is used in two places: PRAGMA journal_mode and ATTACH.
65617   ** In PRAGMA journal_mode, the sqlite3VdbeUsesBtree() routine is called
65618   ** when the statment is prepared and so p->aMutex.nMutex>0.  All mutexes
65619   ** are already acquired.  But when used in ATTACH, sqlite3VdbeUsesBtree()
65620   ** is not called when the statement is prepared because it requires the
65621   ** iDb index of the database as a parameter, and the database has not
65622   ** yet been attached so that index is unavailable.  We have to wait
65623   ** until runtime (now) to get the mutex on the newly attached database.
65624   ** No other mutexes are required by the ATTACH command so this is safe
65625   ** to do.
65626   */
65627   assert( (p->btreeMask & (1<<pOp->p1))!=0 || p->aMutex.nMutex==0 );
65628   if( p->aMutex.nMutex==0 ){
65629     /* This occurs right after ATTACH.  Get a mutex on the newly ATTACHed
65630     ** database. */
65631     sqlite3VdbeUsesBtree(p, pOp->p1);
65632     sqlite3VdbeMutexArrayEnter(p);
65633   }
65634
65635   u.cd.pBt = db->aDb[pOp->p1].pBt;
65636   u.cd.pPager = sqlite3BtreePager(u.cd.pBt);
65637   u.cd.eOld = sqlite3PagerGetJournalMode(u.cd.pPager);
65638   if( u.cd.eNew==PAGER_JOURNALMODE_QUERY ) u.cd.eNew = u.cd.eOld;
65639   if( !sqlite3PagerOkToChangeJournalMode(u.cd.pPager) ) u.cd.eNew = u.cd.eOld;
65640
65641 #ifndef SQLITE_OMIT_WAL
65642   u.cd.zFilename = sqlite3PagerFilename(u.cd.pPager);
65643
65644   /* Do not allow a transition to journal_mode=WAL for a database
65645   ** in temporary storage or if the VFS does not support shared memory
65646   */
65647   if( u.cd.eNew==PAGER_JOURNALMODE_WAL
65648    && (u.cd.zFilename[0]==0                         /* Temp file */
65649        || !sqlite3PagerWalSupported(u.cd.pPager))   /* No shared-memory support */
65650   ){
65651     u.cd.eNew = u.cd.eOld;
65652   }
65653
65654   if( (u.cd.eNew!=u.cd.eOld)
65655    && (u.cd.eOld==PAGER_JOURNALMODE_WAL || u.cd.eNew==PAGER_JOURNALMODE_WAL)
65656   ){
65657     if( !db->autoCommit || db->activeVdbeCnt>1 ){
65658       rc = SQLITE_ERROR;
65659       sqlite3SetString(&p->zErrMsg, db,
65660           "cannot change %s wal mode from within a transaction",
65661           (u.cd.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
65662       );
65663       break;
65664     }else{
65665
65666       if( u.cd.eOld==PAGER_JOURNALMODE_WAL ){
65667         /* If leaving WAL mode, close the log file. If successful, the call
65668         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
65669         ** file. An EXCLUSIVE lock may still be held on the database file
65670         ** after a successful return.
65671         */
65672         rc = sqlite3PagerCloseWal(u.cd.pPager);
65673         if( rc==SQLITE_OK ){
65674           sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
65675         }
65676       }else if( u.cd.eOld==PAGER_JOURNALMODE_MEMORY ){
65677         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
65678         ** as an intermediate */
65679         sqlite3PagerSetJournalMode(u.cd.pPager, PAGER_JOURNALMODE_OFF);
65680       }
65681
65682       /* Open a transaction on the database file. Regardless of the journal
65683       ** mode, this transaction always uses a rollback journal.
65684       */
65685       assert( sqlite3BtreeIsInTrans(u.cd.pBt)==0 );
65686       if( rc==SQLITE_OK ){
65687         rc = sqlite3BtreeSetVersion(u.cd.pBt, (u.cd.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
65688       }
65689     }
65690   }
65691 #endif /* ifndef SQLITE_OMIT_WAL */
65692
65693   if( rc ){
65694     u.cd.eNew = u.cd.eOld;
65695   }
65696   u.cd.eNew = sqlite3PagerSetJournalMode(u.cd.pPager, u.cd.eNew);
65697
65698   pOut = &aMem[pOp->p2];
65699   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
65700   pOut->z = (char *)sqlite3JournalModename(u.cd.eNew);
65701   pOut->n = sqlite3Strlen30(pOut->z);
65702   pOut->enc = SQLITE_UTF8;
65703   sqlite3VdbeChangeEncoding(pOut, encoding);
65704   break;
65705 };
65706 #endif /* SQLITE_OMIT_PRAGMA */
65707
65708 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
65709 /* Opcode: Vacuum * * * * *
65710 **
65711 ** Vacuum the entire database.  This opcode will cause other virtual
65712 ** machines to be created and run.  It may not be called from within
65713 ** a transaction.
65714 */
65715 case OP_Vacuum: {
65716   rc = sqlite3RunVacuum(&p->zErrMsg, db);
65717   break;
65718 }
65719 #endif
65720
65721 #if !defined(SQLITE_OMIT_AUTOVACUUM)
65722 /* Opcode: IncrVacuum P1 P2 * * *
65723 **
65724 ** Perform a single step of the incremental vacuum procedure on
65725 ** the P1 database. If the vacuum has finished, jump to instruction
65726 ** P2. Otherwise, fall through to the next instruction.
65727 */
65728 case OP_IncrVacuum: {        /* jump */
65729 #if 0  /* local variables moved into u.ce */
65730   Btree *pBt;
65731 #endif /* local variables moved into u.ce */
65732
65733   assert( pOp->p1>=0 && pOp->p1<db->nDb );
65734   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
65735   u.ce.pBt = db->aDb[pOp->p1].pBt;
65736   rc = sqlite3BtreeIncrVacuum(u.ce.pBt);
65737   if( rc==SQLITE_DONE ){
65738     pc = pOp->p2 - 1;
65739     rc = SQLITE_OK;
65740   }
65741   break;
65742 }
65743 #endif
65744
65745 /* Opcode: Expire P1 * * * *
65746 **
65747 ** Cause precompiled statements to become expired. An expired statement
65748 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
65749 ** (via sqlite3_step()).
65750 ** 
65751 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
65752 ** then only the currently executing statement is affected. 
65753 */
65754 case OP_Expire: {
65755   if( !pOp->p1 ){
65756     sqlite3ExpirePreparedStatements(db);
65757   }else{
65758     p->expired = 1;
65759   }
65760   break;
65761 }
65762
65763 #ifndef SQLITE_OMIT_SHARED_CACHE
65764 /* Opcode: TableLock P1 P2 P3 P4 *
65765 **
65766 ** Obtain a lock on a particular table. This instruction is only used when
65767 ** the shared-cache feature is enabled. 
65768 **
65769 ** P1 is the index of the database in sqlite3.aDb[] of the database
65770 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
65771 ** a write lock if P3==1.
65772 **
65773 ** P2 contains the root-page of the table to lock.
65774 **
65775 ** P4 contains a pointer to the name of the table being locked. This is only
65776 ** used to generate an error message if the lock cannot be obtained.
65777 */
65778 case OP_TableLock: {
65779   u8 isWriteLock = (u8)pOp->p3;
65780   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
65781     int p1 = pOp->p1; 
65782     assert( p1>=0 && p1<db->nDb );
65783     assert( (p->btreeMask & (1<<p1))!=0 );
65784     assert( isWriteLock==0 || isWriteLock==1 );
65785     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
65786     if( (rc&0xFF)==SQLITE_LOCKED ){
65787       const char *z = pOp->p4.z;
65788       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
65789     }
65790   }
65791   break;
65792 }
65793 #endif /* SQLITE_OMIT_SHARED_CACHE */
65794
65795 #ifndef SQLITE_OMIT_VIRTUALTABLE
65796 /* Opcode: VBegin * * * P4 *
65797 **
65798 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
65799 ** xBegin method for that table.
65800 **
65801 ** Also, whether or not P4 is set, check that this is not being called from
65802 ** within a callback to a virtual table xSync() method. If it is, the error
65803 ** code will be set to SQLITE_LOCKED.
65804 */
65805 case OP_VBegin: {
65806 #if 0  /* local variables moved into u.cf */
65807   VTable *pVTab;
65808 #endif /* local variables moved into u.cf */
65809   u.cf.pVTab = pOp->p4.pVtab;
65810   rc = sqlite3VtabBegin(db, u.cf.pVTab);
65811   if( u.cf.pVTab ) importVtabErrMsg(p, u.cf.pVTab->pVtab);
65812   break;
65813 }
65814 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65815
65816 #ifndef SQLITE_OMIT_VIRTUALTABLE
65817 /* Opcode: VCreate P1 * * P4 *
65818 **
65819 ** P4 is the name of a virtual table in database P1. Call the xCreate method
65820 ** for that table.
65821 */
65822 case OP_VCreate: {
65823   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
65824   break;
65825 }
65826 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65827
65828 #ifndef SQLITE_OMIT_VIRTUALTABLE
65829 /* Opcode: VDestroy P1 * * P4 *
65830 **
65831 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
65832 ** of that table.
65833 */
65834 case OP_VDestroy: {
65835   p->inVtabMethod = 2;
65836   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
65837   p->inVtabMethod = 0;
65838   break;
65839 }
65840 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65841
65842 #ifndef SQLITE_OMIT_VIRTUALTABLE
65843 /* Opcode: VOpen P1 * * P4 *
65844 **
65845 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
65846 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
65847 ** table and stores that cursor in P1.
65848 */
65849 case OP_VOpen: {
65850 #if 0  /* local variables moved into u.cg */
65851   VdbeCursor *pCur;
65852   sqlite3_vtab_cursor *pVtabCursor;
65853   sqlite3_vtab *pVtab;
65854   sqlite3_module *pModule;
65855 #endif /* local variables moved into u.cg */
65856
65857   u.cg.pCur = 0;
65858   u.cg.pVtabCursor = 0;
65859   u.cg.pVtab = pOp->p4.pVtab->pVtab;
65860   u.cg.pModule = (sqlite3_module *)u.cg.pVtab->pModule;
65861   assert(u.cg.pVtab && u.cg.pModule);
65862   rc = u.cg.pModule->xOpen(u.cg.pVtab, &u.cg.pVtabCursor);
65863   importVtabErrMsg(p, u.cg.pVtab);
65864   if( SQLITE_OK==rc ){
65865     /* Initialize sqlite3_vtab_cursor base class */
65866     u.cg.pVtabCursor->pVtab = u.cg.pVtab;
65867
65868     /* Initialise vdbe cursor object */
65869     u.cg.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
65870     if( u.cg.pCur ){
65871       u.cg.pCur->pVtabCursor = u.cg.pVtabCursor;
65872       u.cg.pCur->pModule = u.cg.pVtabCursor->pVtab->pModule;
65873     }else{
65874       db->mallocFailed = 1;
65875       u.cg.pModule->xClose(u.cg.pVtabCursor);
65876     }
65877   }
65878   break;
65879 }
65880 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65881
65882 #ifndef SQLITE_OMIT_VIRTUALTABLE
65883 /* Opcode: VFilter P1 P2 P3 P4 *
65884 **
65885 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
65886 ** the filtered result set is empty.
65887 **
65888 ** P4 is either NULL or a string that was generated by the xBestIndex
65889 ** method of the module.  The interpretation of the P4 string is left
65890 ** to the module implementation.
65891 **
65892 ** This opcode invokes the xFilter method on the virtual table specified
65893 ** by P1.  The integer query plan parameter to xFilter is stored in register
65894 ** P3. Register P3+1 stores the argc parameter to be passed to the
65895 ** xFilter method. Registers P3+2..P3+1+argc are the argc
65896 ** additional parameters which are passed to
65897 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
65898 **
65899 ** A jump is made to P2 if the result set after filtering would be empty.
65900 */
65901 case OP_VFilter: {   /* jump */
65902 #if 0  /* local variables moved into u.ch */
65903   int nArg;
65904   int iQuery;
65905   const sqlite3_module *pModule;
65906   Mem *pQuery;
65907   Mem *pArgc;
65908   sqlite3_vtab_cursor *pVtabCursor;
65909   sqlite3_vtab *pVtab;
65910   VdbeCursor *pCur;
65911   int res;
65912   int i;
65913   Mem **apArg;
65914 #endif /* local variables moved into u.ch */
65915
65916   u.ch.pQuery = &aMem[pOp->p3];
65917   u.ch.pArgc = &u.ch.pQuery[1];
65918   u.ch.pCur = p->apCsr[pOp->p1];
65919   assert( memIsValid(u.ch.pQuery) );
65920   REGISTER_TRACE(pOp->p3, u.ch.pQuery);
65921   assert( u.ch.pCur->pVtabCursor );
65922   u.ch.pVtabCursor = u.ch.pCur->pVtabCursor;
65923   u.ch.pVtab = u.ch.pVtabCursor->pVtab;
65924   u.ch.pModule = u.ch.pVtab->pModule;
65925
65926   /* Grab the index number and argc parameters */
65927   assert( (u.ch.pQuery->flags&MEM_Int)!=0 && u.ch.pArgc->flags==MEM_Int );
65928   u.ch.nArg = (int)u.ch.pArgc->u.i;
65929   u.ch.iQuery = (int)u.ch.pQuery->u.i;
65930
65931   /* Invoke the xFilter method */
65932   {
65933     u.ch.res = 0;
65934     u.ch.apArg = p->apArg;
65935     for(u.ch.i = 0; u.ch.i<u.ch.nArg; u.ch.i++){
65936       u.ch.apArg[u.ch.i] = &u.ch.pArgc[u.ch.i+1];
65937       sqlite3VdbeMemStoreType(u.ch.apArg[u.ch.i]);
65938     }
65939
65940     p->inVtabMethod = 1;
65941     rc = u.ch.pModule->xFilter(u.ch.pVtabCursor, u.ch.iQuery, pOp->p4.z, u.ch.nArg, u.ch.apArg);
65942     p->inVtabMethod = 0;
65943     importVtabErrMsg(p, u.ch.pVtab);
65944     if( rc==SQLITE_OK ){
65945       u.ch.res = u.ch.pModule->xEof(u.ch.pVtabCursor);
65946     }
65947
65948     if( u.ch.res ){
65949       pc = pOp->p2 - 1;
65950     }
65951   }
65952   u.ch.pCur->nullRow = 0;
65953
65954   break;
65955 }
65956 #endif /* SQLITE_OMIT_VIRTUALTABLE */
65957
65958 #ifndef SQLITE_OMIT_VIRTUALTABLE
65959 /* Opcode: VColumn P1 P2 P3 * *
65960 **
65961 ** Store the value of the P2-th column of
65962 ** the row of the virtual-table that the 
65963 ** P1 cursor is pointing to into register P3.
65964 */
65965 case OP_VColumn: {
65966 #if 0  /* local variables moved into u.ci */
65967   sqlite3_vtab *pVtab;
65968   const sqlite3_module *pModule;
65969   Mem *pDest;
65970   sqlite3_context sContext;
65971 #endif /* local variables moved into u.ci */
65972
65973   VdbeCursor *pCur = p->apCsr[pOp->p1];
65974   assert( pCur->pVtabCursor );
65975   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65976   u.ci.pDest = &aMem[pOp->p3];
65977   memAboutToChange(p, u.ci.pDest);
65978   if( pCur->nullRow ){
65979     sqlite3VdbeMemSetNull(u.ci.pDest);
65980     break;
65981   }
65982   u.ci.pVtab = pCur->pVtabCursor->pVtab;
65983   u.ci.pModule = u.ci.pVtab->pModule;
65984   assert( u.ci.pModule->xColumn );
65985   memset(&u.ci.sContext, 0, sizeof(u.ci.sContext));
65986
65987   /* The output cell may already have a buffer allocated. Move
65988   ** the current contents to u.ci.sContext.s so in case the user-function
65989   ** can use the already allocated buffer instead of allocating a
65990   ** new one.
65991   */
65992   sqlite3VdbeMemMove(&u.ci.sContext.s, u.ci.pDest);
65993   MemSetTypeFlag(&u.ci.sContext.s, MEM_Null);
65994
65995   rc = u.ci.pModule->xColumn(pCur->pVtabCursor, &u.ci.sContext, pOp->p2);
65996   importVtabErrMsg(p, u.ci.pVtab);
65997   if( u.ci.sContext.isError ){
65998     rc = u.ci.sContext.isError;
65999   }
66000
66001   /* Copy the result of the function to the P3 register. We
66002   ** do this regardless of whether or not an error occurred to ensure any
66003   ** dynamic allocation in u.ci.sContext.s (a Mem struct) is  released.
66004   */
66005   sqlite3VdbeChangeEncoding(&u.ci.sContext.s, encoding);
66006   sqlite3VdbeMemMove(u.ci.pDest, &u.ci.sContext.s);
66007   REGISTER_TRACE(pOp->p3, u.ci.pDest);
66008   UPDATE_MAX_BLOBSIZE(u.ci.pDest);
66009
66010   if( sqlite3VdbeMemTooBig(u.ci.pDest) ){
66011     goto too_big;
66012   }
66013   break;
66014 }
66015 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66016
66017 #ifndef SQLITE_OMIT_VIRTUALTABLE
66018 /* Opcode: VNext P1 P2 * * *
66019 **
66020 ** Advance virtual table P1 to the next row in its result set and
66021 ** jump to instruction P2.  Or, if the virtual table has reached
66022 ** the end of its result set, then fall through to the next instruction.
66023 */
66024 case OP_VNext: {   /* jump */
66025 #if 0  /* local variables moved into u.cj */
66026   sqlite3_vtab *pVtab;
66027   const sqlite3_module *pModule;
66028   int res;
66029   VdbeCursor *pCur;
66030 #endif /* local variables moved into u.cj */
66031
66032   u.cj.res = 0;
66033   u.cj.pCur = p->apCsr[pOp->p1];
66034   assert( u.cj.pCur->pVtabCursor );
66035   if( u.cj.pCur->nullRow ){
66036     break;
66037   }
66038   u.cj.pVtab = u.cj.pCur->pVtabCursor->pVtab;
66039   u.cj.pModule = u.cj.pVtab->pModule;
66040   assert( u.cj.pModule->xNext );
66041
66042   /* Invoke the xNext() method of the module. There is no way for the
66043   ** underlying implementation to return an error if one occurs during
66044   ** xNext(). Instead, if an error occurs, true is returned (indicating that
66045   ** data is available) and the error code returned when xColumn or
66046   ** some other method is next invoked on the save virtual table cursor.
66047   */
66048   p->inVtabMethod = 1;
66049   rc = u.cj.pModule->xNext(u.cj.pCur->pVtabCursor);
66050   p->inVtabMethod = 0;
66051   importVtabErrMsg(p, u.cj.pVtab);
66052   if( rc==SQLITE_OK ){
66053     u.cj.res = u.cj.pModule->xEof(u.cj.pCur->pVtabCursor);
66054   }
66055
66056   if( !u.cj.res ){
66057     /* If there is data, jump to P2 */
66058     pc = pOp->p2 - 1;
66059   }
66060   break;
66061 }
66062 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66063
66064 #ifndef SQLITE_OMIT_VIRTUALTABLE
66065 /* Opcode: VRename P1 * * P4 *
66066 **
66067 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
66068 ** This opcode invokes the corresponding xRename method. The value
66069 ** in register P1 is passed as the zName argument to the xRename method.
66070 */
66071 case OP_VRename: {
66072 #if 0  /* local variables moved into u.ck */
66073   sqlite3_vtab *pVtab;
66074   Mem *pName;
66075 #endif /* local variables moved into u.ck */
66076
66077   u.ck.pVtab = pOp->p4.pVtab->pVtab;
66078   u.ck.pName = &aMem[pOp->p1];
66079   assert( u.ck.pVtab->pModule->xRename );
66080   assert( memIsValid(u.ck.pName) );
66081   REGISTER_TRACE(pOp->p1, u.ck.pName);
66082   assert( u.ck.pName->flags & MEM_Str );
66083   rc = u.ck.pVtab->pModule->xRename(u.ck.pVtab, u.ck.pName->z);
66084   importVtabErrMsg(p, u.ck.pVtab);
66085   p->expired = 0;
66086
66087   break;
66088 }
66089 #endif
66090
66091 #ifndef SQLITE_OMIT_VIRTUALTABLE
66092 /* Opcode: VUpdate P1 P2 P3 P4 *
66093 **
66094 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
66095 ** This opcode invokes the corresponding xUpdate method. P2 values
66096 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
66097 ** invocation. The value in register (P3+P2-1) corresponds to the 
66098 ** p2th element of the argv array passed to xUpdate.
66099 **
66100 ** The xUpdate method will do a DELETE or an INSERT or both.
66101 ** The argv[0] element (which corresponds to memory cell P3)
66102 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
66103 ** deletion occurs.  The argv[1] element is the rowid of the new 
66104 ** row.  This can be NULL to have the virtual table select the new 
66105 ** rowid for itself.  The subsequent elements in the array are 
66106 ** the values of columns in the new row.
66107 **
66108 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
66109 ** a row to delete.
66110 **
66111 ** P1 is a boolean flag. If it is set to true and the xUpdate call
66112 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
66113 ** is set to the value of the rowid for the row just inserted.
66114 */
66115 case OP_VUpdate: {
66116 #if 0  /* local variables moved into u.cl */
66117   sqlite3_vtab *pVtab;
66118   sqlite3_module *pModule;
66119   int nArg;
66120   int i;
66121   sqlite_int64 rowid;
66122   Mem **apArg;
66123   Mem *pX;
66124 #endif /* local variables moved into u.cl */
66125
66126   u.cl.pVtab = pOp->p4.pVtab->pVtab;
66127   u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
66128   u.cl.nArg = pOp->p2;
66129   assert( pOp->p4type==P4_VTAB );
66130   if( ALWAYS(u.cl.pModule->xUpdate) ){
66131     u.cl.apArg = p->apArg;
66132     u.cl.pX = &aMem[pOp->p3];
66133     for(u.cl.i=0; u.cl.i<u.cl.nArg; u.cl.i++){
66134       assert( memIsValid(u.cl.pX) );
66135       memAboutToChange(p, u.cl.pX);
66136       sqlite3VdbeMemStoreType(u.cl.pX);
66137       u.cl.apArg[u.cl.i] = u.cl.pX;
66138       u.cl.pX++;
66139     }
66140     rc = u.cl.pModule->xUpdate(u.cl.pVtab, u.cl.nArg, u.cl.apArg, &u.cl.rowid);
66141     importVtabErrMsg(p, u.cl.pVtab);
66142     if( rc==SQLITE_OK && pOp->p1 ){
66143       assert( u.cl.nArg>1 && u.cl.apArg[0] && (u.cl.apArg[0]->flags&MEM_Null) );
66144       db->lastRowid = u.cl.rowid;
66145     }
66146     p->nChange++;
66147   }
66148   break;
66149 }
66150 #endif /* SQLITE_OMIT_VIRTUALTABLE */
66151
66152 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
66153 /* Opcode: Pagecount P1 P2 * * *
66154 **
66155 ** Write the current number of pages in database P1 to memory cell P2.
66156 */
66157 case OP_Pagecount: {            /* out2-prerelease */
66158   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
66159   break;
66160 }
66161 #endif
66162
66163
66164 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
66165 /* Opcode: MaxPgcnt P1 P2 P3 * *
66166 **
66167 ** Try to set the maximum page count for database P1 to the value in P3.
66168 ** Do not let the maximum page count fall below the current page count and
66169 ** do not change the maximum page count value if P3==0.
66170 **
66171 ** Store the maximum page count after the change in register P2.
66172 */
66173 case OP_MaxPgcnt: {            /* out2-prerelease */
66174   unsigned int newMax;
66175   Btree *pBt;
66176
66177   pBt = db->aDb[pOp->p1].pBt;
66178   newMax = 0;
66179   if( pOp->p3 ){
66180     newMax = sqlite3BtreeLastPage(pBt);
66181     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
66182   }
66183   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
66184   break;
66185 }
66186 #endif
66187
66188
66189 #ifndef SQLITE_OMIT_TRACE
66190 /* Opcode: Trace * * * P4 *
66191 **
66192 ** If tracing is enabled (by the sqlite3_trace()) interface, then
66193 ** the UTF-8 string contained in P4 is emitted on the trace callback.
66194 */
66195 case OP_Trace: {
66196 #if 0  /* local variables moved into u.cm */
66197   char *zTrace;
66198 #endif /* local variables moved into u.cm */
66199
66200   u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
66201   if( u.cm.zTrace ){
66202     if( db->xTrace ){
66203       char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
66204       db->xTrace(db->pTraceArg, z);
66205       sqlite3DbFree(db, z);
66206     }
66207 #ifdef SQLITE_DEBUG
66208     if( (db->flags & SQLITE_SqlTrace)!=0 ){
66209       sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
66210     }
66211 #endif /* SQLITE_DEBUG */
66212   }
66213   break;
66214 }
66215 #endif
66216
66217
66218 /* Opcode: Noop * * * * *
66219 **
66220 ** Do nothing.  This instruction is often useful as a jump
66221 ** destination.
66222 */
66223 /*
66224 ** The magic Explain opcode are only inserted when explain==2 (which
66225 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
66226 ** This opcode records information from the optimizer.  It is the
66227 ** the same as a no-op.  This opcodesnever appears in a real VM program.
66228 */
66229 default: {          /* This is really OP_Noop and OP_Explain */
66230   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
66231   break;
66232 }
66233
66234 /*****************************************************************************
66235 ** The cases of the switch statement above this line should all be indented
66236 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
66237 ** readability.  From this point on down, the normal indentation rules are
66238 ** restored.
66239 *****************************************************************************/
66240     }
66241
66242 #ifdef VDBE_PROFILE
66243     {
66244       u64 elapsed = sqlite3Hwtime() - start;
66245       pOp->cycles += elapsed;
66246       pOp->cnt++;
66247 #if 0
66248         fprintf(stdout, "%10llu ", elapsed);
66249         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
66250 #endif
66251     }
66252 #endif
66253
66254     /* The following code adds nothing to the actual functionality
66255     ** of the program.  It is only here for testing and debugging.
66256     ** On the other hand, it does burn CPU cycles every time through
66257     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
66258     */
66259 #ifndef NDEBUG
66260     assert( pc>=-1 && pc<p->nOp );
66261
66262 #ifdef SQLITE_DEBUG
66263     if( p->trace ){
66264       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
66265       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
66266         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
66267       }
66268       if( pOp->opflags & OPFLG_OUT3 ){
66269         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
66270       }
66271     }
66272 #endif  /* SQLITE_DEBUG */
66273 #endif  /* NDEBUG */
66274   }  /* The end of the for(;;) loop the loops through opcodes */
66275
66276   /* If we reach this point, it means that execution is finished with
66277   ** an error of some kind.
66278   */
66279 vdbe_error_halt:
66280   assert( rc );
66281   p->rc = rc;
66282   testcase( sqlite3GlobalConfig.xLog!=0 );
66283   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
66284                    pc, p->zSql, p->zErrMsg);
66285   sqlite3VdbeHalt(p);
66286   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
66287   rc = SQLITE_ERROR;
66288   if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
66289
66290   /* This is the only way out of this procedure.  We have to
66291   ** release the mutexes on btrees that were acquired at the
66292   ** top. */
66293 vdbe_return:
66294   sqlite3BtreeMutexArrayLeave(&p->aMutex);
66295   return rc;
66296
66297   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
66298   ** is encountered.
66299   */
66300 too_big:
66301   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
66302   rc = SQLITE_TOOBIG;
66303   goto vdbe_error_halt;
66304
66305   /* Jump to here if a malloc() fails.
66306   */
66307 no_mem:
66308   db->mallocFailed = 1;
66309   sqlite3SetString(&p->zErrMsg, db, "out of memory");
66310   rc = SQLITE_NOMEM;
66311   goto vdbe_error_halt;
66312
66313   /* Jump to here for any other kind of fatal error.  The "rc" variable
66314   ** should hold the error number.
66315   */
66316 abort_due_to_error:
66317   assert( p->zErrMsg==0 );
66318   if( db->mallocFailed ) rc = SQLITE_NOMEM;
66319   if( rc!=SQLITE_IOERR_NOMEM ){
66320     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
66321   }
66322   goto vdbe_error_halt;
66323
66324   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
66325   ** flag.
66326   */
66327 abort_due_to_interrupt:
66328   assert( db->u1.isInterrupted );
66329   rc = SQLITE_INTERRUPT;
66330   p->rc = rc;
66331   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
66332   goto vdbe_error_halt;
66333 }
66334
66335 /************** End of vdbe.c ************************************************/
66336 /************** Begin file vdbeblob.c ****************************************/
66337 /*
66338 ** 2007 May 1
66339 **
66340 ** The author disclaims copyright to this source code.  In place of
66341 ** a legal notice, here is a blessing:
66342 **
66343 **    May you do good and not evil.
66344 **    May you find forgiveness for yourself and forgive others.
66345 **    May you share freely, never taking more than you give.
66346 **
66347 *************************************************************************
66348 **
66349 ** This file contains code used to implement incremental BLOB I/O.
66350 */
66351
66352
66353 #ifndef SQLITE_OMIT_INCRBLOB
66354
66355 /*
66356 ** Valid sqlite3_blob* handles point to Incrblob structures.
66357 */
66358 typedef struct Incrblob Incrblob;
66359 struct Incrblob {
66360   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
66361   int nByte;              /* Size of open blob, in bytes */
66362   int iOffset;            /* Byte offset of blob in cursor data */
66363   int iCol;               /* Table column this handle is open on */
66364   BtCursor *pCsr;         /* Cursor pointing at blob row */
66365   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
66366   sqlite3 *db;            /* The associated database */
66367 };
66368
66369
66370 /*
66371 ** This function is used by both blob_open() and blob_reopen(). It seeks
66372 ** the b-tree cursor associated with blob handle p to point to row iRow.
66373 ** If successful, SQLITE_OK is returned and subsequent calls to
66374 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
66375 **
66376 ** If an error occurs, or if the specified row does not exist or does not
66377 ** contain a value of type TEXT or BLOB in the column nominated when the
66378 ** blob handle was opened, then an error code is returned and *pzErr may
66379 ** be set to point to a buffer containing an error message. It is the
66380 ** responsibility of the caller to free the error message buffer using
66381 ** sqlite3DbFree().
66382 **
66383 ** If an error does occur, then the b-tree cursor is closed. All subsequent
66384 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
66385 ** immediately return SQLITE_ABORT.
66386 */
66387 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
66388   int rc;                         /* Error code */
66389   char *zErr = 0;                 /* Error message */
66390   Vdbe *v = (Vdbe *)p->pStmt;
66391
66392   /* Set the value of the SQL statements only variable to integer iRow. 
66393   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
66394   ** triggering asserts related to mutexes.
66395   */
66396   assert( v->aVar[0].flags&MEM_Int );
66397   v->aVar[0].u.i = iRow;
66398
66399   rc = sqlite3_step(p->pStmt);
66400   if( rc==SQLITE_ROW ){
66401     u32 type = v->apCsr[0]->aType[p->iCol];
66402     if( type<12 ){
66403       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
66404           type==0?"null": type==7?"real": "integer"
66405       );
66406       rc = SQLITE_ERROR;
66407       sqlite3_finalize(p->pStmt);
66408       p->pStmt = 0;
66409     }else{
66410       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
66411       p->nByte = sqlite3VdbeSerialTypeLen(type);
66412       p->pCsr =  v->apCsr[0]->pCursor;
66413       sqlite3BtreeEnterCursor(p->pCsr);
66414       sqlite3BtreeCacheOverflow(p->pCsr);
66415       sqlite3BtreeLeaveCursor(p->pCsr);
66416     }
66417   }
66418
66419   if( rc==SQLITE_ROW ){
66420     rc = SQLITE_OK;
66421   }else if( p->pStmt ){
66422     rc = sqlite3_finalize(p->pStmt);
66423     p->pStmt = 0;
66424     if( rc==SQLITE_OK ){
66425       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
66426       rc = SQLITE_ERROR;
66427     }else{
66428       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
66429     }
66430   }
66431
66432   assert( rc!=SQLITE_OK || zErr==0 );
66433   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
66434
66435   *pzErr = zErr;
66436   return rc;
66437 }
66438
66439 /*
66440 ** Open a blob handle.
66441 */
66442 SQLITE_API int sqlite3_blob_open(
66443   sqlite3* db,            /* The database connection */
66444   const char *zDb,        /* The attached database containing the blob */
66445   const char *zTable,     /* The table containing the blob */
66446   const char *zColumn,    /* The column containing the blob */
66447   sqlite_int64 iRow,      /* The row containing the glob */
66448   int flags,              /* True -> read/write access, false -> read-only */
66449   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
66450 ){
66451   int nAttempt = 0;
66452   int iCol;               /* Index of zColumn in row-record */
66453
66454   /* This VDBE program seeks a btree cursor to the identified 
66455   ** db/table/row entry. The reason for using a vdbe program instead
66456   ** of writing code to use the b-tree layer directly is that the
66457   ** vdbe program will take advantage of the various transaction,
66458   ** locking and error handling infrastructure built into the vdbe.
66459   **
66460   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
66461   ** Code external to the Vdbe then "borrows" the b-tree cursor and
66462   ** uses it to implement the blob_read(), blob_write() and 
66463   ** blob_bytes() functions.
66464   **
66465   ** The sqlite3_blob_close() function finalizes the vdbe program,
66466   ** which closes the b-tree cursor and (possibly) commits the 
66467   ** transaction.
66468   */
66469   static const VdbeOpList openBlob[] = {
66470     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
66471     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
66472     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
66473
66474     /* One of the following two instructions is replaced by an OP_Noop. */
66475     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
66476     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
66477
66478     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
66479     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
66480     {OP_Column, 0, 0, 1},          /* 7  */
66481     {OP_ResultRow, 1, 0, 0},       /* 8  */
66482     {OP_Goto, 0, 5, 0},            /* 9  */
66483     {OP_Close, 0, 0, 0},           /* 10 */
66484     {OP_Halt, 0, 0, 0},            /* 11 */
66485   };
66486
66487   int rc = SQLITE_OK;
66488   char *zErr = 0;
66489   Table *pTab;
66490   Parse *pParse = 0;
66491   Incrblob *pBlob = 0;
66492
66493   flags = !!flags;                /* flags = (flags ? 1 : 0); */
66494   *ppBlob = 0;
66495
66496   sqlite3_mutex_enter(db->mutex);
66497
66498   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
66499   if( !pBlob ) goto blob_open_out;
66500   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
66501   if( !pParse ) goto blob_open_out;
66502
66503   do {
66504     memset(pParse, 0, sizeof(Parse));
66505     pParse->db = db;
66506     sqlite3DbFree(db, zErr);
66507     zErr = 0;
66508
66509     sqlite3BtreeEnterAll(db);
66510     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
66511     if( pTab && IsVirtual(pTab) ){
66512       pTab = 0;
66513       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
66514     }
66515 #ifndef SQLITE_OMIT_VIEW
66516     if( pTab && pTab->pSelect ){
66517       pTab = 0;
66518       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
66519     }
66520 #endif
66521     if( !pTab ){
66522       if( pParse->zErrMsg ){
66523         sqlite3DbFree(db, zErr);
66524         zErr = pParse->zErrMsg;
66525         pParse->zErrMsg = 0;
66526       }
66527       rc = SQLITE_ERROR;
66528       sqlite3BtreeLeaveAll(db);
66529       goto blob_open_out;
66530     }
66531
66532     /* Now search pTab for the exact column. */
66533     for(iCol=0; iCol<pTab->nCol; iCol++) {
66534       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
66535         break;
66536       }
66537     }
66538     if( iCol==pTab->nCol ){
66539       sqlite3DbFree(db, zErr);
66540       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
66541       rc = SQLITE_ERROR;
66542       sqlite3BtreeLeaveAll(db);
66543       goto blob_open_out;
66544     }
66545
66546     /* If the value is being opened for writing, check that the
66547     ** column is not indexed, and that it is not part of a foreign key. 
66548     ** It is against the rules to open a column to which either of these
66549     ** descriptions applies for writing.  */
66550     if( flags ){
66551       const char *zFault = 0;
66552       Index *pIdx;
66553 #ifndef SQLITE_OMIT_FOREIGN_KEY
66554       if( db->flags&SQLITE_ForeignKeys ){
66555         /* Check that the column is not part of an FK child key definition. It
66556         ** is not necessary to check if it is part of a parent key, as parent
66557         ** key columns must be indexed. The check below will pick up this 
66558         ** case.  */
66559         FKey *pFKey;
66560         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
66561           int j;
66562           for(j=0; j<pFKey->nCol; j++){
66563             if( pFKey->aCol[j].iFrom==iCol ){
66564               zFault = "foreign key";
66565             }
66566           }
66567         }
66568       }
66569 #endif
66570       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
66571         int j;
66572         for(j=0; j<pIdx->nColumn; j++){
66573           if( pIdx->aiColumn[j]==iCol ){
66574             zFault = "indexed";
66575           }
66576         }
66577       }
66578       if( zFault ){
66579         sqlite3DbFree(db, zErr);
66580         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
66581         rc = SQLITE_ERROR;
66582         sqlite3BtreeLeaveAll(db);
66583         goto blob_open_out;
66584       }
66585     }
66586
66587     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
66588     assert( pBlob->pStmt || db->mallocFailed );
66589     if( pBlob->pStmt ){
66590       Vdbe *v = (Vdbe *)pBlob->pStmt;
66591       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
66592
66593       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
66594
66595
66596       /* Configure the OP_Transaction */
66597       sqlite3VdbeChangeP1(v, 0, iDb);
66598       sqlite3VdbeChangeP2(v, 0, flags);
66599
66600       /* Configure the OP_VerifyCookie */
66601       sqlite3VdbeChangeP1(v, 1, iDb);
66602       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
66603
66604       /* Make sure a mutex is held on the table to be accessed */
66605       sqlite3VdbeUsesBtree(v, iDb); 
66606
66607       /* Configure the OP_TableLock instruction */
66608 #ifdef SQLITE_OMIT_SHARED_CACHE
66609       sqlite3VdbeChangeToNoop(v, 2, 1);
66610 #else
66611       sqlite3VdbeChangeP1(v, 2, iDb);
66612       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
66613       sqlite3VdbeChangeP3(v, 2, flags);
66614       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
66615 #endif
66616
66617       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
66618       ** parameter of the other to pTab->tnum.  */
66619       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
66620       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
66621       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
66622
66623       /* Configure the number of columns. Configure the cursor to
66624       ** think that the table has one more column than it really
66625       ** does. An OP_Column to retrieve this imaginary column will
66626       ** always return an SQL NULL. This is useful because it means
66627       ** we can invoke OP_Column to fill in the vdbe cursors type 
66628       ** and offset cache without causing any IO.
66629       */
66630       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
66631       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
66632       if( !db->mallocFailed ){
66633         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
66634       }
66635     }
66636    
66637     pBlob->flags = flags;
66638     pBlob->iCol = iCol;
66639     pBlob->db = db;
66640     sqlite3BtreeLeaveAll(db);
66641     if( db->mallocFailed ){
66642       goto blob_open_out;
66643     }
66644     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
66645     rc = blobSeekToRow(pBlob, iRow, &zErr);
66646   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
66647
66648 blob_open_out:
66649   if( rc==SQLITE_OK && db->mallocFailed==0 ){
66650     *ppBlob = (sqlite3_blob *)pBlob;
66651   }else{
66652     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
66653     sqlite3DbFree(db, pBlob);
66654   }
66655   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
66656   sqlite3DbFree(db, zErr);
66657   sqlite3StackFree(db, pParse);
66658   rc = sqlite3ApiExit(db, rc);
66659   sqlite3_mutex_leave(db->mutex);
66660   return rc;
66661 }
66662
66663 /*
66664 ** Close a blob handle that was previously created using
66665 ** sqlite3_blob_open().
66666 */
66667 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
66668   Incrblob *p = (Incrblob *)pBlob;
66669   int rc;
66670   sqlite3 *db;
66671
66672   if( p ){
66673     db = p->db;
66674     sqlite3_mutex_enter(db->mutex);
66675     rc = sqlite3_finalize(p->pStmt);
66676     sqlite3DbFree(db, p);
66677     sqlite3_mutex_leave(db->mutex);
66678   }else{
66679     rc = SQLITE_OK;
66680   }
66681   return rc;
66682 }
66683
66684 /*
66685 ** Perform a read or write operation on a blob
66686 */
66687 static int blobReadWrite(
66688   sqlite3_blob *pBlob, 
66689   void *z, 
66690   int n, 
66691   int iOffset, 
66692   int (*xCall)(BtCursor*, u32, u32, void*)
66693 ){
66694   int rc;
66695   Incrblob *p = (Incrblob *)pBlob;
66696   Vdbe *v;
66697   sqlite3 *db;
66698
66699   if( p==0 ) return SQLITE_MISUSE_BKPT;
66700   db = p->db;
66701   sqlite3_mutex_enter(db->mutex);
66702   v = (Vdbe*)p->pStmt;
66703
66704   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
66705     /* Request is out of range. Return a transient error. */
66706     rc = SQLITE_ERROR;
66707     sqlite3Error(db, SQLITE_ERROR, 0);
66708   }else if( v==0 ){
66709     /* If there is no statement handle, then the blob-handle has
66710     ** already been invalidated. Return SQLITE_ABORT in this case.
66711     */
66712     rc = SQLITE_ABORT;
66713   }else{
66714     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
66715     ** returned, clean-up the statement handle.
66716     */
66717     assert( db == v->db );
66718     sqlite3BtreeEnterCursor(p->pCsr);
66719     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
66720     sqlite3BtreeLeaveCursor(p->pCsr);
66721     if( rc==SQLITE_ABORT ){
66722       sqlite3VdbeFinalize(v);
66723       p->pStmt = 0;
66724     }else{
66725       db->errCode = rc;
66726       v->rc = rc;
66727     }
66728   }
66729   rc = sqlite3ApiExit(db, rc);
66730   sqlite3_mutex_leave(db->mutex);
66731   return rc;
66732 }
66733
66734 /*
66735 ** Read data from a blob handle.
66736 */
66737 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
66738   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
66739 }
66740
66741 /*
66742 ** Write data to a blob handle.
66743 */
66744 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
66745   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
66746 }
66747
66748 /*
66749 ** Query a blob handle for the size of the data.
66750 **
66751 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
66752 ** so no mutex is required for access.
66753 */
66754 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
66755   Incrblob *p = (Incrblob *)pBlob;
66756   return (p && p->pStmt) ? p->nByte : 0;
66757 }
66758
66759 /*
66760 ** Move an existing blob handle to point to a different row of the same
66761 ** database table.
66762 **
66763 ** If an error occurs, or if the specified row does not exist or does not
66764 ** contain a blob or text value, then an error code is returned and the
66765 ** database handle error code and message set. If this happens, then all 
66766 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
66767 ** immediately return SQLITE_ABORT.
66768 */
66769 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
66770   int rc;
66771   Incrblob *p = (Incrblob *)pBlob;
66772   sqlite3 *db;
66773
66774   if( p==0 ) return SQLITE_MISUSE_BKPT;
66775   db = p->db;
66776   sqlite3_mutex_enter(db->mutex);
66777
66778   if( p->pStmt==0 ){
66779     /* If there is no statement handle, then the blob-handle has
66780     ** already been invalidated. Return SQLITE_ABORT in this case.
66781     */
66782     rc = SQLITE_ABORT;
66783   }else{
66784     char *zErr;
66785     rc = blobSeekToRow(p, iRow, &zErr);
66786     if( rc!=SQLITE_OK ){
66787       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
66788       sqlite3DbFree(db, zErr);
66789     }
66790     assert( rc!=SQLITE_SCHEMA );
66791   }
66792
66793   rc = sqlite3ApiExit(db, rc);
66794   assert( rc==SQLITE_OK || p->pStmt==0 );
66795   sqlite3_mutex_leave(db->mutex);
66796   return rc;
66797 }
66798
66799 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
66800
66801 /************** End of vdbeblob.c ********************************************/
66802 /************** Begin file journal.c *****************************************/
66803 /*
66804 ** 2007 August 22
66805 **
66806 ** The author disclaims copyright to this source code.  In place of
66807 ** a legal notice, here is a blessing:
66808 **
66809 **    May you do good and not evil.
66810 **    May you find forgiveness for yourself and forgive others.
66811 **    May you share freely, never taking more than you give.
66812 **
66813 *************************************************************************
66814 **
66815 ** This file implements a special kind of sqlite3_file object used
66816 ** by SQLite to create journal files if the atomic-write optimization
66817 ** is enabled.
66818 **
66819 ** The distinctive characteristic of this sqlite3_file is that the
66820 ** actual on disk file is created lazily. When the file is created,
66821 ** the caller specifies a buffer size for an in-memory buffer to
66822 ** be used to service read() and write() requests. The actual file
66823 ** on disk is not created or populated until either:
66824 **
66825 **   1) The in-memory representation grows too large for the allocated 
66826 **      buffer, or
66827 **   2) The sqlite3JournalCreate() function is called.
66828 */
66829 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
66830
66831
66832 /*
66833 ** A JournalFile object is a subclass of sqlite3_file used by
66834 ** as an open file handle for journal files.
66835 */
66836 struct JournalFile {
66837   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
66838   int nBuf;                       /* Size of zBuf[] in bytes */
66839   char *zBuf;                     /* Space to buffer journal writes */
66840   int iSize;                      /* Amount of zBuf[] currently used */
66841   int flags;                      /* xOpen flags */
66842   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
66843   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
66844   const char *zJournal;           /* Name of the journal file */
66845 };
66846 typedef struct JournalFile JournalFile;
66847
66848 /*
66849 ** If it does not already exists, create and populate the on-disk file 
66850 ** for JournalFile p.
66851 */
66852 static int createFile(JournalFile *p){
66853   int rc = SQLITE_OK;
66854   if( !p->pReal ){
66855     sqlite3_file *pReal = (sqlite3_file *)&p[1];
66856     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
66857     if( rc==SQLITE_OK ){
66858       p->pReal = pReal;
66859       if( p->iSize>0 ){
66860         assert(p->iSize<=p->nBuf);
66861         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
66862       }
66863     }
66864   }
66865   return rc;
66866 }
66867
66868 /*
66869 ** Close the file.
66870 */
66871 static int jrnlClose(sqlite3_file *pJfd){
66872   JournalFile *p = (JournalFile *)pJfd;
66873   if( p->pReal ){
66874     sqlite3OsClose(p->pReal);
66875   }
66876   sqlite3_free(p->zBuf);
66877   return SQLITE_OK;
66878 }
66879
66880 /*
66881 ** Read data from the file.
66882 */
66883 static int jrnlRead(
66884   sqlite3_file *pJfd,    /* The journal file from which to read */
66885   void *zBuf,            /* Put the results here */
66886   int iAmt,              /* Number of bytes to read */
66887   sqlite_int64 iOfst     /* Begin reading at this offset */
66888 ){
66889   int rc = SQLITE_OK;
66890   JournalFile *p = (JournalFile *)pJfd;
66891   if( p->pReal ){
66892     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
66893   }else if( (iAmt+iOfst)>p->iSize ){
66894     rc = SQLITE_IOERR_SHORT_READ;
66895   }else{
66896     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
66897   }
66898   return rc;
66899 }
66900
66901 /*
66902 ** Write data to the file.
66903 */
66904 static int jrnlWrite(
66905   sqlite3_file *pJfd,    /* The journal file into which to write */
66906   const void *zBuf,      /* Take data to be written from here */
66907   int iAmt,              /* Number of bytes to write */
66908   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
66909 ){
66910   int rc = SQLITE_OK;
66911   JournalFile *p = (JournalFile *)pJfd;
66912   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
66913     rc = createFile(p);
66914   }
66915   if( rc==SQLITE_OK ){
66916     if( p->pReal ){
66917       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
66918     }else{
66919       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
66920       if( p->iSize<(iOfst+iAmt) ){
66921         p->iSize = (iOfst+iAmt);
66922       }
66923     }
66924   }
66925   return rc;
66926 }
66927
66928 /*
66929 ** Truncate the file.
66930 */
66931 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
66932   int rc = SQLITE_OK;
66933   JournalFile *p = (JournalFile *)pJfd;
66934   if( p->pReal ){
66935     rc = sqlite3OsTruncate(p->pReal, size);
66936   }else if( size<p->iSize ){
66937     p->iSize = size;
66938   }
66939   return rc;
66940 }
66941
66942 /*
66943 ** Sync the file.
66944 */
66945 static int jrnlSync(sqlite3_file *pJfd, int flags){
66946   int rc;
66947   JournalFile *p = (JournalFile *)pJfd;
66948   if( p->pReal ){
66949     rc = sqlite3OsSync(p->pReal, flags);
66950   }else{
66951     rc = SQLITE_OK;
66952   }
66953   return rc;
66954 }
66955
66956 /*
66957 ** Query the size of the file in bytes.
66958 */
66959 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
66960   int rc = SQLITE_OK;
66961   JournalFile *p = (JournalFile *)pJfd;
66962   if( p->pReal ){
66963     rc = sqlite3OsFileSize(p->pReal, pSize);
66964   }else{
66965     *pSize = (sqlite_int64) p->iSize;
66966   }
66967   return rc;
66968 }
66969
66970 /*
66971 ** Table of methods for JournalFile sqlite3_file object.
66972 */
66973 static struct sqlite3_io_methods JournalFileMethods = {
66974   1,             /* iVersion */
66975   jrnlClose,     /* xClose */
66976   jrnlRead,      /* xRead */
66977   jrnlWrite,     /* xWrite */
66978   jrnlTruncate,  /* xTruncate */
66979   jrnlSync,      /* xSync */
66980   jrnlFileSize,  /* xFileSize */
66981   0,             /* xLock */
66982   0,             /* xUnlock */
66983   0,             /* xCheckReservedLock */
66984   0,             /* xFileControl */
66985   0,             /* xSectorSize */
66986   0,             /* xDeviceCharacteristics */
66987   0,             /* xShmMap */
66988   0,             /* xShmLock */
66989   0,             /* xShmBarrier */
66990   0              /* xShmUnmap */
66991 };
66992
66993 /* 
66994 ** Open a journal file.
66995 */
66996 SQLITE_PRIVATE int sqlite3JournalOpen(
66997   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
66998   const char *zName,         /* Name of the journal file */
66999   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
67000   int flags,                 /* Opening flags */
67001   int nBuf                   /* Bytes buffered before opening the file */
67002 ){
67003   JournalFile *p = (JournalFile *)pJfd;
67004   memset(p, 0, sqlite3JournalSize(pVfs));
67005   if( nBuf>0 ){
67006     p->zBuf = sqlite3MallocZero(nBuf);
67007     if( !p->zBuf ){
67008       return SQLITE_NOMEM;
67009     }
67010   }else{
67011     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
67012   }
67013   p->pMethod = &JournalFileMethods;
67014   p->nBuf = nBuf;
67015   p->flags = flags;
67016   p->zJournal = zName;
67017   p->pVfs = pVfs;
67018   return SQLITE_OK;
67019 }
67020
67021 /*
67022 ** If the argument p points to a JournalFile structure, and the underlying
67023 ** file has not yet been created, create it now.
67024 */
67025 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
67026   if( p->pMethods!=&JournalFileMethods ){
67027     return SQLITE_OK;
67028   }
67029   return createFile((JournalFile *)p);
67030 }
67031
67032 /* 
67033 ** Return the number of bytes required to store a JournalFile that uses vfs
67034 ** pVfs to create the underlying on-disk files.
67035 */
67036 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
67037   return (pVfs->szOsFile+sizeof(JournalFile));
67038 }
67039 #endif
67040
67041 /************** End of journal.c *********************************************/
67042 /************** Begin file memjournal.c **************************************/
67043 /*
67044 ** 2008 October 7
67045 **
67046 ** The author disclaims copyright to this source code.  In place of
67047 ** a legal notice, here is a blessing:
67048 **
67049 **    May you do good and not evil.
67050 **    May you find forgiveness for yourself and forgive others.
67051 **    May you share freely, never taking more than you give.
67052 **
67053 *************************************************************************
67054 **
67055 ** This file contains code use to implement an in-memory rollback journal.
67056 ** The in-memory rollback journal is used to journal transactions for
67057 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
67058 */
67059
67060 /* Forward references to internal structures */
67061 typedef struct MemJournal MemJournal;
67062 typedef struct FilePoint FilePoint;
67063 typedef struct FileChunk FileChunk;
67064
67065 /* Space to hold the rollback journal is allocated in increments of
67066 ** this many bytes.
67067 **
67068 ** The size chosen is a little less than a power of two.  That way,
67069 ** the FileChunk object will have a size that almost exactly fills
67070 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
67071 ** memory allocators.
67072 */
67073 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
67074
67075 /* Macro to find the minimum of two numeric values.
67076 */
67077 #ifndef MIN
67078 # define MIN(x,y) ((x)<(y)?(x):(y))
67079 #endif
67080
67081 /*
67082 ** The rollback journal is composed of a linked list of these structures.
67083 */
67084 struct FileChunk {
67085   FileChunk *pNext;               /* Next chunk in the journal */
67086   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
67087 };
67088
67089 /*
67090 ** An instance of this object serves as a cursor into the rollback journal.
67091 ** The cursor can be either for reading or writing.
67092 */
67093 struct FilePoint {
67094   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
67095   FileChunk *pChunk;              /* Specific chunk into which cursor points */
67096 };
67097
67098 /*
67099 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
67100 ** is an instance of this class.
67101 */
67102 struct MemJournal {
67103   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
67104   FileChunk *pFirst;              /* Head of in-memory chunk-list */
67105   FilePoint endpoint;             /* Pointer to the end of the file */
67106   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
67107 };
67108
67109 /*
67110 ** Read data from the in-memory journal file.  This is the implementation
67111 ** of the sqlite3_vfs.xRead method.
67112 */
67113 static int memjrnlRead(
67114   sqlite3_file *pJfd,    /* The journal file from which to read */
67115   void *zBuf,            /* Put the results here */
67116   int iAmt,              /* Number of bytes to read */
67117   sqlite_int64 iOfst     /* Begin reading at this offset */
67118 ){
67119   MemJournal *p = (MemJournal *)pJfd;
67120   u8 *zOut = zBuf;
67121   int nRead = iAmt;
67122   int iChunkOffset;
67123   FileChunk *pChunk;
67124
67125   /* SQLite never tries to read past the end of a rollback journal file */
67126   assert( iOfst+iAmt<=p->endpoint.iOffset );
67127
67128   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
67129     sqlite3_int64 iOff = 0;
67130     for(pChunk=p->pFirst; 
67131         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
67132         pChunk=pChunk->pNext
67133     ){
67134       iOff += JOURNAL_CHUNKSIZE;
67135     }
67136   }else{
67137     pChunk = p->readpoint.pChunk;
67138   }
67139
67140   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
67141   do {
67142     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
67143     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
67144     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
67145     zOut += nCopy;
67146     nRead -= iSpace;
67147     iChunkOffset = 0;
67148   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
67149   p->readpoint.iOffset = iOfst+iAmt;
67150   p->readpoint.pChunk = pChunk;
67151
67152   return SQLITE_OK;
67153 }
67154
67155 /*
67156 ** Write data to the file.
67157 */
67158 static int memjrnlWrite(
67159   sqlite3_file *pJfd,    /* The journal file into which to write */
67160   const void *zBuf,      /* Take data to be written from here */
67161   int iAmt,              /* Number of bytes to write */
67162   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
67163 ){
67164   MemJournal *p = (MemJournal *)pJfd;
67165   int nWrite = iAmt;
67166   u8 *zWrite = (u8 *)zBuf;
67167
67168   /* An in-memory journal file should only ever be appended to. Random
67169   ** access writes are not required by sqlite.
67170   */
67171   assert( iOfst==p->endpoint.iOffset );
67172   UNUSED_PARAMETER(iOfst);
67173
67174   while( nWrite>0 ){
67175     FileChunk *pChunk = p->endpoint.pChunk;
67176     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
67177     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
67178
67179     if( iChunkOffset==0 ){
67180       /* New chunk is required to extend the file. */
67181       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
67182       if( !pNew ){
67183         return SQLITE_IOERR_NOMEM;
67184       }
67185       pNew->pNext = 0;
67186       if( pChunk ){
67187         assert( p->pFirst );
67188         pChunk->pNext = pNew;
67189       }else{
67190         assert( !p->pFirst );
67191         p->pFirst = pNew;
67192       }
67193       p->endpoint.pChunk = pNew;
67194     }
67195
67196     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
67197     zWrite += iSpace;
67198     nWrite -= iSpace;
67199     p->endpoint.iOffset += iSpace;
67200   }
67201
67202   return SQLITE_OK;
67203 }
67204
67205 /*
67206 ** Truncate the file.
67207 */
67208 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
67209   MemJournal *p = (MemJournal *)pJfd;
67210   FileChunk *pChunk;
67211   assert(size==0);
67212   UNUSED_PARAMETER(size);
67213   pChunk = p->pFirst;
67214   while( pChunk ){
67215     FileChunk *pTmp = pChunk;
67216     pChunk = pChunk->pNext;
67217     sqlite3_free(pTmp);
67218   }
67219   sqlite3MemJournalOpen(pJfd);
67220   return SQLITE_OK;
67221 }
67222
67223 /*
67224 ** Close the file.
67225 */
67226 static int memjrnlClose(sqlite3_file *pJfd){
67227   memjrnlTruncate(pJfd, 0);
67228   return SQLITE_OK;
67229 }
67230
67231
67232 /*
67233 ** Sync the file.
67234 **
67235 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
67236 ** is never called in a working implementation.  This implementation
67237 ** exists purely as a contingency, in case some malfunction in some other
67238 ** part of SQLite causes Sync to be called by mistake.
67239 */
67240 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
67241   UNUSED_PARAMETER2(NotUsed, NotUsed2);
67242   return SQLITE_OK;
67243 }
67244
67245 /*
67246 ** Query the size of the file in bytes.
67247 */
67248 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
67249   MemJournal *p = (MemJournal *)pJfd;
67250   *pSize = (sqlite_int64) p->endpoint.iOffset;
67251   return SQLITE_OK;
67252 }
67253
67254 /*
67255 ** Table of methods for MemJournal sqlite3_file object.
67256 */
67257 static const struct sqlite3_io_methods MemJournalMethods = {
67258   1,                /* iVersion */
67259   memjrnlClose,     /* xClose */
67260   memjrnlRead,      /* xRead */
67261   memjrnlWrite,     /* xWrite */
67262   memjrnlTruncate,  /* xTruncate */
67263   memjrnlSync,      /* xSync */
67264   memjrnlFileSize,  /* xFileSize */
67265   0,                /* xLock */
67266   0,                /* xUnlock */
67267   0,                /* xCheckReservedLock */
67268   0,                /* xFileControl */
67269   0,                /* xSectorSize */
67270   0,                /* xDeviceCharacteristics */
67271   0,                /* xShmMap */
67272   0,                /* xShmLock */
67273   0,                /* xShmBarrier */
67274   0                 /* xShmUnlock */
67275 };
67276
67277 /* 
67278 ** Open a journal file.
67279 */
67280 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
67281   MemJournal *p = (MemJournal *)pJfd;
67282   assert( EIGHT_BYTE_ALIGNMENT(p) );
67283   memset(p, 0, sqlite3MemJournalSize());
67284   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
67285 }
67286
67287 /*
67288 ** Return true if the file-handle passed as an argument is 
67289 ** an in-memory journal 
67290 */
67291 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
67292   return pJfd->pMethods==&MemJournalMethods;
67293 }
67294
67295 /* 
67296 ** Return the number of bytes required to store a MemJournal file descriptor.
67297 */
67298 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
67299   return sizeof(MemJournal);
67300 }
67301
67302 /************** End of memjournal.c ******************************************/
67303 /************** Begin file walker.c ******************************************/
67304 /*
67305 ** 2008 August 16
67306 **
67307 ** The author disclaims copyright to this source code.  In place of
67308 ** a legal notice, here is a blessing:
67309 **
67310 **    May you do good and not evil.
67311 **    May you find forgiveness for yourself and forgive others.
67312 **    May you share freely, never taking more than you give.
67313 **
67314 *************************************************************************
67315 ** This file contains routines used for walking the parser tree for
67316 ** an SQL statement.
67317 */
67318
67319
67320 /*
67321 ** Walk an expression tree.  Invoke the callback once for each node
67322 ** of the expression, while decending.  (In other words, the callback
67323 ** is invoked before visiting children.)
67324 **
67325 ** The return value from the callback should be one of the WRC_*
67326 ** constants to specify how to proceed with the walk.
67327 **
67328 **    WRC_Continue      Continue descending down the tree.
67329 **
67330 **    WRC_Prune         Do not descend into child nodes.  But allow
67331 **                      the walk to continue with sibling nodes.
67332 **
67333 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
67334 **                      return the top-level walk call.
67335 **
67336 ** The return value from this routine is WRC_Abort to abandon the tree walk
67337 ** and WRC_Continue to continue.
67338 */
67339 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
67340   int rc;
67341   if( pExpr==0 ) return WRC_Continue;
67342   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
67343   testcase( ExprHasProperty(pExpr, EP_Reduced) );
67344   rc = pWalker->xExprCallback(pWalker, pExpr);
67345   if( rc==WRC_Continue
67346               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
67347     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
67348     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
67349     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
67350       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
67351     }else{
67352       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
67353     }
67354   }
67355   return rc & WRC_Abort;
67356 }
67357
67358 /*
67359 ** Call sqlite3WalkExpr() for every expression in list p or until
67360 ** an abort request is seen.
67361 */
67362 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
67363   int i;
67364   struct ExprList_item *pItem;
67365   if( p ){
67366     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
67367       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
67368     }
67369   }
67370   return WRC_Continue;
67371 }
67372
67373 /*
67374 ** Walk all expressions associated with SELECT statement p.  Do
67375 ** not invoke the SELECT callback on p, but do (of course) invoke
67376 ** any expr callbacks and SELECT callbacks that come from subqueries.
67377 ** Return WRC_Abort or WRC_Continue.
67378 */
67379 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
67380   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
67381   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
67382   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
67383   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
67384   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
67385   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
67386   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
67387   return WRC_Continue;
67388 }
67389
67390 /*
67391 ** Walk the parse trees associated with all subqueries in the
67392 ** FROM clause of SELECT statement p.  Do not invoke the select
67393 ** callback on p, but do invoke it on each FROM clause subquery
67394 ** and on any subqueries further down in the tree.  Return 
67395 ** WRC_Abort or WRC_Continue;
67396 */
67397 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
67398   SrcList *pSrc;
67399   int i;
67400   struct SrcList_item *pItem;
67401
67402   pSrc = p->pSrc;
67403   if( ALWAYS(pSrc) ){
67404     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
67405       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
67406         return WRC_Abort;
67407       }
67408     }
67409   }
67410   return WRC_Continue;
67411
67412
67413 /*
67414 ** Call sqlite3WalkExpr() for every expression in Select statement p.
67415 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
67416 ** on the compound select chain, p->pPrior.
67417 **
67418 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
67419 ** there is an abort request.
67420 **
67421 ** If the Walker does not have an xSelectCallback() then this routine
67422 ** is a no-op returning WRC_Continue.
67423 */
67424 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
67425   int rc;
67426   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
67427   rc = WRC_Continue;
67428   while( p  ){
67429     rc = pWalker->xSelectCallback(pWalker, p);
67430     if( rc ) break;
67431     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
67432     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
67433     p = p->pPrior;
67434   }
67435   return rc & WRC_Abort;
67436 }
67437
67438 /************** End of walker.c **********************************************/
67439 /************** Begin file resolve.c *****************************************/
67440 /*
67441 ** 2008 August 18
67442 **
67443 ** The author disclaims copyright to this source code.  In place of
67444 ** a legal notice, here is a blessing:
67445 **
67446 **    May you do good and not evil.
67447 **    May you find forgiveness for yourself and forgive others.
67448 **    May you share freely, never taking more than you give.
67449 **
67450 *************************************************************************
67451 **
67452 ** This file contains routines used for walking the parser tree and
67453 ** resolve all identifiers by associating them with a particular
67454 ** table and column.
67455 */
67456
67457 /*
67458 ** Turn the pExpr expression into an alias for the iCol-th column of the
67459 ** result set in pEList.
67460 **
67461 ** If the result set column is a simple column reference, then this routine
67462 ** makes an exact copy.  But for any other kind of expression, this
67463 ** routine make a copy of the result set column as the argument to the
67464 ** TK_AS operator.  The TK_AS operator causes the expression to be
67465 ** evaluated just once and then reused for each alias.
67466 **
67467 ** The reason for suppressing the TK_AS term when the expression is a simple
67468 ** column reference is so that the column reference will be recognized as
67469 ** usable by indices within the WHERE clause processing logic. 
67470 **
67471 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
67472 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
67473 **
67474 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
67475 **
67476 ** Is equivalent to:
67477 **
67478 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
67479 **
67480 ** The result of random()%5 in the GROUP BY clause is probably different
67481 ** from the result in the result-set.  We might fix this someday.  Or
67482 ** then again, we might not...
67483 */
67484 static void resolveAlias(
67485   Parse *pParse,         /* Parsing context */
67486   ExprList *pEList,      /* A result set */
67487   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
67488   Expr *pExpr,           /* Transform this into an alias to the result set */
67489   const char *zType      /* "GROUP" or "ORDER" or "" */
67490 ){
67491   Expr *pOrig;           /* The iCol-th column of the result set */
67492   Expr *pDup;            /* Copy of pOrig */
67493   sqlite3 *db;           /* The database connection */
67494
67495   assert( iCol>=0 && iCol<pEList->nExpr );
67496   pOrig = pEList->a[iCol].pExpr;
67497   assert( pOrig!=0 );
67498   assert( pOrig->flags & EP_Resolved );
67499   db = pParse->db;
67500   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
67501     pDup = sqlite3ExprDup(db, pOrig, 0);
67502     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
67503     if( pDup==0 ) return;
67504     if( pEList->a[iCol].iAlias==0 ){
67505       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
67506     }
67507     pDup->iTable = pEList->a[iCol].iAlias;
67508   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
67509     pDup = sqlite3ExprDup(db, pOrig, 0);
67510     if( pDup==0 ) return;
67511   }else{
67512     char *zToken = pOrig->u.zToken;
67513     assert( zToken!=0 );
67514     pOrig->u.zToken = 0;
67515     pDup = sqlite3ExprDup(db, pOrig, 0);
67516     pOrig->u.zToken = zToken;
67517     if( pDup==0 ) return;
67518     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
67519     pDup->flags2 |= EP2_MallocedToken;
67520     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
67521   }
67522   if( pExpr->flags & EP_ExpCollate ){
67523     pDup->pColl = pExpr->pColl;
67524     pDup->flags |= EP_ExpCollate;
67525   }
67526
67527   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
67528   ** prevents ExprDelete() from deleting the Expr structure itself,
67529   ** allowing it to be repopulated by the memcpy() on the following line.
67530   */
67531   ExprSetProperty(pExpr, EP_Static);
67532   sqlite3ExprDelete(db, pExpr);
67533   memcpy(pExpr, pDup, sizeof(*pExpr));
67534   sqlite3DbFree(db, pDup);
67535 }
67536
67537 /*
67538 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
67539 ** that name in the set of source tables in pSrcList and make the pExpr 
67540 ** expression node refer back to that source column.  The following changes
67541 ** are made to pExpr:
67542 **
67543 **    pExpr->iDb           Set the index in db->aDb[] of the database X
67544 **                         (even if X is implied).
67545 **    pExpr->iTable        Set to the cursor number for the table obtained
67546 **                         from pSrcList.
67547 **    pExpr->pTab          Points to the Table structure of X.Y (even if
67548 **                         X and/or Y are implied.)
67549 **    pExpr->iColumn       Set to the column number within the table.
67550 **    pExpr->op            Set to TK_COLUMN.
67551 **    pExpr->pLeft         Any expression this points to is deleted
67552 **    pExpr->pRight        Any expression this points to is deleted.
67553 **
67554 ** The zDb variable is the name of the database (the "X").  This value may be
67555 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
67556 ** can be used.  The zTable variable is the name of the table (the "Y").  This
67557 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
67558 ** means that the form of the name is Z and that columns from any table
67559 ** can be used.
67560 **
67561 ** If the name cannot be resolved unambiguously, leave an error message
67562 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
67563 */
67564 static int lookupName(
67565   Parse *pParse,       /* The parsing context */
67566   const char *zDb,     /* Name of the database containing table, or NULL */
67567   const char *zTab,    /* Name of table containing column, or NULL */
67568   const char *zCol,    /* Name of the column. */
67569   NameContext *pNC,    /* The name context used to resolve the name */
67570   Expr *pExpr          /* Make this EXPR node point to the selected column */
67571 ){
67572   int i, j;            /* Loop counters */
67573   int cnt = 0;                      /* Number of matching column names */
67574   int cntTab = 0;                   /* Number of matching table names */
67575   sqlite3 *db = pParse->db;         /* The database connection */
67576   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
67577   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
67578   NameContext *pTopNC = pNC;        /* First namecontext in the list */
67579   Schema *pSchema = 0;              /* Schema of the expression */
67580   int isTrigger = 0;
67581
67582   assert( pNC );     /* the name context cannot be NULL. */
67583   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
67584   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
67585
67586   /* Initialize the node to no-match */
67587   pExpr->iTable = -1;
67588   pExpr->pTab = 0;
67589   ExprSetIrreducible(pExpr);
67590
67591   /* Start at the inner-most context and move outward until a match is found */
67592   while( pNC && cnt==0 ){
67593     ExprList *pEList;
67594     SrcList *pSrcList = pNC->pSrcList;
67595
67596     if( pSrcList ){
67597       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
67598         Table *pTab;
67599         int iDb;
67600         Column *pCol;
67601   
67602         pTab = pItem->pTab;
67603         assert( pTab!=0 && pTab->zName!=0 );
67604         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
67605         assert( pTab->nCol>0 );
67606         if( zTab ){
67607           if( pItem->zAlias ){
67608             char *zTabName = pItem->zAlias;
67609             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
67610           }else{
67611             char *zTabName = pTab->zName;
67612             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
67613               continue;
67614             }
67615             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
67616               continue;
67617             }
67618           }
67619         }
67620         if( 0==(cntTab++) ){
67621           pExpr->iTable = pItem->iCursor;
67622           pExpr->pTab = pTab;
67623           pSchema = pTab->pSchema;
67624           pMatch = pItem;
67625         }
67626         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
67627           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
67628             IdList *pUsing;
67629             cnt++;
67630             pExpr->iTable = pItem->iCursor;
67631             pExpr->pTab = pTab;
67632             pMatch = pItem;
67633             pSchema = pTab->pSchema;
67634             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
67635             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
67636             if( i<pSrcList->nSrc-1 ){
67637               if( pItem[1].jointype & JT_NATURAL ){
67638                 /* If this match occurred in the left table of a natural join,
67639                 ** then skip the right table to avoid a duplicate match */
67640                 pItem++;
67641                 i++;
67642               }else if( (pUsing = pItem[1].pUsing)!=0 ){
67643                 /* If this match occurs on a column that is in the USING clause
67644                 ** of a join, skip the search of the right table of the join
67645                 ** to avoid a duplicate match there. */
67646                 int k;
67647                 for(k=0; k<pUsing->nId; k++){
67648                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
67649                     pItem++;
67650                     i++;
67651                     break;
67652                   }
67653                 }
67654               }
67655             }
67656             break;
67657           }
67658         }
67659       }
67660     }
67661
67662 #ifndef SQLITE_OMIT_TRIGGER
67663     /* If we have not already resolved the name, then maybe 
67664     ** it is a new.* or old.* trigger argument reference
67665     */
67666     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
67667       int op = pParse->eTriggerOp;
67668       Table *pTab = 0;
67669       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
67670       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
67671         pExpr->iTable = 1;
67672         pTab = pParse->pTriggerTab;
67673       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
67674         pExpr->iTable = 0;
67675         pTab = pParse->pTriggerTab;
67676       }
67677
67678       if( pTab ){ 
67679         int iCol;
67680         pSchema = pTab->pSchema;
67681         cntTab++;
67682         for(iCol=0; iCol<pTab->nCol; iCol++){
67683           Column *pCol = &pTab->aCol[iCol];
67684           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
67685             if( iCol==pTab->iPKey ){
67686               iCol = -1;
67687             }
67688             break;
67689           }
67690         }
67691         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
67692           iCol = -1;        /* IMP: R-44911-55124 */
67693         }
67694         if( iCol<pTab->nCol ){
67695           cnt++;
67696           if( iCol<0 ){
67697             pExpr->affinity = SQLITE_AFF_INTEGER;
67698           }else if( pExpr->iTable==0 ){
67699             testcase( iCol==31 );
67700             testcase( iCol==32 );
67701             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
67702           }else{
67703             testcase( iCol==31 );
67704             testcase( iCol==32 );
67705             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
67706           }
67707           pExpr->iColumn = (i16)iCol;
67708           pExpr->pTab = pTab;
67709           isTrigger = 1;
67710         }
67711       }
67712     }
67713 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
67714
67715     /*
67716     ** Perhaps the name is a reference to the ROWID
67717     */
67718     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
67719       cnt = 1;
67720       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
67721       pExpr->affinity = SQLITE_AFF_INTEGER;
67722     }
67723
67724     /*
67725     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
67726     ** might refer to an result-set alias.  This happens, for example, when
67727     ** we are resolving names in the WHERE clause of the following command:
67728     **
67729     **     SELECT a+b AS x FROM table WHERE x<10;
67730     **
67731     ** In cases like this, replace pExpr with a copy of the expression that
67732     ** forms the result set entry ("a+b" in the example) and return immediately.
67733     ** Note that the expression in the result set should have already been
67734     ** resolved by the time the WHERE clause is resolved.
67735     */
67736     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
67737       for(j=0; j<pEList->nExpr; j++){
67738         char *zAs = pEList->a[j].zName;
67739         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
67740           Expr *pOrig;
67741           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
67742           assert( pExpr->x.pList==0 );
67743           assert( pExpr->x.pSelect==0 );
67744           pOrig = pEList->a[j].pExpr;
67745           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
67746             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
67747             return WRC_Abort;
67748           }
67749           resolveAlias(pParse, pEList, j, pExpr, "");
67750           cnt = 1;
67751           pMatch = 0;
67752           assert( zTab==0 && zDb==0 );
67753           goto lookupname_end;
67754         }
67755       } 
67756     }
67757
67758     /* Advance to the next name context.  The loop will exit when either
67759     ** we have a match (cnt>0) or when we run out of name contexts.
67760     */
67761     if( cnt==0 ){
67762       pNC = pNC->pNext;
67763     }
67764   }
67765
67766   /*
67767   ** If X and Y are NULL (in other words if only the column name Z is
67768   ** supplied) and the value of Z is enclosed in double-quotes, then
67769   ** Z is a string literal if it doesn't match any column names.  In that
67770   ** case, we need to return right away and not make any changes to
67771   ** pExpr.
67772   **
67773   ** Because no reference was made to outer contexts, the pNC->nRef
67774   ** fields are not changed in any context.
67775   */
67776   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
67777     pExpr->op = TK_STRING;
67778     pExpr->pTab = 0;
67779     return WRC_Prune;
67780   }
67781
67782   /*
67783   ** cnt==0 means there was not match.  cnt>1 means there were two or
67784   ** more matches.  Either way, we have an error.
67785   */
67786   if( cnt!=1 ){
67787     const char *zErr;
67788     zErr = cnt==0 ? "no such column" : "ambiguous column name";
67789     if( zDb ){
67790       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
67791     }else if( zTab ){
67792       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
67793     }else{
67794       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
67795     }
67796     pParse->checkSchema = 1;
67797     pTopNC->nErr++;
67798   }
67799
67800   /* If a column from a table in pSrcList is referenced, then record
67801   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
67802   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
67803   ** column number is greater than the number of bits in the bitmask
67804   ** then set the high-order bit of the bitmask.
67805   */
67806   if( pExpr->iColumn>=0 && pMatch!=0 ){
67807     int n = pExpr->iColumn;
67808     testcase( n==BMS-1 );
67809     if( n>=BMS ){
67810       n = BMS-1;
67811     }
67812     assert( pMatch->iCursor==pExpr->iTable );
67813     pMatch->colUsed |= ((Bitmask)1)<<n;
67814   }
67815
67816   /* Clean up and return
67817   */
67818   sqlite3ExprDelete(db, pExpr->pLeft);
67819   pExpr->pLeft = 0;
67820   sqlite3ExprDelete(db, pExpr->pRight);
67821   pExpr->pRight = 0;
67822   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
67823 lookupname_end:
67824   if( cnt==1 ){
67825     assert( pNC!=0 );
67826     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
67827     /* Increment the nRef value on all name contexts from TopNC up to
67828     ** the point where the name matched. */
67829     for(;;){
67830       assert( pTopNC!=0 );
67831       pTopNC->nRef++;
67832       if( pTopNC==pNC ) break;
67833       pTopNC = pTopNC->pNext;
67834     }
67835     return WRC_Prune;
67836   } else {
67837     return WRC_Abort;
67838   }
67839 }
67840
67841 /*
67842 ** Allocate and return a pointer to an expression to load the column iCol
67843 ** from datasource iSrc in SrcList pSrc.
67844 */
67845 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
67846   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
67847   if( p ){
67848     struct SrcList_item *pItem = &pSrc->a[iSrc];
67849     p->pTab = pItem->pTab;
67850     p->iTable = pItem->iCursor;
67851     if( p->pTab->iPKey==iCol ){
67852       p->iColumn = -1;
67853     }else{
67854       p->iColumn = (ynVar)iCol;
67855       testcase( iCol==BMS );
67856       testcase( iCol==BMS-1 );
67857       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
67858     }
67859     ExprSetProperty(p, EP_Resolved);
67860   }
67861   return p;
67862 }
67863
67864 /*
67865 ** This routine is callback for sqlite3WalkExpr().
67866 **
67867 ** Resolve symbolic names into TK_COLUMN operators for the current
67868 ** node in the expression tree.  Return 0 to continue the search down
67869 ** the tree or 2 to abort the tree walk.
67870 **
67871 ** This routine also does error checking and name resolution for
67872 ** function names.  The operator for aggregate functions is changed
67873 ** to TK_AGG_FUNCTION.
67874 */
67875 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
67876   NameContext *pNC;
67877   Parse *pParse;
67878
67879   pNC = pWalker->u.pNC;
67880   assert( pNC!=0 );
67881   pParse = pNC->pParse;
67882   assert( pParse==pWalker->pParse );
67883
67884   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
67885   ExprSetProperty(pExpr, EP_Resolved);
67886 #ifndef NDEBUG
67887   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
67888     SrcList *pSrcList = pNC->pSrcList;
67889     int i;
67890     for(i=0; i<pNC->pSrcList->nSrc; i++){
67891       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
67892     }
67893   }
67894 #endif
67895   switch( pExpr->op ){
67896
67897 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
67898     /* The special operator TK_ROW means use the rowid for the first
67899     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
67900     ** clause processing on UPDATE and DELETE statements.
67901     */
67902     case TK_ROW: {
67903       SrcList *pSrcList = pNC->pSrcList;
67904       struct SrcList_item *pItem;
67905       assert( pSrcList && pSrcList->nSrc==1 );
67906       pItem = pSrcList->a; 
67907       pExpr->op = TK_COLUMN;
67908       pExpr->pTab = pItem->pTab;
67909       pExpr->iTable = pItem->iCursor;
67910       pExpr->iColumn = -1;
67911       pExpr->affinity = SQLITE_AFF_INTEGER;
67912       break;
67913     }
67914 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
67915
67916     /* A lone identifier is the name of a column.
67917     */
67918     case TK_ID: {
67919       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
67920     }
67921   
67922     /* A table name and column name:     ID.ID
67923     ** Or a database, table and column:  ID.ID.ID
67924     */
67925     case TK_DOT: {
67926       const char *zColumn;
67927       const char *zTable;
67928       const char *zDb;
67929       Expr *pRight;
67930
67931       /* if( pSrcList==0 ) break; */
67932       pRight = pExpr->pRight;
67933       if( pRight->op==TK_ID ){
67934         zDb = 0;
67935         zTable = pExpr->pLeft->u.zToken;
67936         zColumn = pRight->u.zToken;
67937       }else{
67938         assert( pRight->op==TK_DOT );
67939         zDb = pExpr->pLeft->u.zToken;
67940         zTable = pRight->pLeft->u.zToken;
67941         zColumn = pRight->pRight->u.zToken;
67942       }
67943       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
67944     }
67945
67946     /* Resolve function names
67947     */
67948     case TK_CONST_FUNC:
67949     case TK_FUNCTION: {
67950       ExprList *pList = pExpr->x.pList;    /* The argument list */
67951       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
67952       int no_such_func = 0;       /* True if no such function exists */
67953       int wrong_num_args = 0;     /* True if wrong number of arguments */
67954       int is_agg = 0;             /* True if is an aggregate function */
67955       int auth;                   /* Authorization to use the function */
67956       int nId;                    /* Number of characters in function name */
67957       const char *zId;            /* The function name. */
67958       FuncDef *pDef;              /* Information about the function */
67959       u8 enc = ENC(pParse->db);   /* The database encoding */
67960
67961       testcase( pExpr->op==TK_CONST_FUNC );
67962       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
67963       zId = pExpr->u.zToken;
67964       nId = sqlite3Strlen30(zId);
67965       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
67966       if( pDef==0 ){
67967         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
67968         if( pDef==0 ){
67969           no_such_func = 1;
67970         }else{
67971           wrong_num_args = 1;
67972         }
67973       }else{
67974         is_agg = pDef->xFunc==0;
67975       }
67976 #ifndef SQLITE_OMIT_AUTHORIZATION
67977       if( pDef ){
67978         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
67979         if( auth!=SQLITE_OK ){
67980           if( auth==SQLITE_DENY ){
67981             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
67982                                     pDef->zName);
67983             pNC->nErr++;
67984           }
67985           pExpr->op = TK_NULL;
67986           return WRC_Prune;
67987         }
67988       }
67989 #endif
67990       if( is_agg && !pNC->allowAgg ){
67991         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
67992         pNC->nErr++;
67993         is_agg = 0;
67994       }else if( no_such_func ){
67995         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
67996         pNC->nErr++;
67997       }else if( wrong_num_args ){
67998         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
67999              nId, zId);
68000         pNC->nErr++;
68001       }
68002       if( is_agg ){
68003         pExpr->op = TK_AGG_FUNCTION;
68004         pNC->hasAgg = 1;
68005       }
68006       if( is_agg ) pNC->allowAgg = 0;
68007       sqlite3WalkExprList(pWalker, pList);
68008       if( is_agg ) pNC->allowAgg = 1;
68009       /* FIX ME:  Compute pExpr->affinity based on the expected return
68010       ** type of the function 
68011       */
68012       return WRC_Prune;
68013     }
68014 #ifndef SQLITE_OMIT_SUBQUERY
68015     case TK_SELECT:
68016     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
68017 #endif
68018     case TK_IN: {
68019       testcase( pExpr->op==TK_IN );
68020       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
68021         int nRef = pNC->nRef;
68022 #ifndef SQLITE_OMIT_CHECK
68023         if( pNC->isCheck ){
68024           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
68025         }
68026 #endif
68027         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
68028         assert( pNC->nRef>=nRef );
68029         if( nRef!=pNC->nRef ){
68030           ExprSetProperty(pExpr, EP_VarSelect);
68031         }
68032       }
68033       break;
68034     }
68035 #ifndef SQLITE_OMIT_CHECK
68036     case TK_VARIABLE: {
68037       if( pNC->isCheck ){
68038         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
68039       }
68040       break;
68041     }
68042 #endif
68043   }
68044   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
68045 }
68046
68047 /*
68048 ** pEList is a list of expressions which are really the result set of the
68049 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
68050 ** This routine checks to see if pE is a simple identifier which corresponds
68051 ** to the AS-name of one of the terms of the expression list.  If it is,
68052 ** this routine return an integer between 1 and N where N is the number of
68053 ** elements in pEList, corresponding to the matching entry.  If there is
68054 ** no match, or if pE is not a simple identifier, then this routine
68055 ** return 0.
68056 **
68057 ** pEList has been resolved.  pE has not.
68058 */
68059 static int resolveAsName(
68060   Parse *pParse,     /* Parsing context for error messages */
68061   ExprList *pEList,  /* List of expressions to scan */
68062   Expr *pE           /* Expression we are trying to match */
68063 ){
68064   int i;             /* Loop counter */
68065
68066   UNUSED_PARAMETER(pParse);
68067
68068   if( pE->op==TK_ID ){
68069     char *zCol = pE->u.zToken;
68070     for(i=0; i<pEList->nExpr; i++){
68071       char *zAs = pEList->a[i].zName;
68072       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
68073         return i+1;
68074       }
68075     }
68076   }
68077   return 0;
68078 }
68079
68080 /*
68081 ** pE is a pointer to an expression which is a single term in the
68082 ** ORDER BY of a compound SELECT.  The expression has not been
68083 ** name resolved.
68084 **
68085 ** At the point this routine is called, we already know that the
68086 ** ORDER BY term is not an integer index into the result set.  That
68087 ** case is handled by the calling routine.
68088 **
68089 ** Attempt to match pE against result set columns in the left-most
68090 ** SELECT statement.  Return the index i of the matching column,
68091 ** as an indication to the caller that it should sort by the i-th column.
68092 ** The left-most column is 1.  In other words, the value returned is the
68093 ** same integer value that would be used in the SQL statement to indicate
68094 ** the column.
68095 **
68096 ** If there is no match, return 0.  Return -1 if an error occurs.
68097 */
68098 static int resolveOrderByTermToExprList(
68099   Parse *pParse,     /* Parsing context for error messages */
68100   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
68101   Expr *pE           /* The specific ORDER BY term */
68102 ){
68103   int i;             /* Loop counter */
68104   ExprList *pEList;  /* The columns of the result set */
68105   NameContext nc;    /* Name context for resolving pE */
68106   sqlite3 *db;       /* Database connection */
68107   int rc;            /* Return code from subprocedures */
68108   u8 savedSuppErr;   /* Saved value of db->suppressErr */
68109
68110   assert( sqlite3ExprIsInteger(pE, &i)==0 );
68111   pEList = pSelect->pEList;
68112
68113   /* Resolve all names in the ORDER BY term expression
68114   */
68115   memset(&nc, 0, sizeof(nc));
68116   nc.pParse = pParse;
68117   nc.pSrcList = pSelect->pSrc;
68118   nc.pEList = pEList;
68119   nc.allowAgg = 1;
68120   nc.nErr = 0;
68121   db = pParse->db;
68122   savedSuppErr = db->suppressErr;
68123   db->suppressErr = 1;
68124   rc = sqlite3ResolveExprNames(&nc, pE);
68125   db->suppressErr = savedSuppErr;
68126   if( rc ) return 0;
68127
68128   /* Try to match the ORDER BY expression against an expression
68129   ** in the result set.  Return an 1-based index of the matching
68130   ** result-set entry.
68131   */
68132   for(i=0; i<pEList->nExpr; i++){
68133     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
68134       return i+1;
68135     }
68136   }
68137
68138   /* If no match, return 0. */
68139   return 0;
68140 }
68141
68142 /*
68143 ** Generate an ORDER BY or GROUP BY term out-of-range error.
68144 */
68145 static void resolveOutOfRangeError(
68146   Parse *pParse,         /* The error context into which to write the error */
68147   const char *zType,     /* "ORDER" or "GROUP" */
68148   int i,                 /* The index (1-based) of the term out of range */
68149   int mx                 /* Largest permissible value of i */
68150 ){
68151   sqlite3ErrorMsg(pParse, 
68152     "%r %s BY term out of range - should be "
68153     "between 1 and %d", i, zType, mx);
68154 }
68155
68156 /*
68157 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
68158 ** each term of the ORDER BY clause is a constant integer between 1
68159 ** and N where N is the number of columns in the compound SELECT.
68160 **
68161 ** ORDER BY terms that are already an integer between 1 and N are
68162 ** unmodified.  ORDER BY terms that are integers outside the range of
68163 ** 1 through N generate an error.  ORDER BY terms that are expressions
68164 ** are matched against result set expressions of compound SELECT
68165 ** beginning with the left-most SELECT and working toward the right.
68166 ** At the first match, the ORDER BY expression is transformed into
68167 ** the integer column number.
68168 **
68169 ** Return the number of errors seen.
68170 */
68171 static int resolveCompoundOrderBy(
68172   Parse *pParse,        /* Parsing context.  Leave error messages here */
68173   Select *pSelect       /* The SELECT statement containing the ORDER BY */
68174 ){
68175   int i;
68176   ExprList *pOrderBy;
68177   ExprList *pEList;
68178   sqlite3 *db;
68179   int moreToDo = 1;
68180
68181   pOrderBy = pSelect->pOrderBy;
68182   if( pOrderBy==0 ) return 0;
68183   db = pParse->db;
68184 #if SQLITE_MAX_COLUMN
68185   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
68186     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
68187     return 1;
68188   }
68189 #endif
68190   for(i=0; i<pOrderBy->nExpr; i++){
68191     pOrderBy->a[i].done = 0;
68192   }
68193   pSelect->pNext = 0;
68194   while( pSelect->pPrior ){
68195     pSelect->pPrior->pNext = pSelect;
68196     pSelect = pSelect->pPrior;
68197   }
68198   while( pSelect && moreToDo ){
68199     struct ExprList_item *pItem;
68200     moreToDo = 0;
68201     pEList = pSelect->pEList;
68202     assert( pEList!=0 );
68203     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
68204       int iCol = -1;
68205       Expr *pE, *pDup;
68206       if( pItem->done ) continue;
68207       pE = pItem->pExpr;
68208       if( sqlite3ExprIsInteger(pE, &iCol) ){
68209         if( iCol<=0 || iCol>pEList->nExpr ){
68210           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
68211           return 1;
68212         }
68213       }else{
68214         iCol = resolveAsName(pParse, pEList, pE);
68215         if( iCol==0 ){
68216           pDup = sqlite3ExprDup(db, pE, 0);
68217           if( !db->mallocFailed ){
68218             assert(pDup);
68219             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
68220           }
68221           sqlite3ExprDelete(db, pDup);
68222         }
68223       }
68224       if( iCol>0 ){
68225         CollSeq *pColl = pE->pColl;
68226         int flags = pE->flags & EP_ExpCollate;
68227         sqlite3ExprDelete(db, pE);
68228         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
68229         if( pE==0 ) return 1;
68230         pE->pColl = pColl;
68231         pE->flags |= EP_IntValue | flags;
68232         pE->u.iValue = iCol;
68233         pItem->iCol = (u16)iCol;
68234         pItem->done = 1;
68235       }else{
68236         moreToDo = 1;
68237       }
68238     }
68239     pSelect = pSelect->pNext;
68240   }
68241   for(i=0; i<pOrderBy->nExpr; i++){
68242     if( pOrderBy->a[i].done==0 ){
68243       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
68244             "column in the result set", i+1);
68245       return 1;
68246     }
68247   }
68248   return 0;
68249 }
68250
68251 /*
68252 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
68253 ** the SELECT statement pSelect.  If any term is reference to a
68254 ** result set expression (as determined by the ExprList.a.iCol field)
68255 ** then convert that term into a copy of the corresponding result set
68256 ** column.
68257 **
68258 ** If any errors are detected, add an error message to pParse and
68259 ** return non-zero.  Return zero if no errors are seen.
68260 */
68261 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
68262   Parse *pParse,        /* Parsing context.  Leave error messages here */
68263   Select *pSelect,      /* The SELECT statement containing the clause */
68264   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
68265   const char *zType     /* "ORDER" or "GROUP" */
68266 ){
68267   int i;
68268   sqlite3 *db = pParse->db;
68269   ExprList *pEList;
68270   struct ExprList_item *pItem;
68271
68272   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
68273 #if SQLITE_MAX_COLUMN
68274   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
68275     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
68276     return 1;
68277   }
68278 #endif
68279   pEList = pSelect->pEList;
68280   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
68281   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
68282     if( pItem->iCol ){
68283       if( pItem->iCol>pEList->nExpr ){
68284         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
68285         return 1;
68286       }
68287       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
68288     }
68289   }
68290   return 0;
68291 }
68292
68293 /*
68294 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
68295 ** The Name context of the SELECT statement is pNC.  zType is either
68296 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
68297 **
68298 ** This routine resolves each term of the clause into an expression.
68299 ** If the order-by term is an integer I between 1 and N (where N is the
68300 ** number of columns in the result set of the SELECT) then the expression
68301 ** in the resolution is a copy of the I-th result-set expression.  If
68302 ** the order-by term is an identify that corresponds to the AS-name of
68303 ** a result-set expression, then the term resolves to a copy of the
68304 ** result-set expression.  Otherwise, the expression is resolved in
68305 ** the usual way - using sqlite3ResolveExprNames().
68306 **
68307 ** This routine returns the number of errors.  If errors occur, then
68308 ** an appropriate error message might be left in pParse.  (OOM errors
68309 ** excepted.)
68310 */
68311 static int resolveOrderGroupBy(
68312   NameContext *pNC,     /* The name context of the SELECT statement */
68313   Select *pSelect,      /* The SELECT statement holding pOrderBy */
68314   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
68315   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
68316 ){
68317   int i;                         /* Loop counter */
68318   int iCol;                      /* Column number */
68319   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
68320   Parse *pParse;                 /* Parsing context */
68321   int nResult;                   /* Number of terms in the result set */
68322
68323   if( pOrderBy==0 ) return 0;
68324   nResult = pSelect->pEList->nExpr;
68325   pParse = pNC->pParse;
68326   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
68327     Expr *pE = pItem->pExpr;
68328     iCol = resolveAsName(pParse, pSelect->pEList, pE);
68329     if( iCol>0 ){
68330       /* If an AS-name match is found, mark this ORDER BY column as being
68331       ** a copy of the iCol-th result-set column.  The subsequent call to
68332       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
68333       ** copy of the iCol-th result-set expression. */
68334       pItem->iCol = (u16)iCol;
68335       continue;
68336     }
68337     if( sqlite3ExprIsInteger(pE, &iCol) ){
68338       /* The ORDER BY term is an integer constant.  Again, set the column
68339       ** number so that sqlite3ResolveOrderGroupBy() will convert the
68340       ** order-by term to a copy of the result-set expression */
68341       if( iCol<1 ){
68342         resolveOutOfRangeError(pParse, zType, i+1, nResult);
68343         return 1;
68344       }
68345       pItem->iCol = (u16)iCol;
68346       continue;
68347     }
68348
68349     /* Otherwise, treat the ORDER BY term as an ordinary expression */
68350     pItem->iCol = 0;
68351     if( sqlite3ResolveExprNames(pNC, pE) ){
68352       return 1;
68353     }
68354   }
68355   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
68356 }
68357
68358 /*
68359 ** Resolve names in the SELECT statement p and all of its descendents.
68360 */
68361 static int resolveSelectStep(Walker *pWalker, Select *p){
68362   NameContext *pOuterNC;  /* Context that contains this SELECT */
68363   NameContext sNC;        /* Name context of this SELECT */
68364   int isCompound;         /* True if p is a compound select */
68365   int nCompound;          /* Number of compound terms processed so far */
68366   Parse *pParse;          /* Parsing context */
68367   ExprList *pEList;       /* Result set expression list */
68368   int i;                  /* Loop counter */
68369   ExprList *pGroupBy;     /* The GROUP BY clause */
68370   Select *pLeftmost;      /* Left-most of SELECT of a compound */
68371   sqlite3 *db;            /* Database connection */
68372   
68373
68374   assert( p!=0 );
68375   if( p->selFlags & SF_Resolved ){
68376     return WRC_Prune;
68377   }
68378   pOuterNC = pWalker->u.pNC;
68379   pParse = pWalker->pParse;
68380   db = pParse->db;
68381
68382   /* Normally sqlite3SelectExpand() will be called first and will have
68383   ** already expanded this SELECT.  However, if this is a subquery within
68384   ** an expression, sqlite3ResolveExprNames() will be called without a
68385   ** prior call to sqlite3SelectExpand().  When that happens, let
68386   ** sqlite3SelectPrep() do all of the processing for this SELECT.
68387   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
68388   ** this routine in the correct order.
68389   */
68390   if( (p->selFlags & SF_Expanded)==0 ){
68391     sqlite3SelectPrep(pParse, p, pOuterNC);
68392     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
68393   }
68394
68395   isCompound = p->pPrior!=0;
68396   nCompound = 0;
68397   pLeftmost = p;
68398   while( p ){
68399     assert( (p->selFlags & SF_Expanded)!=0 );
68400     assert( (p->selFlags & SF_Resolved)==0 );
68401     p->selFlags |= SF_Resolved;
68402
68403     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
68404     ** are not allowed to refer to any names, so pass an empty NameContext.
68405     */
68406     memset(&sNC, 0, sizeof(sNC));
68407     sNC.pParse = pParse;
68408     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
68409         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
68410       return WRC_Abort;
68411     }
68412   
68413     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
68414     ** resolve the result-set expression list.
68415     */
68416     sNC.allowAgg = 1;
68417     sNC.pSrcList = p->pSrc;
68418     sNC.pNext = pOuterNC;
68419   
68420     /* Resolve names in the result set. */
68421     pEList = p->pEList;
68422     assert( pEList!=0 );
68423     for(i=0; i<pEList->nExpr; i++){
68424       Expr *pX = pEList->a[i].pExpr;
68425       if( sqlite3ResolveExprNames(&sNC, pX) ){
68426         return WRC_Abort;
68427       }
68428     }
68429   
68430     /* Recursively resolve names in all subqueries
68431     */
68432     for(i=0; i<p->pSrc->nSrc; i++){
68433       struct SrcList_item *pItem = &p->pSrc->a[i];
68434       if( pItem->pSelect ){
68435         const char *zSavedContext = pParse->zAuthContext;
68436         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
68437         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
68438         pParse->zAuthContext = zSavedContext;
68439         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
68440       }
68441     }
68442   
68443     /* If there are no aggregate functions in the result-set, and no GROUP BY 
68444     ** expression, do not allow aggregates in any of the other expressions.
68445     */
68446     assert( (p->selFlags & SF_Aggregate)==0 );
68447     pGroupBy = p->pGroupBy;
68448     if( pGroupBy || sNC.hasAgg ){
68449       p->selFlags |= SF_Aggregate;
68450     }else{
68451       sNC.allowAgg = 0;
68452     }
68453   
68454     /* If a HAVING clause is present, then there must be a GROUP BY clause.
68455     */
68456     if( p->pHaving && !pGroupBy ){
68457       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
68458       return WRC_Abort;
68459     }
68460   
68461     /* Add the expression list to the name-context before parsing the
68462     ** other expressions in the SELECT statement. This is so that
68463     ** expressions in the WHERE clause (etc.) can refer to expressions by
68464     ** aliases in the result set.
68465     **
68466     ** Minor point: If this is the case, then the expression will be
68467     ** re-evaluated for each reference to it.
68468     */
68469     sNC.pEList = p->pEList;
68470     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
68471        sqlite3ResolveExprNames(&sNC, p->pHaving)
68472     ){
68473       return WRC_Abort;
68474     }
68475
68476     /* The ORDER BY and GROUP BY clauses may not refer to terms in
68477     ** outer queries 
68478     */
68479     sNC.pNext = 0;
68480     sNC.allowAgg = 1;
68481
68482     /* Process the ORDER BY clause for singleton SELECT statements.
68483     ** The ORDER BY clause for compounds SELECT statements is handled
68484     ** below, after all of the result-sets for all of the elements of
68485     ** the compound have been resolved.
68486     */
68487     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
68488       return WRC_Abort;
68489     }
68490     if( db->mallocFailed ){
68491       return WRC_Abort;
68492     }
68493   
68494     /* Resolve the GROUP BY clause.  At the same time, make sure 
68495     ** the GROUP BY clause does not contain aggregate functions.
68496     */
68497     if( pGroupBy ){
68498       struct ExprList_item *pItem;
68499     
68500       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
68501         return WRC_Abort;
68502       }
68503       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
68504         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
68505           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
68506               "the GROUP BY clause");
68507           return WRC_Abort;
68508         }
68509       }
68510     }
68511
68512     /* Advance to the next term of the compound
68513     */
68514     p = p->pPrior;
68515     nCompound++;
68516   }
68517
68518   /* Resolve the ORDER BY on a compound SELECT after all terms of
68519   ** the compound have been resolved.
68520   */
68521   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
68522     return WRC_Abort;
68523   }
68524
68525   return WRC_Prune;
68526 }
68527
68528 /*
68529 ** This routine walks an expression tree and resolves references to
68530 ** table columns and result-set columns.  At the same time, do error
68531 ** checking on function usage and set a flag if any aggregate functions
68532 ** are seen.
68533 **
68534 ** To resolve table columns references we look for nodes (or subtrees) of the 
68535 ** form X.Y.Z or Y.Z or just Z where
68536 **
68537 **      X:   The name of a database.  Ex:  "main" or "temp" or
68538 **           the symbolic name assigned to an ATTACH-ed database.
68539 **
68540 **      Y:   The name of a table in a FROM clause.  Or in a trigger
68541 **           one of the special names "old" or "new".
68542 **
68543 **      Z:   The name of a column in table Y.
68544 **
68545 ** The node at the root of the subtree is modified as follows:
68546 **
68547 **    Expr.op        Changed to TK_COLUMN
68548 **    Expr.pTab      Points to the Table object for X.Y
68549 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
68550 **    Expr.iTable    The VDBE cursor number for X.Y
68551 **
68552 **
68553 ** To resolve result-set references, look for expression nodes of the
68554 ** form Z (with no X and Y prefix) where the Z matches the right-hand
68555 ** size of an AS clause in the result-set of a SELECT.  The Z expression
68556 ** is replaced by a copy of the left-hand side of the result-set expression.
68557 ** Table-name and function resolution occurs on the substituted expression
68558 ** tree.  For example, in:
68559 **
68560 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
68561 **
68562 ** The "x" term of the order by is replaced by "a+b" to render:
68563 **
68564 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
68565 **
68566 ** Function calls are checked to make sure that the function is 
68567 ** defined and that the correct number of arguments are specified.
68568 ** If the function is an aggregate function, then the pNC->hasAgg is
68569 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
68570 ** If an expression contains aggregate functions then the EP_Agg
68571 ** property on the expression is set.
68572 **
68573 ** An error message is left in pParse if anything is amiss.  The number
68574 ** if errors is returned.
68575 */
68576 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
68577   NameContext *pNC,       /* Namespace to resolve expressions in. */
68578   Expr *pExpr             /* The expression to be analyzed. */
68579 ){
68580   int savedHasAgg;
68581   Walker w;
68582
68583   if( pExpr==0 ) return 0;
68584 #if SQLITE_MAX_EXPR_DEPTH>0
68585   {
68586     Parse *pParse = pNC->pParse;
68587     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
68588       return 1;
68589     }
68590     pParse->nHeight += pExpr->nHeight;
68591   }
68592 #endif
68593   savedHasAgg = pNC->hasAgg;
68594   pNC->hasAgg = 0;
68595   w.xExprCallback = resolveExprStep;
68596   w.xSelectCallback = resolveSelectStep;
68597   w.pParse = pNC->pParse;
68598   w.u.pNC = pNC;
68599   sqlite3WalkExpr(&w, pExpr);
68600 #if SQLITE_MAX_EXPR_DEPTH>0
68601   pNC->pParse->nHeight -= pExpr->nHeight;
68602 #endif
68603   if( pNC->nErr>0 || w.pParse->nErr>0 ){
68604     ExprSetProperty(pExpr, EP_Error);
68605   }
68606   if( pNC->hasAgg ){
68607     ExprSetProperty(pExpr, EP_Agg);
68608   }else if( savedHasAgg ){
68609     pNC->hasAgg = 1;
68610   }
68611   return ExprHasProperty(pExpr, EP_Error);
68612 }
68613
68614
68615 /*
68616 ** Resolve all names in all expressions of a SELECT and in all
68617 ** decendents of the SELECT, including compounds off of p->pPrior,
68618 ** subqueries in expressions, and subqueries used as FROM clause
68619 ** terms.
68620 **
68621 ** See sqlite3ResolveExprNames() for a description of the kinds of
68622 ** transformations that occur.
68623 **
68624 ** All SELECT statements should have been expanded using
68625 ** sqlite3SelectExpand() prior to invoking this routine.
68626 */
68627 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
68628   Parse *pParse,         /* The parser context */
68629   Select *p,             /* The SELECT statement being coded. */
68630   NameContext *pOuterNC  /* Name context for parent SELECT statement */
68631 ){
68632   Walker w;
68633
68634   assert( p!=0 );
68635   w.xExprCallback = resolveExprStep;
68636   w.xSelectCallback = resolveSelectStep;
68637   w.pParse = pParse;
68638   w.u.pNC = pOuterNC;
68639   sqlite3WalkSelect(&w, p);
68640 }
68641
68642 /************** End of resolve.c *********************************************/
68643 /************** Begin file expr.c ********************************************/
68644 /*
68645 ** 2001 September 15
68646 **
68647 ** The author disclaims copyright to this source code.  In place of
68648 ** a legal notice, here is a blessing:
68649 **
68650 **    May you do good and not evil.
68651 **    May you find forgiveness for yourself and forgive others.
68652 **    May you share freely, never taking more than you give.
68653 **
68654 *************************************************************************
68655 ** This file contains routines used for analyzing expressions and
68656 ** for generating VDBE code that evaluates expressions in SQLite.
68657 */
68658
68659 /*
68660 ** Return the 'affinity' of the expression pExpr if any.
68661 **
68662 ** If pExpr is a column, a reference to a column via an 'AS' alias,
68663 ** or a sub-select with a column as the return value, then the 
68664 ** affinity of that column is returned. Otherwise, 0x00 is returned,
68665 ** indicating no affinity for the expression.
68666 **
68667 ** i.e. the WHERE clause expresssions in the following statements all
68668 ** have an affinity:
68669 **
68670 ** CREATE TABLE t1(a);
68671 ** SELECT * FROM t1 WHERE a;
68672 ** SELECT a AS b FROM t1 WHERE b;
68673 ** SELECT * FROM t1 WHERE (select a from t1);
68674 */
68675 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
68676   int op = pExpr->op;
68677   if( op==TK_SELECT ){
68678     assert( pExpr->flags&EP_xIsSelect );
68679     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
68680   }
68681 #ifndef SQLITE_OMIT_CAST
68682   if( op==TK_CAST ){
68683     assert( !ExprHasProperty(pExpr, EP_IntValue) );
68684     return sqlite3AffinityType(pExpr->u.zToken);
68685   }
68686 #endif
68687   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
68688    && pExpr->pTab!=0
68689   ){
68690     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
68691     ** a TK_COLUMN but was previously evaluated and cached in a register */
68692     int j = pExpr->iColumn;
68693     if( j<0 ) return SQLITE_AFF_INTEGER;
68694     assert( pExpr->pTab && j<pExpr->pTab->nCol );
68695     return pExpr->pTab->aCol[j].affinity;
68696   }
68697   return pExpr->affinity;
68698 }
68699
68700 /*
68701 ** Set the explicit collating sequence for an expression to the
68702 ** collating sequence supplied in the second argument.
68703 */
68704 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
68705   if( pExpr && pColl ){
68706     pExpr->pColl = pColl;
68707     pExpr->flags |= EP_ExpCollate;
68708   }
68709   return pExpr;
68710 }
68711
68712 /*
68713 ** Set the collating sequence for expression pExpr to be the collating
68714 ** sequence named by pToken.   Return a pointer to the revised expression.
68715 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
68716 ** flag.  An explicit collating sequence will override implicit
68717 ** collating sequences.
68718 */
68719 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
68720   char *zColl = 0;            /* Dequoted name of collation sequence */
68721   CollSeq *pColl;
68722   sqlite3 *db = pParse->db;
68723   zColl = sqlite3NameFromToken(db, pCollName);
68724   pColl = sqlite3LocateCollSeq(pParse, zColl);
68725   sqlite3ExprSetColl(pExpr, pColl);
68726   sqlite3DbFree(db, zColl);
68727   return pExpr;
68728 }
68729
68730 /*
68731 ** Return the default collation sequence for the expression pExpr. If
68732 ** there is no default collation type, return 0.
68733 */
68734 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
68735   CollSeq *pColl = 0;
68736   Expr *p = pExpr;
68737   while( ALWAYS(p) ){
68738     int op;
68739     pColl = p->pColl;
68740     if( pColl ) break;
68741     op = p->op;
68742     if( p->pTab!=0 && (
68743         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
68744     )){
68745       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
68746       ** a TK_COLUMN but was previously evaluated and cached in a register */
68747       const char *zColl;
68748       int j = p->iColumn;
68749       if( j>=0 ){
68750         sqlite3 *db = pParse->db;
68751         zColl = p->pTab->aCol[j].zColl;
68752         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
68753         pExpr->pColl = pColl;
68754       }
68755       break;
68756     }
68757     if( op!=TK_CAST && op!=TK_UPLUS ){
68758       break;
68759     }
68760     p = p->pLeft;
68761   }
68762   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
68763     pColl = 0;
68764   }
68765   return pColl;
68766 }
68767
68768 /*
68769 ** pExpr is an operand of a comparison operator.  aff2 is the
68770 ** type affinity of the other operand.  This routine returns the
68771 ** type affinity that should be used for the comparison operator.
68772 */
68773 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
68774   char aff1 = sqlite3ExprAffinity(pExpr);
68775   if( aff1 && aff2 ){
68776     /* Both sides of the comparison are columns. If one has numeric
68777     ** affinity, use that. Otherwise use no affinity.
68778     */
68779     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
68780       return SQLITE_AFF_NUMERIC;
68781     }else{
68782       return SQLITE_AFF_NONE;
68783     }
68784   }else if( !aff1 && !aff2 ){
68785     /* Neither side of the comparison is a column.  Compare the
68786     ** results directly.
68787     */
68788     return SQLITE_AFF_NONE;
68789   }else{
68790     /* One side is a column, the other is not. Use the columns affinity. */
68791     assert( aff1==0 || aff2==0 );
68792     return (aff1 + aff2);
68793   }
68794 }
68795
68796 /*
68797 ** pExpr is a comparison operator.  Return the type affinity that should
68798 ** be applied to both operands prior to doing the comparison.
68799 */
68800 static char comparisonAffinity(Expr *pExpr){
68801   char aff;
68802   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
68803           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
68804           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
68805   assert( pExpr->pLeft );
68806   aff = sqlite3ExprAffinity(pExpr->pLeft);
68807   if( pExpr->pRight ){
68808     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
68809   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
68810     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
68811   }else if( !aff ){
68812     aff = SQLITE_AFF_NONE;
68813   }
68814   return aff;
68815 }
68816
68817 /*
68818 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
68819 ** idx_affinity is the affinity of an indexed column. Return true
68820 ** if the index with affinity idx_affinity may be used to implement
68821 ** the comparison in pExpr.
68822 */
68823 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
68824   char aff = comparisonAffinity(pExpr);
68825   switch( aff ){
68826     case SQLITE_AFF_NONE:
68827       return 1;
68828     case SQLITE_AFF_TEXT:
68829       return idx_affinity==SQLITE_AFF_TEXT;
68830     default:
68831       return sqlite3IsNumericAffinity(idx_affinity);
68832   }
68833 }
68834
68835 /*
68836 ** Return the P5 value that should be used for a binary comparison
68837 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
68838 */
68839 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
68840   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
68841   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
68842   return aff;
68843 }
68844
68845 /*
68846 ** Return a pointer to the collation sequence that should be used by
68847 ** a binary comparison operator comparing pLeft and pRight.
68848 **
68849 ** If the left hand expression has a collating sequence type, then it is
68850 ** used. Otherwise the collation sequence for the right hand expression
68851 ** is used, or the default (BINARY) if neither expression has a collating
68852 ** type.
68853 **
68854 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
68855 ** it is not considered.
68856 */
68857 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
68858   Parse *pParse, 
68859   Expr *pLeft, 
68860   Expr *pRight
68861 ){
68862   CollSeq *pColl;
68863   assert( pLeft );
68864   if( pLeft->flags & EP_ExpCollate ){
68865     assert( pLeft->pColl );
68866     pColl = pLeft->pColl;
68867   }else if( pRight && pRight->flags & EP_ExpCollate ){
68868     assert( pRight->pColl );
68869     pColl = pRight->pColl;
68870   }else{
68871     pColl = sqlite3ExprCollSeq(pParse, pLeft);
68872     if( !pColl ){
68873       pColl = sqlite3ExprCollSeq(pParse, pRight);
68874     }
68875   }
68876   return pColl;
68877 }
68878
68879 /*
68880 ** Generate code for a comparison operator.
68881 */
68882 static int codeCompare(
68883   Parse *pParse,    /* The parsing (and code generating) context */
68884   Expr *pLeft,      /* The left operand */
68885   Expr *pRight,     /* The right operand */
68886   int opcode,       /* The comparison opcode */
68887   int in1, int in2, /* Register holding operands */
68888   int dest,         /* Jump here if true.  */
68889   int jumpIfNull    /* If true, jump if either operand is NULL */
68890 ){
68891   int p5;
68892   int addr;
68893   CollSeq *p4;
68894
68895   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
68896   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
68897   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
68898                            (void*)p4, P4_COLLSEQ);
68899   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
68900   return addr;
68901 }
68902
68903 #if SQLITE_MAX_EXPR_DEPTH>0
68904 /*
68905 ** Check that argument nHeight is less than or equal to the maximum
68906 ** expression depth allowed. If it is not, leave an error message in
68907 ** pParse.
68908 */
68909 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
68910   int rc = SQLITE_OK;
68911   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
68912   if( nHeight>mxHeight ){
68913     sqlite3ErrorMsg(pParse, 
68914        "Expression tree is too large (maximum depth %d)", mxHeight
68915     );
68916     rc = SQLITE_ERROR;
68917   }
68918   return rc;
68919 }
68920
68921 /* The following three functions, heightOfExpr(), heightOfExprList()
68922 ** and heightOfSelect(), are used to determine the maximum height
68923 ** of any expression tree referenced by the structure passed as the
68924 ** first argument.
68925 **
68926 ** If this maximum height is greater than the current value pointed
68927 ** to by pnHeight, the second parameter, then set *pnHeight to that
68928 ** value.
68929 */
68930 static void heightOfExpr(Expr *p, int *pnHeight){
68931   if( p ){
68932     if( p->nHeight>*pnHeight ){
68933       *pnHeight = p->nHeight;
68934     }
68935   }
68936 }
68937 static void heightOfExprList(ExprList *p, int *pnHeight){
68938   if( p ){
68939     int i;
68940     for(i=0; i<p->nExpr; i++){
68941       heightOfExpr(p->a[i].pExpr, pnHeight);
68942     }
68943   }
68944 }
68945 static void heightOfSelect(Select *p, int *pnHeight){
68946   if( p ){
68947     heightOfExpr(p->pWhere, pnHeight);
68948     heightOfExpr(p->pHaving, pnHeight);
68949     heightOfExpr(p->pLimit, pnHeight);
68950     heightOfExpr(p->pOffset, pnHeight);
68951     heightOfExprList(p->pEList, pnHeight);
68952     heightOfExprList(p->pGroupBy, pnHeight);
68953     heightOfExprList(p->pOrderBy, pnHeight);
68954     heightOfSelect(p->pPrior, pnHeight);
68955   }
68956 }
68957
68958 /*
68959 ** Set the Expr.nHeight variable in the structure passed as an 
68960 ** argument. An expression with no children, Expr.pList or 
68961 ** Expr.pSelect member has a height of 1. Any other expression
68962 ** has a height equal to the maximum height of any other 
68963 ** referenced Expr plus one.
68964 */
68965 static void exprSetHeight(Expr *p){
68966   int nHeight = 0;
68967   heightOfExpr(p->pLeft, &nHeight);
68968   heightOfExpr(p->pRight, &nHeight);
68969   if( ExprHasProperty(p, EP_xIsSelect) ){
68970     heightOfSelect(p->x.pSelect, &nHeight);
68971   }else{
68972     heightOfExprList(p->x.pList, &nHeight);
68973   }
68974   p->nHeight = nHeight + 1;
68975 }
68976
68977 /*
68978 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
68979 ** the height is greater than the maximum allowed expression depth,
68980 ** leave an error in pParse.
68981 */
68982 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
68983   exprSetHeight(p);
68984   sqlite3ExprCheckHeight(pParse, p->nHeight);
68985 }
68986
68987 /*
68988 ** Return the maximum height of any expression tree referenced
68989 ** by the select statement passed as an argument.
68990 */
68991 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
68992   int nHeight = 0;
68993   heightOfSelect(p, &nHeight);
68994   return nHeight;
68995 }
68996 #else
68997   #define exprSetHeight(y)
68998 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
68999
69000 /*
69001 ** This routine is the core allocator for Expr nodes.
69002 **
69003 ** Construct a new expression node and return a pointer to it.  Memory
69004 ** for this node and for the pToken argument is a single allocation
69005 ** obtained from sqlite3DbMalloc().  The calling function
69006 ** is responsible for making sure the node eventually gets freed.
69007 **
69008 ** If dequote is true, then the token (if it exists) is dequoted.
69009 ** If dequote is false, no dequoting is performance.  The deQuote
69010 ** parameter is ignored if pToken is NULL or if the token does not
69011 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
69012 ** then the EP_DblQuoted flag is set on the expression node.
69013 **
69014 ** Special case:  If op==TK_INTEGER and pToken points to a string that
69015 ** can be translated into a 32-bit integer, then the token is not
69016 ** stored in u.zToken.  Instead, the integer values is written
69017 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
69018 ** is allocated to hold the integer text and the dequote flag is ignored.
69019 */
69020 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
69021   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
69022   int op,                 /* Expression opcode */
69023   const Token *pToken,    /* Token argument.  Might be NULL */
69024   int dequote             /* True to dequote */
69025 ){
69026   Expr *pNew;
69027   int nExtra = 0;
69028   int iValue = 0;
69029
69030   if( pToken ){
69031     if( op!=TK_INTEGER || pToken->z==0
69032           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
69033       nExtra = pToken->n+1;
69034     }
69035   }
69036   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
69037   if( pNew ){
69038     pNew->op = (u8)op;
69039     pNew->iAgg = -1;
69040     if( pToken ){
69041       if( nExtra==0 ){
69042         pNew->flags |= EP_IntValue;
69043         pNew->u.iValue = iValue;
69044       }else{
69045         int c;
69046         pNew->u.zToken = (char*)&pNew[1];
69047         memcpy(pNew->u.zToken, pToken->z, pToken->n);
69048         pNew->u.zToken[pToken->n] = 0;
69049         if( dequote && nExtra>=3 
69050              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
69051           sqlite3Dequote(pNew->u.zToken);
69052           if( c=='"' ) pNew->flags |= EP_DblQuoted;
69053         }
69054       }
69055     }
69056 #if SQLITE_MAX_EXPR_DEPTH>0
69057     pNew->nHeight = 1;
69058 #endif  
69059   }
69060   return pNew;
69061 }
69062
69063 /*
69064 ** Allocate a new expression node from a zero-terminated token that has
69065 ** already been dequoted.
69066 */
69067 SQLITE_PRIVATE Expr *sqlite3Expr(
69068   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
69069   int op,                 /* Expression opcode */
69070   const char *zToken      /* Token argument.  Might be NULL */
69071 ){
69072   Token x;
69073   x.z = zToken;
69074   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
69075   return sqlite3ExprAlloc(db, op, &x, 0);
69076 }
69077
69078 /*
69079 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
69080 **
69081 ** If pRoot==NULL that means that a memory allocation error has occurred.
69082 ** In that case, delete the subtrees pLeft and pRight.
69083 */
69084 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
69085   sqlite3 *db,
69086   Expr *pRoot,
69087   Expr *pLeft,
69088   Expr *pRight
69089 ){
69090   if( pRoot==0 ){
69091     assert( db->mallocFailed );
69092     sqlite3ExprDelete(db, pLeft);
69093     sqlite3ExprDelete(db, pRight);
69094   }else{
69095     if( pRight ){
69096       pRoot->pRight = pRight;
69097       if( pRight->flags & EP_ExpCollate ){
69098         pRoot->flags |= EP_ExpCollate;
69099         pRoot->pColl = pRight->pColl;
69100       }
69101     }
69102     if( pLeft ){
69103       pRoot->pLeft = pLeft;
69104       if( pLeft->flags & EP_ExpCollate ){
69105         pRoot->flags |= EP_ExpCollate;
69106         pRoot->pColl = pLeft->pColl;
69107       }
69108     }
69109     exprSetHeight(pRoot);
69110   }
69111 }
69112
69113 /*
69114 ** Allocate a Expr node which joins as many as two subtrees.
69115 **
69116 ** One or both of the subtrees can be NULL.  Return a pointer to the new
69117 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
69118 ** free the subtrees and return NULL.
69119 */
69120 SQLITE_PRIVATE Expr *sqlite3PExpr(
69121   Parse *pParse,          /* Parsing context */
69122   int op,                 /* Expression opcode */
69123   Expr *pLeft,            /* Left operand */
69124   Expr *pRight,           /* Right operand */
69125   const Token *pToken     /* Argument token */
69126 ){
69127   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
69128   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
69129   if( p ) {
69130     sqlite3ExprCheckHeight(pParse, p->nHeight);
69131   }
69132   return p;
69133 }
69134
69135 /*
69136 ** Join two expressions using an AND operator.  If either expression is
69137 ** NULL, then just return the other expression.
69138 */
69139 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
69140   if( pLeft==0 ){
69141     return pRight;
69142   }else if( pRight==0 ){
69143     return pLeft;
69144   }else{
69145     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
69146     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
69147     return pNew;
69148   }
69149 }
69150
69151 /*
69152 ** Construct a new expression node for a function with multiple
69153 ** arguments.
69154 */
69155 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
69156   Expr *pNew;
69157   sqlite3 *db = pParse->db;
69158   assert( pToken );
69159   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
69160   if( pNew==0 ){
69161     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
69162     return 0;
69163   }
69164   pNew->x.pList = pList;
69165   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
69166   sqlite3ExprSetHeight(pParse, pNew);
69167   return pNew;
69168 }
69169
69170 /*
69171 ** Assign a variable number to an expression that encodes a wildcard
69172 ** in the original SQL statement.  
69173 **
69174 ** Wildcards consisting of a single "?" are assigned the next sequential
69175 ** variable number.
69176 **
69177 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
69178 ** sure "nnn" is not too be to avoid a denial of service attack when
69179 ** the SQL statement comes from an external source.
69180 **
69181 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
69182 ** as the previous instance of the same wildcard.  Or if this is the first
69183 ** instance of the wildcard, the next sequenial variable number is
69184 ** assigned.
69185 */
69186 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
69187   sqlite3 *db = pParse->db;
69188   const char *z;
69189
69190   if( pExpr==0 ) return;
69191   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
69192   z = pExpr->u.zToken;
69193   assert( z!=0 );
69194   assert( z[0]!=0 );
69195   if( z[1]==0 ){
69196     /* Wildcard of the form "?".  Assign the next variable number */
69197     assert( z[0]=='?' );
69198     pExpr->iColumn = (ynVar)(++pParse->nVar);
69199   }else if( z[0]=='?' ){
69200     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
69201     ** use it as the variable number */
69202     i64 i;
69203     int bOk = 0==sqlite3Atoi64(&z[1], &i, sqlite3Strlen30(&z[1]), SQLITE_UTF8);
69204     pExpr->iColumn = (ynVar)i;
69205     testcase( i==0 );
69206     testcase( i==1 );
69207     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
69208     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
69209     if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
69210       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
69211           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
69212     }
69213     if( i>pParse->nVar ){
69214       pParse->nVar = (int)i;
69215     }
69216   }else{
69217     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
69218     ** number as the prior appearance of the same name, or if the name
69219     ** has never appeared before, reuse the same variable number
69220     */
69221     int i;
69222     u32 n;
69223     n = sqlite3Strlen30(z);
69224     for(i=0; i<pParse->nVarExpr; i++){
69225       Expr *pE = pParse->apVarExpr[i];
69226       assert( pE!=0 );
69227       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
69228         pExpr->iColumn = pE->iColumn;
69229         break;
69230       }
69231     }
69232     if( i>=pParse->nVarExpr ){
69233       pExpr->iColumn = (ynVar)(++pParse->nVar);
69234       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
69235         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
69236         pParse->apVarExpr =
69237             sqlite3DbReallocOrFree(
69238               db,
69239               pParse->apVarExpr,
69240               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
69241             );
69242       }
69243       if( !db->mallocFailed ){
69244         assert( pParse->apVarExpr!=0 );
69245         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
69246       }
69247     }
69248   } 
69249   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
69250     sqlite3ErrorMsg(pParse, "too many SQL variables");
69251   }
69252 }
69253
69254 /*
69255 ** Recursively delete an expression tree.
69256 */
69257 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
69258   if( p==0 ) return;
69259   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
69260     sqlite3ExprDelete(db, p->pLeft);
69261     sqlite3ExprDelete(db, p->pRight);
69262     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
69263       sqlite3DbFree(db, p->u.zToken);
69264     }
69265     if( ExprHasProperty(p, EP_xIsSelect) ){
69266       sqlite3SelectDelete(db, p->x.pSelect);
69267     }else{
69268       sqlite3ExprListDelete(db, p->x.pList);
69269     }
69270   }
69271   if( !ExprHasProperty(p, EP_Static) ){
69272     sqlite3DbFree(db, p);
69273   }
69274 }
69275
69276 /*
69277 ** Return the number of bytes allocated for the expression structure 
69278 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
69279 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
69280 */
69281 static int exprStructSize(Expr *p){
69282   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
69283   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
69284   return EXPR_FULLSIZE;
69285 }
69286
69287 /*
69288 ** The dupedExpr*Size() routines each return the number of bytes required
69289 ** to store a copy of an expression or expression tree.  They differ in
69290 ** how much of the tree is measured.
69291 **
69292 **     dupedExprStructSize()     Size of only the Expr structure 
69293 **     dupedExprNodeSize()       Size of Expr + space for token
69294 **     dupedExprSize()           Expr + token + subtree components
69295 **
69296 ***************************************************************************
69297 **
69298 ** The dupedExprStructSize() function returns two values OR-ed together:  
69299 ** (1) the space required for a copy of the Expr structure only and 
69300 ** (2) the EP_xxx flags that indicate what the structure size should be.
69301 ** The return values is always one of:
69302 **
69303 **      EXPR_FULLSIZE
69304 **      EXPR_REDUCEDSIZE   | EP_Reduced
69305 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
69306 **
69307 ** The size of the structure can be found by masking the return value
69308 ** of this routine with 0xfff.  The flags can be found by masking the
69309 ** return value with EP_Reduced|EP_TokenOnly.
69310 **
69311 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
69312 ** (unreduced) Expr objects as they or originally constructed by the parser.
69313 ** During expression analysis, extra information is computed and moved into
69314 ** later parts of teh Expr object and that extra information might get chopped
69315 ** off if the expression is reduced.  Note also that it does not work to
69316 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
69317 ** to reduce a pristine expression tree from the parser.  The implementation
69318 ** of dupedExprStructSize() contain multiple assert() statements that attempt
69319 ** to enforce this constraint.
69320 */
69321 static int dupedExprStructSize(Expr *p, int flags){
69322   int nSize;
69323   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
69324   if( 0==(flags&EXPRDUP_REDUCE) ){
69325     nSize = EXPR_FULLSIZE;
69326   }else{
69327     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
69328     assert( !ExprHasProperty(p, EP_FromJoin) ); 
69329     assert( (p->flags2 & EP2_MallocedToken)==0 );
69330     assert( (p->flags2 & EP2_Irreducible)==0 );
69331     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
69332       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
69333     }else{
69334       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
69335     }
69336   }
69337   return nSize;
69338 }
69339
69340 /*
69341 ** This function returns the space in bytes required to store the copy 
69342 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
69343 ** string is defined.)
69344 */
69345 static int dupedExprNodeSize(Expr *p, int flags){
69346   int nByte = dupedExprStructSize(p, flags) & 0xfff;
69347   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
69348     nByte += sqlite3Strlen30(p->u.zToken)+1;
69349   }
69350   return ROUND8(nByte);
69351 }
69352
69353 /*
69354 ** Return the number of bytes required to create a duplicate of the 
69355 ** expression passed as the first argument. The second argument is a
69356 ** mask containing EXPRDUP_XXX flags.
69357 **
69358 ** The value returned includes space to create a copy of the Expr struct
69359 ** itself and the buffer referred to by Expr.u.zToken, if any.
69360 **
69361 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
69362 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
69363 ** and Expr.pRight variables (but not for any structures pointed to or 
69364 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
69365 */
69366 static int dupedExprSize(Expr *p, int flags){
69367   int nByte = 0;
69368   if( p ){
69369     nByte = dupedExprNodeSize(p, flags);
69370     if( flags&EXPRDUP_REDUCE ){
69371       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
69372     }
69373   }
69374   return nByte;
69375 }
69376
69377 /*
69378 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
69379 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
69380 ** to store the copy of expression p, the copies of p->u.zToken
69381 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
69382 ** if any. Before returning, *pzBuffer is set to the first byte passed the
69383 ** portion of the buffer copied into by this function.
69384 */
69385 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
69386   Expr *pNew = 0;                      /* Value to return */
69387   if( p ){
69388     const int isReduced = (flags&EXPRDUP_REDUCE);
69389     u8 *zAlloc;
69390     u32 staticFlag = 0;
69391
69392     assert( pzBuffer==0 || isReduced );
69393
69394     /* Figure out where to write the new Expr structure. */
69395     if( pzBuffer ){
69396       zAlloc = *pzBuffer;
69397       staticFlag = EP_Static;
69398     }else{
69399       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
69400     }
69401     pNew = (Expr *)zAlloc;
69402
69403     if( pNew ){
69404       /* Set nNewSize to the size allocated for the structure pointed to
69405       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
69406       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
69407       ** by the copy of the p->u.zToken string (if any).
69408       */
69409       const unsigned nStructSize = dupedExprStructSize(p, flags);
69410       const int nNewSize = nStructSize & 0xfff;
69411       int nToken;
69412       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
69413         nToken = sqlite3Strlen30(p->u.zToken) + 1;
69414       }else{
69415         nToken = 0;
69416       }
69417       if( isReduced ){
69418         assert( ExprHasProperty(p, EP_Reduced)==0 );
69419         memcpy(zAlloc, p, nNewSize);
69420       }else{
69421         int nSize = exprStructSize(p);
69422         memcpy(zAlloc, p, nSize);
69423         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
69424       }
69425
69426       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
69427       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
69428       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
69429       pNew->flags |= staticFlag;
69430
69431       /* Copy the p->u.zToken string, if any. */
69432       if( nToken ){
69433         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
69434         memcpy(zToken, p->u.zToken, nToken);
69435       }
69436
69437       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
69438         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
69439         if( ExprHasProperty(p, EP_xIsSelect) ){
69440           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
69441         }else{
69442           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
69443         }
69444       }
69445
69446       /* Fill in pNew->pLeft and pNew->pRight. */
69447       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
69448         zAlloc += dupedExprNodeSize(p, flags);
69449         if( ExprHasProperty(pNew, EP_Reduced) ){
69450           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
69451           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
69452         }
69453         if( pzBuffer ){
69454           *pzBuffer = zAlloc;
69455         }
69456       }else{
69457         pNew->flags2 = 0;
69458         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
69459           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
69460           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
69461         }
69462       }
69463
69464     }
69465   }
69466   return pNew;
69467 }
69468
69469 /*
69470 ** The following group of routines make deep copies of expressions,
69471 ** expression lists, ID lists, and select statements.  The copies can
69472 ** be deleted (by being passed to their respective ...Delete() routines)
69473 ** without effecting the originals.
69474 **
69475 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
69476 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
69477 ** by subsequent calls to sqlite*ListAppend() routines.
69478 **
69479 ** Any tables that the SrcList might point to are not duplicated.
69480 **
69481 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
69482 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
69483 ** truncated version of the usual Expr structure that will be stored as
69484 ** part of the in-memory representation of the database schema.
69485 */
69486 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
69487   return exprDup(db, p, flags, 0);
69488 }
69489 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
69490   ExprList *pNew;
69491   struct ExprList_item *pItem, *pOldItem;
69492   int i;
69493   if( p==0 ) return 0;
69494   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
69495   if( pNew==0 ) return 0;
69496   pNew->iECursor = 0;
69497   pNew->nExpr = pNew->nAlloc = p->nExpr;
69498   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
69499   if( pItem==0 ){
69500     sqlite3DbFree(db, pNew);
69501     return 0;
69502   } 
69503   pOldItem = p->a;
69504   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
69505     Expr *pOldExpr = pOldItem->pExpr;
69506     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
69507     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
69508     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
69509     pItem->sortOrder = pOldItem->sortOrder;
69510     pItem->done = 0;
69511     pItem->iCol = pOldItem->iCol;
69512     pItem->iAlias = pOldItem->iAlias;
69513   }
69514   return pNew;
69515 }
69516
69517 /*
69518 ** If cursors, triggers, views and subqueries are all omitted from
69519 ** the build, then none of the following routines, except for 
69520 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
69521 ** called with a NULL argument.
69522 */
69523 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
69524  || !defined(SQLITE_OMIT_SUBQUERY)
69525 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
69526   SrcList *pNew;
69527   int i;
69528   int nByte;
69529   if( p==0 ) return 0;
69530   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
69531   pNew = sqlite3DbMallocRaw(db, nByte );
69532   if( pNew==0 ) return 0;
69533   pNew->nSrc = pNew->nAlloc = p->nSrc;
69534   for(i=0; i<p->nSrc; i++){
69535     struct SrcList_item *pNewItem = &pNew->a[i];
69536     struct SrcList_item *pOldItem = &p->a[i];
69537     Table *pTab;
69538     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
69539     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
69540     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
69541     pNewItem->jointype = pOldItem->jointype;
69542     pNewItem->iCursor = pOldItem->iCursor;
69543     pNewItem->isPopulated = pOldItem->isPopulated;
69544     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
69545     pNewItem->notIndexed = pOldItem->notIndexed;
69546     pNewItem->pIndex = pOldItem->pIndex;
69547     pTab = pNewItem->pTab = pOldItem->pTab;
69548     if( pTab ){
69549       pTab->nRef++;
69550     }
69551     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
69552     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
69553     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
69554     pNewItem->colUsed = pOldItem->colUsed;
69555   }
69556   return pNew;
69557 }
69558 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
69559   IdList *pNew;
69560   int i;
69561   if( p==0 ) return 0;
69562   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
69563   if( pNew==0 ) return 0;
69564   pNew->nId = pNew->nAlloc = p->nId;
69565   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
69566   if( pNew->a==0 ){
69567     sqlite3DbFree(db, pNew);
69568     return 0;
69569   }
69570   for(i=0; i<p->nId; i++){
69571     struct IdList_item *pNewItem = &pNew->a[i];
69572     struct IdList_item *pOldItem = &p->a[i];
69573     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
69574     pNewItem->idx = pOldItem->idx;
69575   }
69576   return pNew;
69577 }
69578 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
69579   Select *pNew;
69580   if( p==0 ) return 0;
69581   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
69582   if( pNew==0 ) return 0;
69583   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
69584   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
69585   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
69586   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
69587   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
69588   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
69589   pNew->op = p->op;
69590   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
69591   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
69592   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
69593   pNew->iLimit = 0;
69594   pNew->iOffset = 0;
69595   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
69596   pNew->pRightmost = 0;
69597   pNew->addrOpenEphm[0] = -1;
69598   pNew->addrOpenEphm[1] = -1;
69599   pNew->addrOpenEphm[2] = -1;
69600   return pNew;
69601 }
69602 #else
69603 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
69604   assert( p==0 );
69605   return 0;
69606 }
69607 #endif
69608
69609
69610 /*
69611 ** Add a new element to the end of an expression list.  If pList is
69612 ** initially NULL, then create a new expression list.
69613 **
69614 ** If a memory allocation error occurs, the entire list is freed and
69615 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
69616 ** that the new entry was successfully appended.
69617 */
69618 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
69619   Parse *pParse,          /* Parsing context */
69620   ExprList *pList,        /* List to which to append. Might be NULL */
69621   Expr *pExpr             /* Expression to be appended. Might be NULL */
69622 ){
69623   sqlite3 *db = pParse->db;
69624   if( pList==0 ){
69625     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
69626     if( pList==0 ){
69627       goto no_mem;
69628     }
69629     assert( pList->nAlloc==0 );
69630   }
69631   if( pList->nAlloc<=pList->nExpr ){
69632     struct ExprList_item *a;
69633     int n = pList->nAlloc*2 + 4;
69634     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
69635     if( a==0 ){
69636       goto no_mem;
69637     }
69638     pList->a = a;
69639     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
69640   }
69641   assert( pList->a!=0 );
69642   if( 1 ){
69643     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
69644     memset(pItem, 0, sizeof(*pItem));
69645     pItem->pExpr = pExpr;
69646   }
69647   return pList;
69648
69649 no_mem:     
69650   /* Avoid leaking memory if malloc has failed. */
69651   sqlite3ExprDelete(db, pExpr);
69652   sqlite3ExprListDelete(db, pList);
69653   return 0;
69654 }
69655
69656 /*
69657 ** Set the ExprList.a[].zName element of the most recently added item
69658 ** on the expression list.
69659 **
69660 ** pList might be NULL following an OOM error.  But pName should never be
69661 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
69662 ** is set.
69663 */
69664 SQLITE_PRIVATE void sqlite3ExprListSetName(
69665   Parse *pParse,          /* Parsing context */
69666   ExprList *pList,        /* List to which to add the span. */
69667   Token *pName,           /* Name to be added */
69668   int dequote             /* True to cause the name to be dequoted */
69669 ){
69670   assert( pList!=0 || pParse->db->mallocFailed!=0 );
69671   if( pList ){
69672     struct ExprList_item *pItem;
69673     assert( pList->nExpr>0 );
69674     pItem = &pList->a[pList->nExpr-1];
69675     assert( pItem->zName==0 );
69676     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
69677     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
69678   }
69679 }
69680
69681 /*
69682 ** Set the ExprList.a[].zSpan element of the most recently added item
69683 ** on the expression list.
69684 **
69685 ** pList might be NULL following an OOM error.  But pSpan should never be
69686 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
69687 ** is set.
69688 */
69689 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
69690   Parse *pParse,          /* Parsing context */
69691   ExprList *pList,        /* List to which to add the span. */
69692   ExprSpan *pSpan         /* The span to be added */
69693 ){
69694   sqlite3 *db = pParse->db;
69695   assert( pList!=0 || db->mallocFailed!=0 );
69696   if( pList ){
69697     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
69698     assert( pList->nExpr>0 );
69699     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
69700     sqlite3DbFree(db, pItem->zSpan);
69701     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
69702                                     (int)(pSpan->zEnd - pSpan->zStart));
69703   }
69704 }
69705
69706 /*
69707 ** If the expression list pEList contains more than iLimit elements,
69708 ** leave an error message in pParse.
69709 */
69710 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
69711   Parse *pParse,
69712   ExprList *pEList,
69713   const char *zObject
69714 ){
69715   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
69716   testcase( pEList && pEList->nExpr==mx );
69717   testcase( pEList && pEList->nExpr==mx+1 );
69718   if( pEList && pEList->nExpr>mx ){
69719     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
69720   }
69721 }
69722
69723 /*
69724 ** Delete an entire expression list.
69725 */
69726 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
69727   int i;
69728   struct ExprList_item *pItem;
69729   if( pList==0 ) return;
69730   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
69731   assert( pList->nExpr<=pList->nAlloc );
69732   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
69733     sqlite3ExprDelete(db, pItem->pExpr);
69734     sqlite3DbFree(db, pItem->zName);
69735     sqlite3DbFree(db, pItem->zSpan);
69736   }
69737   sqlite3DbFree(db, pList->a);
69738   sqlite3DbFree(db, pList);
69739 }
69740
69741 /*
69742 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
69743 ** to an integer.  These routines are checking an expression to see
69744 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
69745 ** not constant.
69746 **
69747 ** These callback routines are used to implement the following:
69748 **
69749 **     sqlite3ExprIsConstant()
69750 **     sqlite3ExprIsConstantNotJoin()
69751 **     sqlite3ExprIsConstantOrFunction()
69752 **
69753 */
69754 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
69755
69756   /* If pWalker->u.i is 3 then any term of the expression that comes from
69757   ** the ON or USING clauses of a join disqualifies the expression
69758   ** from being considered constant. */
69759   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
69760     pWalker->u.i = 0;
69761     return WRC_Abort;
69762   }
69763
69764   switch( pExpr->op ){
69765     /* Consider functions to be constant if all their arguments are constant
69766     ** and pWalker->u.i==2 */
69767     case TK_FUNCTION:
69768       if( pWalker->u.i==2 ) return 0;
69769       /* Fall through */
69770     case TK_ID:
69771     case TK_COLUMN:
69772     case TK_AGG_FUNCTION:
69773     case TK_AGG_COLUMN:
69774       testcase( pExpr->op==TK_ID );
69775       testcase( pExpr->op==TK_COLUMN );
69776       testcase( pExpr->op==TK_AGG_FUNCTION );
69777       testcase( pExpr->op==TK_AGG_COLUMN );
69778       pWalker->u.i = 0;
69779       return WRC_Abort;
69780     default:
69781       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
69782       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
69783       return WRC_Continue;
69784   }
69785 }
69786 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
69787   UNUSED_PARAMETER(NotUsed);
69788   pWalker->u.i = 0;
69789   return WRC_Abort;
69790 }
69791 static int exprIsConst(Expr *p, int initFlag){
69792   Walker w;
69793   w.u.i = initFlag;
69794   w.xExprCallback = exprNodeIsConstant;
69795   w.xSelectCallback = selectNodeIsConstant;
69796   sqlite3WalkExpr(&w, p);
69797   return w.u.i;
69798 }
69799
69800 /*
69801 ** Walk an expression tree.  Return 1 if the expression is constant
69802 ** and 0 if it involves variables or function calls.
69803 **
69804 ** For the purposes of this function, a double-quoted string (ex: "abc")
69805 ** is considered a variable but a single-quoted string (ex: 'abc') is
69806 ** a constant.
69807 */
69808 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
69809   return exprIsConst(p, 1);
69810 }
69811
69812 /*
69813 ** Walk an expression tree.  Return 1 if the expression is constant
69814 ** that does no originate from the ON or USING clauses of a join.
69815 ** Return 0 if it involves variables or function calls or terms from
69816 ** an ON or USING clause.
69817 */
69818 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
69819   return exprIsConst(p, 3);
69820 }
69821
69822 /*
69823 ** Walk an expression tree.  Return 1 if the expression is constant
69824 ** or a function call with constant arguments.  Return and 0 if there
69825 ** are any variables.
69826 **
69827 ** For the purposes of this function, a double-quoted string (ex: "abc")
69828 ** is considered a variable but a single-quoted string (ex: 'abc') is
69829 ** a constant.
69830 */
69831 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
69832   return exprIsConst(p, 2);
69833 }
69834
69835 /*
69836 ** If the expression p codes a constant integer that is small enough
69837 ** to fit in a 32-bit integer, return 1 and put the value of the integer
69838 ** in *pValue.  If the expression is not an integer or if it is too big
69839 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
69840 */
69841 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
69842   int rc = 0;
69843   if( p->flags & EP_IntValue ){
69844     *pValue = p->u.iValue;
69845     return 1;
69846   }
69847   switch( p->op ){
69848     case TK_INTEGER: {
69849       rc = sqlite3GetInt32(p->u.zToken, pValue);
69850       assert( rc==0 );
69851       break;
69852     }
69853     case TK_UPLUS: {
69854       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
69855       break;
69856     }
69857     case TK_UMINUS: {
69858       int v;
69859       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
69860         *pValue = -v;
69861         rc = 1;
69862       }
69863       break;
69864     }
69865     default: break;
69866   }
69867   if( rc ){
69868     assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
69869                || (p->flags2 & EP2_MallocedToken)==0 );
69870     p->op = TK_INTEGER;
69871     p->flags |= EP_IntValue;
69872     p->u.iValue = *pValue;
69873   }
69874   return rc;
69875 }
69876
69877 /*
69878 ** Return FALSE if there is no chance that the expression can be NULL.
69879 **
69880 ** If the expression might be NULL or if the expression is too complex
69881 ** to tell return TRUE.  
69882 **
69883 ** This routine is used as an optimization, to skip OP_IsNull opcodes
69884 ** when we know that a value cannot be NULL.  Hence, a false positive
69885 ** (returning TRUE when in fact the expression can never be NULL) might
69886 ** be a small performance hit but is otherwise harmless.  On the other
69887 ** hand, a false negative (returning FALSE when the result could be NULL)
69888 ** will likely result in an incorrect answer.  So when in doubt, return
69889 ** TRUE.
69890 */
69891 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
69892   u8 op;
69893   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
69894   op = p->op;
69895   if( op==TK_REGISTER ) op = p->op2;
69896   switch( op ){
69897     case TK_INTEGER:
69898     case TK_STRING:
69899     case TK_FLOAT:
69900     case TK_BLOB:
69901       return 0;
69902     default:
69903       return 1;
69904   }
69905 }
69906
69907 /*
69908 ** Generate an OP_IsNull instruction that tests register iReg and jumps
69909 ** to location iDest if the value in iReg is NULL.  The value in iReg 
69910 ** was computed by pExpr.  If we can look at pExpr at compile-time and
69911 ** determine that it can never generate a NULL, then the OP_IsNull operation
69912 ** can be omitted.
69913 */
69914 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
69915   Vdbe *v,            /* The VDBE under construction */
69916   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
69917   int iReg,           /* Test the value in this register for NULL */
69918   int iDest           /* Jump here if the value is null */
69919 ){
69920   if( sqlite3ExprCanBeNull(pExpr) ){
69921     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
69922   }
69923 }
69924
69925 /*
69926 ** Return TRUE if the given expression is a constant which would be
69927 ** unchanged by OP_Affinity with the affinity given in the second
69928 ** argument.
69929 **
69930 ** This routine is used to determine if the OP_Affinity operation
69931 ** can be omitted.  When in doubt return FALSE.  A false negative
69932 ** is harmless.  A false positive, however, can result in the wrong
69933 ** answer.
69934 */
69935 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
69936   u8 op;
69937   if( aff==SQLITE_AFF_NONE ) return 1;
69938   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
69939   op = p->op;
69940   if( op==TK_REGISTER ) op = p->op2;
69941   switch( op ){
69942     case TK_INTEGER: {
69943       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
69944     }
69945     case TK_FLOAT: {
69946       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
69947     }
69948     case TK_STRING: {
69949       return aff==SQLITE_AFF_TEXT;
69950     }
69951     case TK_BLOB: {
69952       return 1;
69953     }
69954     case TK_COLUMN: {
69955       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
69956       return p->iColumn<0
69957           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
69958     }
69959     default: {
69960       return 0;
69961     }
69962   }
69963 }
69964
69965 /*
69966 ** Return TRUE if the given string is a row-id column name.
69967 */
69968 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
69969   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
69970   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
69971   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
69972   return 0;
69973 }
69974
69975 /*
69976 ** Return true if we are able to the IN operator optimization on a
69977 ** query of the form
69978 **
69979 **       x IN (SELECT ...)
69980 **
69981 ** Where the SELECT... clause is as specified by the parameter to this
69982 ** routine.
69983 **
69984 ** The Select object passed in has already been preprocessed and no
69985 ** errors have been found.
69986 */
69987 #ifndef SQLITE_OMIT_SUBQUERY
69988 static int isCandidateForInOpt(Select *p){
69989   SrcList *pSrc;
69990   ExprList *pEList;
69991   Table *pTab;
69992   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
69993   if( p->pPrior ) return 0;              /* Not a compound SELECT */
69994   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
69995     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
69996     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
69997     return 0; /* No DISTINCT keyword and no aggregate functions */
69998   }
69999   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
70000   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
70001   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
70002   if( p->pWhere ) return 0;              /* Has no WHERE clause */
70003   pSrc = p->pSrc;
70004   assert( pSrc!=0 );
70005   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
70006   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
70007   pTab = pSrc->a[0].pTab;
70008   if( NEVER(pTab==0) ) return 0;
70009   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
70010   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
70011   pEList = p->pEList;
70012   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
70013   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
70014   return 1;
70015 }
70016 #endif /* SQLITE_OMIT_SUBQUERY */
70017
70018 /*
70019 ** This function is used by the implementation of the IN (...) operator.
70020 ** It's job is to find or create a b-tree structure that may be used
70021 ** either to test for membership of the (...) set or to iterate through
70022 ** its members, skipping duplicates.
70023 **
70024 ** The index of the cursor opened on the b-tree (database table, database index 
70025 ** or ephermal table) is stored in pX->iTable before this function returns.
70026 ** The returned value of this function indicates the b-tree type, as follows:
70027 **
70028 **   IN_INDEX_ROWID - The cursor was opened on a database table.
70029 **   IN_INDEX_INDEX - The cursor was opened on a database index.
70030 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
70031 **                    populated epheremal table.
70032 **
70033 ** An existing b-tree may only be used if the SELECT is of the simple
70034 ** form:
70035 **
70036 **     SELECT <column> FROM <table>
70037 **
70038 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
70039 ** through the set members, skipping any duplicates. In this case an
70040 ** epheremal table must be used unless the selected <column> is guaranteed
70041 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
70042 ** has a UNIQUE constraint or UNIQUE index.
70043 **
70044 ** If the prNotFound parameter is not 0, then the b-tree will be used 
70045 ** for fast set membership tests. In this case an epheremal table must 
70046 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
70047 ** be found with <column> as its left-most column.
70048 **
70049 ** When the b-tree is being used for membership tests, the calling function
70050 ** needs to know whether or not the structure contains an SQL NULL 
70051 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
70052 ** If there is any chance that the (...) might contain a NULL value at
70053 ** runtime, then a register is allocated and the register number written
70054 ** to *prNotFound. If there is no chance that the (...) contains a
70055 ** NULL value, then *prNotFound is left unchanged.
70056 **
70057 ** If a register is allocated and its location stored in *prNotFound, then
70058 ** its initial value is NULL.  If the (...) does not remain constant
70059 ** for the duration of the query (i.e. the SELECT within the (...)
70060 ** is a correlated subquery) then the value of the allocated register is
70061 ** reset to NULL each time the subquery is rerun. This allows the
70062 ** caller to use vdbe code equivalent to the following:
70063 **
70064 **   if( register==NULL ){
70065 **     has_null = <test if data structure contains null>
70066 **     register = 1
70067 **   }
70068 **
70069 ** in order to avoid running the <test if data structure contains null>
70070 ** test more often than is necessary.
70071 */
70072 #ifndef SQLITE_OMIT_SUBQUERY
70073 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
70074   Select *p;                            /* SELECT to the right of IN operator */
70075   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
70076   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
70077   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
70078
70079   assert( pX->op==TK_IN );
70080
70081   /* Check to see if an existing table or index can be used to
70082   ** satisfy the query.  This is preferable to generating a new 
70083   ** ephemeral table.
70084   */
70085   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
70086   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
70087     sqlite3 *db = pParse->db;              /* Database connection */
70088     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
70089     int iCol = pExpr->iColumn;             /* Index of column <column> */
70090     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
70091     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
70092     int iDb;                               /* Database idx for pTab */
70093    
70094     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
70095     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70096     sqlite3CodeVerifySchema(pParse, iDb);
70097     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
70098
70099     /* This function is only called from two places. In both cases the vdbe
70100     ** has already been allocated. So assume sqlite3GetVdbe() is always
70101     ** successful here.
70102     */
70103     assert(v);
70104     if( iCol<0 ){
70105       int iMem = ++pParse->nMem;
70106       int iAddr;
70107
70108       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
70109       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
70110
70111       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
70112       eType = IN_INDEX_ROWID;
70113
70114       sqlite3VdbeJumpHere(v, iAddr);
70115     }else{
70116       Index *pIdx;                         /* Iterator variable */
70117
70118       /* The collation sequence used by the comparison. If an index is to
70119       ** be used in place of a temp-table, it must be ordered according
70120       ** to this collation sequence.  */
70121       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
70122
70123       /* Check that the affinity that will be used to perform the 
70124       ** comparison is the same as the affinity of the column. If
70125       ** it is not, it is not possible to use any index.
70126       */
70127       char aff = comparisonAffinity(pX);
70128       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
70129
70130       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
70131         if( (pIdx->aiColumn[0]==iCol)
70132          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
70133          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
70134         ){
70135           int iMem = ++pParse->nMem;
70136           int iAddr;
70137           char *pKey;
70138   
70139           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
70140           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
70141           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
70142   
70143           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
70144                                pKey,P4_KEYINFO_HANDOFF);
70145           VdbeComment((v, "%s", pIdx->zName));
70146           eType = IN_INDEX_INDEX;
70147
70148           sqlite3VdbeJumpHere(v, iAddr);
70149           if( prNotFound && !pTab->aCol[iCol].notNull ){
70150             *prNotFound = ++pParse->nMem;
70151           }
70152         }
70153       }
70154     }
70155   }
70156
70157   if( eType==0 ){
70158     /* Could not found an existing table or index to use as the RHS b-tree.
70159     ** We will have to generate an ephemeral table to do the job.
70160     */
70161     double savedNQueryLoop = pParse->nQueryLoop;
70162     int rMayHaveNull = 0;
70163     eType = IN_INDEX_EPH;
70164     if( prNotFound ){
70165       *prNotFound = rMayHaveNull = ++pParse->nMem;
70166     }else{
70167       testcase( pParse->nQueryLoop>(double)1 );
70168       pParse->nQueryLoop = (double)1;
70169       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
70170         eType = IN_INDEX_ROWID;
70171       }
70172     }
70173     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
70174     pParse->nQueryLoop = savedNQueryLoop;
70175   }else{
70176     pX->iTable = iTab;
70177   }
70178   return eType;
70179 }
70180 #endif
70181
70182 /*
70183 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
70184 ** or IN operators.  Examples:
70185 **
70186 **     (SELECT a FROM b)          -- subquery
70187 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
70188 **     x IN (4,5,11)              -- IN operator with list on right-hand side
70189 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
70190 **
70191 ** The pExpr parameter describes the expression that contains the IN
70192 ** operator or subquery.
70193 **
70194 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
70195 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
70196 ** to some integer key column of a table B-Tree. In this case, use an
70197 ** intkey B-Tree to store the set of IN(...) values instead of the usual
70198 ** (slower) variable length keys B-Tree.
70199 **
70200 ** If rMayHaveNull is non-zero, that means that the operation is an IN
70201 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
70202 ** Furthermore, the IN is in a WHERE clause and that we really want
70203 ** to iterate over the RHS of the IN operator in order to quickly locate
70204 ** all corresponding LHS elements.  All this routine does is initialize
70205 ** the register given by rMayHaveNull to NULL.  Calling routines will take
70206 ** care of changing this register value to non-NULL if the RHS is NULL-free.
70207 **
70208 ** If rMayHaveNull is zero, that means that the subquery is being used
70209 ** for membership testing only.  There is no need to initialize any
70210 ** registers to indicate the presense or absence of NULLs on the RHS.
70211 **
70212 ** For a SELECT or EXISTS operator, return the register that holds the
70213 ** result.  For IN operators or if an error occurs, the return value is 0.
70214 */
70215 #ifndef SQLITE_OMIT_SUBQUERY
70216 SQLITE_PRIVATE int sqlite3CodeSubselect(
70217   Parse *pParse,          /* Parsing context */
70218   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
70219   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
70220   int isRowid             /* If true, LHS of IN operator is a rowid */
70221 ){
70222   int testAddr = 0;                       /* One-time test address */
70223   int rReg = 0;                           /* Register storing resulting */
70224   Vdbe *v = sqlite3GetVdbe(pParse);
70225   if( NEVER(v==0) ) return 0;
70226   sqlite3ExprCachePush(pParse);
70227
70228   /* This code must be run in its entirety every time it is encountered
70229   ** if any of the following is true:
70230   **
70231   **    *  The right-hand side is a correlated subquery
70232   **    *  The right-hand side is an expression list containing variables
70233   **    *  We are inside a trigger
70234   **
70235   ** If all of the above are false, then we can run this code just once
70236   ** save the results, and reuse the same result on subsequent invocations.
70237   */
70238   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
70239     int mem = ++pParse->nMem;
70240     sqlite3VdbeAddOp1(v, OP_If, mem);
70241     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
70242     assert( testAddr>0 || pParse->db->mallocFailed );
70243   }
70244
70245 #ifndef SQLITE_OMIT_EXPLAIN
70246   if( pParse->explain==2 ){
70247     char *zMsg = sqlite3MPrintf(
70248         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr?"":"CORRELATED ",
70249         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
70250     );
70251     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
70252   }
70253 #endif
70254
70255   switch( pExpr->op ){
70256     case TK_IN: {
70257       char affinity;              /* Affinity of the LHS of the IN */
70258       KeyInfo keyInfo;            /* Keyinfo for the generated table */
70259       int addr;                   /* Address of OP_OpenEphemeral instruction */
70260       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
70261
70262       if( rMayHaveNull ){
70263         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
70264       }
70265
70266       affinity = sqlite3ExprAffinity(pLeft);
70267
70268       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
70269       ** expression it is handled the same way.  An ephemeral table is 
70270       ** filled with single-field index keys representing the results
70271       ** from the SELECT or the <exprlist>.
70272       **
70273       ** If the 'x' expression is a column value, or the SELECT...
70274       ** statement returns a column value, then the affinity of that
70275       ** column is used to build the index keys. If both 'x' and the
70276       ** SELECT... statement are columns, then numeric affinity is used
70277       ** if either column has NUMERIC or INTEGER affinity. If neither
70278       ** 'x' nor the SELECT... statement are columns, then numeric affinity
70279       ** is used.
70280       */
70281       pExpr->iTable = pParse->nTab++;
70282       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
70283       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
70284       memset(&keyInfo, 0, sizeof(keyInfo));
70285       keyInfo.nField = 1;
70286
70287       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
70288         /* Case 1:     expr IN (SELECT ...)
70289         **
70290         ** Generate code to write the results of the select into the temporary
70291         ** table allocated and opened above.
70292         */
70293         SelectDest dest;
70294         ExprList *pEList;
70295
70296         assert( !isRowid );
70297         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
70298         dest.affinity = (u8)affinity;
70299         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
70300         pExpr->x.pSelect->iLimit = 0;
70301         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
70302           return 0;
70303         }
70304         pEList = pExpr->x.pSelect->pEList;
70305         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
70306           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
70307               pEList->a[0].pExpr);
70308         }
70309       }else if( ALWAYS(pExpr->x.pList!=0) ){
70310         /* Case 2:     expr IN (exprlist)
70311         **
70312         ** For each expression, build an index key from the evaluation and
70313         ** store it in the temporary table. If <expr> is a column, then use
70314         ** that columns affinity when building index keys. If <expr> is not
70315         ** a column, use numeric affinity.
70316         */
70317         int i;
70318         ExprList *pList = pExpr->x.pList;
70319         struct ExprList_item *pItem;
70320         int r1, r2, r3;
70321
70322         if( !affinity ){
70323           affinity = SQLITE_AFF_NONE;
70324         }
70325         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
70326
70327         /* Loop through each expression in <exprlist>. */
70328         r1 = sqlite3GetTempReg(pParse);
70329         r2 = sqlite3GetTempReg(pParse);
70330         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
70331         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
70332           Expr *pE2 = pItem->pExpr;
70333           int iValToIns;
70334
70335           /* If the expression is not constant then we will need to
70336           ** disable the test that was generated above that makes sure
70337           ** this code only executes once.  Because for a non-constant
70338           ** expression we need to rerun this code each time.
70339           */
70340           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
70341             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
70342             testAddr = 0;
70343           }
70344
70345           /* Evaluate the expression and insert it into the temp table */
70346           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
70347             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
70348           }else{
70349             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
70350             if( isRowid ){
70351               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
70352                                 sqlite3VdbeCurrentAddr(v)+2);
70353               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
70354             }else{
70355               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
70356               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
70357               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
70358             }
70359           }
70360         }
70361         sqlite3ReleaseTempReg(pParse, r1);
70362         sqlite3ReleaseTempReg(pParse, r2);
70363       }
70364       if( !isRowid ){
70365         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
70366       }
70367       break;
70368     }
70369
70370     case TK_EXISTS:
70371     case TK_SELECT:
70372     default: {
70373       /* If this has to be a scalar SELECT.  Generate code to put the
70374       ** value of this select in a memory cell and record the number
70375       ** of the memory cell in iColumn.  If this is an EXISTS, write
70376       ** an integer 0 (not exists) or 1 (exists) into a memory cell
70377       ** and record that memory cell in iColumn.
70378       */
70379       Select *pSel;                         /* SELECT statement to encode */
70380       SelectDest dest;                      /* How to deal with SELECt result */
70381
70382       testcase( pExpr->op==TK_EXISTS );
70383       testcase( pExpr->op==TK_SELECT );
70384       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
70385
70386       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
70387       pSel = pExpr->x.pSelect;
70388       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
70389       if( pExpr->op==TK_SELECT ){
70390         dest.eDest = SRT_Mem;
70391         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
70392         VdbeComment((v, "Init subquery result"));
70393       }else{
70394         dest.eDest = SRT_Exists;
70395         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
70396         VdbeComment((v, "Init EXISTS result"));
70397       }
70398       sqlite3ExprDelete(pParse->db, pSel->pLimit);
70399       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
70400                                   &sqlite3IntTokens[1]);
70401       pSel->iLimit = 0;
70402       if( sqlite3Select(pParse, pSel, &dest) ){
70403         return 0;
70404       }
70405       rReg = dest.iParm;
70406       ExprSetIrreducible(pExpr);
70407       break;
70408     }
70409   }
70410
70411   if( testAddr ){
70412     sqlite3VdbeJumpHere(v, testAddr-1);
70413   }
70414   sqlite3ExprCachePop(pParse, 1);
70415
70416   return rReg;
70417 }
70418 #endif /* SQLITE_OMIT_SUBQUERY */
70419
70420 #ifndef SQLITE_OMIT_SUBQUERY
70421 /*
70422 ** Generate code for an IN expression.
70423 **
70424 **      x IN (SELECT ...)
70425 **      x IN (value, value, ...)
70426 **
70427 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
70428 ** is an array of zero or more values.  The expression is true if the LHS is
70429 ** contained within the RHS.  The value of the expression is unknown (NULL)
70430 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
70431 ** RHS contains one or more NULL values.
70432 **
70433 ** This routine generates code will jump to destIfFalse if the LHS is not 
70434 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
70435 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
70436 ** within the RHS then fall through.
70437 */
70438 static void sqlite3ExprCodeIN(
70439   Parse *pParse,        /* Parsing and code generating context */
70440   Expr *pExpr,          /* The IN expression */
70441   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
70442   int destIfNull        /* Jump here if the results are unknown due to NULLs */
70443 ){
70444   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
70445   char affinity;        /* Comparison affinity to use */
70446   int eType;            /* Type of the RHS */
70447   int r1;               /* Temporary use register */
70448   Vdbe *v;              /* Statement under construction */
70449
70450   /* Compute the RHS.   After this step, the table with cursor
70451   ** pExpr->iTable will contains the values that make up the RHS.
70452   */
70453   v = pParse->pVdbe;
70454   assert( v!=0 );       /* OOM detected prior to this routine */
70455   VdbeNoopComment((v, "begin IN expr"));
70456   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
70457
70458   /* Figure out the affinity to use to create a key from the results
70459   ** of the expression. affinityStr stores a static string suitable for
70460   ** P4 of OP_MakeRecord.
70461   */
70462   affinity = comparisonAffinity(pExpr);
70463
70464   /* Code the LHS, the <expr> from "<expr> IN (...)".
70465   */
70466   sqlite3ExprCachePush(pParse);
70467   r1 = sqlite3GetTempReg(pParse);
70468   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
70469
70470   /* If the LHS is NULL, then the result is either false or NULL depending
70471   ** on whether the RHS is empty or not, respectively.
70472   */
70473   if( destIfNull==destIfFalse ){
70474     /* Shortcut for the common case where the false and NULL outcomes are
70475     ** the same. */
70476     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
70477   }else{
70478     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
70479     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
70480     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
70481     sqlite3VdbeJumpHere(v, addr1);
70482   }
70483
70484   if( eType==IN_INDEX_ROWID ){
70485     /* In this case, the RHS is the ROWID of table b-tree
70486     */
70487     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
70488     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
70489   }else{
70490     /* In this case, the RHS is an index b-tree.
70491     */
70492     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
70493
70494     /* If the set membership test fails, then the result of the 
70495     ** "x IN (...)" expression must be either 0 or NULL. If the set
70496     ** contains no NULL values, then the result is 0. If the set 
70497     ** contains one or more NULL values, then the result of the
70498     ** expression is also NULL.
70499     */
70500     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
70501       /* This branch runs if it is known at compile time that the RHS
70502       ** cannot contain NULL values. This happens as the result
70503       ** of a "NOT NULL" constraint in the database schema.
70504       **
70505       ** Also run this branch if NULL is equivalent to FALSE
70506       ** for this particular IN operator.
70507       */
70508       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
70509
70510     }else{
70511       /* In this branch, the RHS of the IN might contain a NULL and
70512       ** the presence of a NULL on the RHS makes a difference in the
70513       ** outcome.
70514       */
70515       int j1, j2, j3;
70516
70517       /* First check to see if the LHS is contained in the RHS.  If so,
70518       ** then the presence of NULLs in the RHS does not matter, so jump
70519       ** over all of the code that follows.
70520       */
70521       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
70522
70523       /* Here we begin generating code that runs if the LHS is not
70524       ** contained within the RHS.  Generate additional code that
70525       ** tests the RHS for NULLs.  If the RHS contains a NULL then
70526       ** jump to destIfNull.  If there are no NULLs in the RHS then
70527       ** jump to destIfFalse.
70528       */
70529       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
70530       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
70531       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
70532       sqlite3VdbeJumpHere(v, j3);
70533       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
70534       sqlite3VdbeJumpHere(v, j2);
70535
70536       /* Jump to the appropriate target depending on whether or not
70537       ** the RHS contains a NULL
70538       */
70539       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
70540       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
70541
70542       /* The OP_Found at the top of this branch jumps here when true, 
70543       ** causing the overall IN expression evaluation to fall through.
70544       */
70545       sqlite3VdbeJumpHere(v, j1);
70546     }
70547   }
70548   sqlite3ReleaseTempReg(pParse, r1);
70549   sqlite3ExprCachePop(pParse, 1);
70550   VdbeComment((v, "end IN expr"));
70551 }
70552 #endif /* SQLITE_OMIT_SUBQUERY */
70553
70554 /*
70555 ** Duplicate an 8-byte value
70556 */
70557 static char *dup8bytes(Vdbe *v, const char *in){
70558   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
70559   if( out ){
70560     memcpy(out, in, 8);
70561   }
70562   return out;
70563 }
70564
70565 #ifndef SQLITE_OMIT_FLOATING_POINT
70566 /*
70567 ** Generate an instruction that will put the floating point
70568 ** value described by z[0..n-1] into register iMem.
70569 **
70570 ** The z[] string will probably not be zero-terminated.  But the 
70571 ** z[n] character is guaranteed to be something that does not look
70572 ** like the continuation of the number.
70573 */
70574 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
70575   if( ALWAYS(z!=0) ){
70576     double value;
70577     char *zV;
70578     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
70579     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
70580     if( negateFlag ) value = -value;
70581     zV = dup8bytes(v, (char*)&value);
70582     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
70583   }
70584 }
70585 #endif
70586
70587
70588 /*
70589 ** Generate an instruction that will put the integer describe by
70590 ** text z[0..n-1] into register iMem.
70591 **
70592 ** Expr.u.zToken is always UTF8 and zero-terminated.
70593 */
70594 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
70595   Vdbe *v = pParse->pVdbe;
70596   if( pExpr->flags & EP_IntValue ){
70597     int i = pExpr->u.iValue;
70598     if( negFlag ) i = -i;
70599     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
70600   }else{
70601     int c;
70602     i64 value;
70603     const char *z = pExpr->u.zToken;
70604     assert( z!=0 );
70605     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
70606     if( c==0 || (c==2 && negFlag) ){
70607       char *zV;
70608       if( negFlag ){ value = -value; }
70609       zV = dup8bytes(v, (char*)&value);
70610       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
70611     }else{
70612 #ifdef SQLITE_OMIT_FLOATING_POINT
70613       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
70614 #else
70615       codeReal(v, z, negFlag, iMem);
70616 #endif
70617     }
70618   }
70619 }
70620
70621 /*
70622 ** Clear a cache entry.
70623 */
70624 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
70625   if( p->tempReg ){
70626     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
70627       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
70628     }
70629     p->tempReg = 0;
70630   }
70631 }
70632
70633
70634 /*
70635 ** Record in the column cache that a particular column from a
70636 ** particular table is stored in a particular register.
70637 */
70638 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
70639   int i;
70640   int minLru;
70641   int idxLru;
70642   struct yColCache *p;
70643
70644   assert( iReg>0 );  /* Register numbers are always positive */
70645   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
70646
70647   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
70648   ** for testing only - to verify that SQLite always gets the same answer
70649   ** with and without the column cache.
70650   */
70651   if( pParse->db->flags & SQLITE_ColumnCache ) return;
70652
70653   /* First replace any existing entry.
70654   **
70655   ** Actually, the way the column cache is currently used, we are guaranteed
70656   ** that the object will never already be in cache.  Verify this guarantee.
70657   */
70658 #ifndef NDEBUG
70659   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70660 #if 0 /* This code wold remove the entry from the cache if it existed */
70661     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
70662       cacheEntryClear(pParse, p);
70663       p->iLevel = pParse->iCacheLevel;
70664       p->iReg = iReg;
70665       p->lru = pParse->iCacheCnt++;
70666       return;
70667     }
70668 #endif
70669     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
70670   }
70671 #endif
70672
70673   /* Find an empty slot and replace it */
70674   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70675     if( p->iReg==0 ){
70676       p->iLevel = pParse->iCacheLevel;
70677       p->iTable = iTab;
70678       p->iColumn = iCol;
70679       p->iReg = iReg;
70680       p->tempReg = 0;
70681       p->lru = pParse->iCacheCnt++;
70682       return;
70683     }
70684   }
70685
70686   /* Replace the last recently used */
70687   minLru = 0x7fffffff;
70688   idxLru = -1;
70689   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70690     if( p->lru<minLru ){
70691       idxLru = i;
70692       minLru = p->lru;
70693     }
70694   }
70695   if( ALWAYS(idxLru>=0) ){
70696     p = &pParse->aColCache[idxLru];
70697     p->iLevel = pParse->iCacheLevel;
70698     p->iTable = iTab;
70699     p->iColumn = iCol;
70700     p->iReg = iReg;
70701     p->tempReg = 0;
70702     p->lru = pParse->iCacheCnt++;
70703     return;
70704   }
70705 }
70706
70707 /*
70708 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
70709 ** Purge the range of registers from the column cache.
70710 */
70711 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
70712   int i;
70713   int iLast = iReg + nReg - 1;
70714   struct yColCache *p;
70715   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70716     int r = p->iReg;
70717     if( r>=iReg && r<=iLast ){
70718       cacheEntryClear(pParse, p);
70719       p->iReg = 0;
70720     }
70721   }
70722 }
70723
70724 /*
70725 ** Remember the current column cache context.  Any new entries added
70726 ** added to the column cache after this call are removed when the
70727 ** corresponding pop occurs.
70728 */
70729 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
70730   pParse->iCacheLevel++;
70731 }
70732
70733 /*
70734 ** Remove from the column cache any entries that were added since the
70735 ** the previous N Push operations.  In other words, restore the cache
70736 ** to the state it was in N Pushes ago.
70737 */
70738 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
70739   int i;
70740   struct yColCache *p;
70741   assert( N>0 );
70742   assert( pParse->iCacheLevel>=N );
70743   pParse->iCacheLevel -= N;
70744   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70745     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
70746       cacheEntryClear(pParse, p);
70747       p->iReg = 0;
70748     }
70749   }
70750 }
70751
70752 /*
70753 ** When a cached column is reused, make sure that its register is
70754 ** no longer available as a temp register.  ticket #3879:  that same
70755 ** register might be in the cache in multiple places, so be sure to
70756 ** get them all.
70757 */
70758 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
70759   int i;
70760   struct yColCache *p;
70761   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70762     if( p->iReg==iReg ){
70763       p->tempReg = 0;
70764     }
70765   }
70766 }
70767
70768 /*
70769 ** Generate code to extract the value of the iCol-th column of a table.
70770 */
70771 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
70772   Vdbe *v,        /* The VDBE under construction */
70773   Table *pTab,    /* The table containing the value */
70774   int iTabCur,    /* The cursor for this table */
70775   int iCol,       /* Index of the column to extract */
70776   int regOut      /* Extract the valud into this register */
70777 ){
70778   if( iCol<0 || iCol==pTab->iPKey ){
70779     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
70780   }else{
70781     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
70782     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
70783   }
70784   if( iCol>=0 ){
70785     sqlite3ColumnDefault(v, pTab, iCol, regOut);
70786   }
70787 }
70788
70789 /*
70790 ** Generate code that will extract the iColumn-th column from
70791 ** table pTab and store the column value in a register.  An effort
70792 ** is made to store the column value in register iReg, but this is
70793 ** not guaranteed.  The location of the column value is returned.
70794 **
70795 ** There must be an open cursor to pTab in iTable when this routine
70796 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
70797 */
70798 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
70799   Parse *pParse,   /* Parsing and code generating context */
70800   Table *pTab,     /* Description of the table we are reading from */
70801   int iColumn,     /* Index of the table column */
70802   int iTable,      /* The cursor pointing to the table */
70803   int iReg         /* Store results here */
70804 ){
70805   Vdbe *v = pParse->pVdbe;
70806   int i;
70807   struct yColCache *p;
70808
70809   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70810     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
70811       p->lru = pParse->iCacheCnt++;
70812       sqlite3ExprCachePinRegister(pParse, p->iReg);
70813       return p->iReg;
70814     }
70815   }  
70816   assert( v!=0 );
70817   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
70818   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
70819   return iReg;
70820 }
70821
70822 /*
70823 ** Clear all column cache entries.
70824 */
70825 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
70826   int i;
70827   struct yColCache *p;
70828
70829   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70830     if( p->iReg ){
70831       cacheEntryClear(pParse, p);
70832       p->iReg = 0;
70833     }
70834   }
70835 }
70836
70837 /*
70838 ** Record the fact that an affinity change has occurred on iCount
70839 ** registers starting with iStart.
70840 */
70841 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
70842   sqlite3ExprCacheRemove(pParse, iStart, iCount);
70843 }
70844
70845 /*
70846 ** Generate code to move content from registers iFrom...iFrom+nReg-1
70847 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
70848 */
70849 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
70850   int i;
70851   struct yColCache *p;
70852   if( NEVER(iFrom==iTo) ) return;
70853   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
70854   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70855     int x = p->iReg;
70856     if( x>=iFrom && x<iFrom+nReg ){
70857       p->iReg += iTo-iFrom;
70858     }
70859   }
70860 }
70861
70862 /*
70863 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
70864 ** over to iTo..iTo+nReg-1.
70865 */
70866 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
70867   int i;
70868   if( NEVER(iFrom==iTo) ) return;
70869   for(i=0; i<nReg; i++){
70870     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
70871   }
70872 }
70873
70874 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
70875 /*
70876 ** Return true if any register in the range iFrom..iTo (inclusive)
70877 ** is used as part of the column cache.
70878 **
70879 ** This routine is used within assert() and testcase() macros only
70880 ** and does not appear in a normal build.
70881 */
70882 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
70883   int i;
70884   struct yColCache *p;
70885   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
70886     int r = p->iReg;
70887     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
70888   }
70889   return 0;
70890 }
70891 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
70892
70893 /*
70894 ** Generate code into the current Vdbe to evaluate the given
70895 ** expression.  Attempt to store the results in register "target".
70896 ** Return the register where results are stored.
70897 **
70898 ** With this routine, there is no guarantee that results will
70899 ** be stored in target.  The result might be stored in some other
70900 ** register if it is convenient to do so.  The calling function
70901 ** must check the return code and move the results to the desired
70902 ** register.
70903 */
70904 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
70905   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
70906   int op;                   /* The opcode being coded */
70907   int inReg = target;       /* Results stored in register inReg */
70908   int regFree1 = 0;         /* If non-zero free this temporary register */
70909   int regFree2 = 0;         /* If non-zero free this temporary register */
70910   int r1, r2, r3, r4;       /* Various register numbers */
70911   sqlite3 *db = pParse->db; /* The database connection */
70912
70913   assert( target>0 && target<=pParse->nMem );
70914   if( v==0 ){
70915     assert( pParse->db->mallocFailed );
70916     return 0;
70917   }
70918
70919   if( pExpr==0 ){
70920     op = TK_NULL;
70921   }else{
70922     op = pExpr->op;
70923   }
70924   switch( op ){
70925     case TK_AGG_COLUMN: {
70926       AggInfo *pAggInfo = pExpr->pAggInfo;
70927       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
70928       if( !pAggInfo->directMode ){
70929         assert( pCol->iMem>0 );
70930         inReg = pCol->iMem;
70931         break;
70932       }else if( pAggInfo->useSortingIdx ){
70933         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
70934                               pCol->iSorterColumn, target);
70935         break;
70936       }
70937       /* Otherwise, fall thru into the TK_COLUMN case */
70938     }
70939     case TK_COLUMN: {
70940       if( pExpr->iTable<0 ){
70941         /* This only happens when coding check constraints */
70942         assert( pParse->ckBase>0 );
70943         inReg = pExpr->iColumn + pParse->ckBase;
70944       }else{
70945         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
70946                                  pExpr->iColumn, pExpr->iTable, target);
70947       }
70948       break;
70949     }
70950     case TK_INTEGER: {
70951       codeInteger(pParse, pExpr, 0, target);
70952       break;
70953     }
70954 #ifndef SQLITE_OMIT_FLOATING_POINT
70955     case TK_FLOAT: {
70956       assert( !ExprHasProperty(pExpr, EP_IntValue) );
70957       codeReal(v, pExpr->u.zToken, 0, target);
70958       break;
70959     }
70960 #endif
70961     case TK_STRING: {
70962       assert( !ExprHasProperty(pExpr, EP_IntValue) );
70963       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
70964       break;
70965     }
70966     case TK_NULL: {
70967       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
70968       break;
70969     }
70970 #ifndef SQLITE_OMIT_BLOB_LITERAL
70971     case TK_BLOB: {
70972       int n;
70973       const char *z;
70974       char *zBlob;
70975       assert( !ExprHasProperty(pExpr, EP_IntValue) );
70976       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
70977       assert( pExpr->u.zToken[1]=='\'' );
70978       z = &pExpr->u.zToken[2];
70979       n = sqlite3Strlen30(z) - 1;
70980       assert( z[n]=='\'' );
70981       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
70982       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
70983       break;
70984     }
70985 #endif
70986     case TK_VARIABLE: {
70987       assert( !ExprHasProperty(pExpr, EP_IntValue) );
70988       assert( pExpr->u.zToken!=0 );
70989       assert( pExpr->u.zToken[0]!=0 );
70990       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
70991       if( pExpr->u.zToken[1]!=0 ){
70992         sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
70993       }
70994       break;
70995     }
70996     case TK_REGISTER: {
70997       inReg = pExpr->iTable;
70998       break;
70999     }
71000     case TK_AS: {
71001       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
71002       break;
71003     }
71004 #ifndef SQLITE_OMIT_CAST
71005     case TK_CAST: {
71006       /* Expressions of the form:   CAST(pLeft AS token) */
71007       int aff, to_op;
71008       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
71009       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71010       aff = sqlite3AffinityType(pExpr->u.zToken);
71011       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
71012       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
71013       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
71014       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
71015       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
71016       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
71017       testcase( to_op==OP_ToText );
71018       testcase( to_op==OP_ToBlob );
71019       testcase( to_op==OP_ToNumeric );
71020       testcase( to_op==OP_ToInt );
71021       testcase( to_op==OP_ToReal );
71022       if( inReg!=target ){
71023         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
71024         inReg = target;
71025       }
71026       sqlite3VdbeAddOp1(v, to_op, inReg);
71027       testcase( usedAsColumnCache(pParse, inReg, inReg) );
71028       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
71029       break;
71030     }
71031 #endif /* SQLITE_OMIT_CAST */
71032     case TK_LT:
71033     case TK_LE:
71034     case TK_GT:
71035     case TK_GE:
71036     case TK_NE:
71037     case TK_EQ: {
71038       assert( TK_LT==OP_Lt );
71039       assert( TK_LE==OP_Le );
71040       assert( TK_GT==OP_Gt );
71041       assert( TK_GE==OP_Ge );
71042       assert( TK_EQ==OP_Eq );
71043       assert( TK_NE==OP_Ne );
71044       testcase( op==TK_LT );
71045       testcase( op==TK_LE );
71046       testcase( op==TK_GT );
71047       testcase( op==TK_GE );
71048       testcase( op==TK_EQ );
71049       testcase( op==TK_NE );
71050       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71051       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71052       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71053                   r1, r2, inReg, SQLITE_STOREP2);
71054       testcase( regFree1==0 );
71055       testcase( regFree2==0 );
71056       break;
71057     }
71058     case TK_IS:
71059     case TK_ISNOT: {
71060       testcase( op==TK_IS );
71061       testcase( op==TK_ISNOT );
71062       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71063       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71064       op = (op==TK_IS) ? TK_EQ : TK_NE;
71065       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71066                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
71067       testcase( regFree1==0 );
71068       testcase( regFree2==0 );
71069       break;
71070     }
71071     case TK_AND:
71072     case TK_OR:
71073     case TK_PLUS:
71074     case TK_STAR:
71075     case TK_MINUS:
71076     case TK_REM:
71077     case TK_BITAND:
71078     case TK_BITOR:
71079     case TK_SLASH:
71080     case TK_LSHIFT:
71081     case TK_RSHIFT: 
71082     case TK_CONCAT: {
71083       assert( TK_AND==OP_And );
71084       assert( TK_OR==OP_Or );
71085       assert( TK_PLUS==OP_Add );
71086       assert( TK_MINUS==OP_Subtract );
71087       assert( TK_REM==OP_Remainder );
71088       assert( TK_BITAND==OP_BitAnd );
71089       assert( TK_BITOR==OP_BitOr );
71090       assert( TK_SLASH==OP_Divide );
71091       assert( TK_LSHIFT==OP_ShiftLeft );
71092       assert( TK_RSHIFT==OP_ShiftRight );
71093       assert( TK_CONCAT==OP_Concat );
71094       testcase( op==TK_AND );
71095       testcase( op==TK_OR );
71096       testcase( op==TK_PLUS );
71097       testcase( op==TK_MINUS );
71098       testcase( op==TK_REM );
71099       testcase( op==TK_BITAND );
71100       testcase( op==TK_BITOR );
71101       testcase( op==TK_SLASH );
71102       testcase( op==TK_LSHIFT );
71103       testcase( op==TK_RSHIFT );
71104       testcase( op==TK_CONCAT );
71105       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71106       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71107       sqlite3VdbeAddOp3(v, op, r2, r1, target);
71108       testcase( regFree1==0 );
71109       testcase( regFree2==0 );
71110       break;
71111     }
71112     case TK_UMINUS: {
71113       Expr *pLeft = pExpr->pLeft;
71114       assert( pLeft );
71115       if( pLeft->op==TK_INTEGER ){
71116         codeInteger(pParse, pLeft, 1, target);
71117 #ifndef SQLITE_OMIT_FLOATING_POINT
71118       }else if( pLeft->op==TK_FLOAT ){
71119         assert( !ExprHasProperty(pExpr, EP_IntValue) );
71120         codeReal(v, pLeft->u.zToken, 1, target);
71121 #endif
71122       }else{
71123         regFree1 = r1 = sqlite3GetTempReg(pParse);
71124         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
71125         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
71126         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
71127         testcase( regFree2==0 );
71128       }
71129       inReg = target;
71130       break;
71131     }
71132     case TK_BITNOT:
71133     case TK_NOT: {
71134       assert( TK_BITNOT==OP_BitNot );
71135       assert( TK_NOT==OP_Not );
71136       testcase( op==TK_BITNOT );
71137       testcase( op==TK_NOT );
71138       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71139       testcase( regFree1==0 );
71140       inReg = target;
71141       sqlite3VdbeAddOp2(v, op, r1, inReg);
71142       break;
71143     }
71144     case TK_ISNULL:
71145     case TK_NOTNULL: {
71146       int addr;
71147       assert( TK_ISNULL==OP_IsNull );
71148       assert( TK_NOTNULL==OP_NotNull );
71149       testcase( op==TK_ISNULL );
71150       testcase( op==TK_NOTNULL );
71151       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
71152       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71153       testcase( regFree1==0 );
71154       addr = sqlite3VdbeAddOp1(v, op, r1);
71155       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
71156       sqlite3VdbeJumpHere(v, addr);
71157       break;
71158     }
71159     case TK_AGG_FUNCTION: {
71160       AggInfo *pInfo = pExpr->pAggInfo;
71161       if( pInfo==0 ){
71162         assert( !ExprHasProperty(pExpr, EP_IntValue) );
71163         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
71164       }else{
71165         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
71166       }
71167       break;
71168     }
71169     case TK_CONST_FUNC:
71170     case TK_FUNCTION: {
71171       ExprList *pFarg;       /* List of function arguments */
71172       int nFarg;             /* Number of function arguments */
71173       FuncDef *pDef;         /* The function definition object */
71174       int nId;               /* Length of the function name in bytes */
71175       const char *zId;       /* The function name */
71176       int constMask = 0;     /* Mask of function arguments that are constant */
71177       int i;                 /* Loop counter */
71178       u8 enc = ENC(db);      /* The text encoding used by this database */
71179       CollSeq *pColl = 0;    /* A collating sequence */
71180
71181       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
71182       testcase( op==TK_CONST_FUNC );
71183       testcase( op==TK_FUNCTION );
71184       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
71185         pFarg = 0;
71186       }else{
71187         pFarg = pExpr->x.pList;
71188       }
71189       nFarg = pFarg ? pFarg->nExpr : 0;
71190       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71191       zId = pExpr->u.zToken;
71192       nId = sqlite3Strlen30(zId);
71193       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
71194       if( pDef==0 ){
71195         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
71196         break;
71197       }
71198
71199       /* Attempt a direct implementation of the built-in COALESCE() and
71200       ** IFNULL() functions.  This avoids unnecessary evalation of
71201       ** arguments past the first non-NULL argument.
71202       */
71203       if( pDef->flags & SQLITE_FUNC_COALESCE ){
71204         int endCoalesce = sqlite3VdbeMakeLabel(v);
71205         assert( nFarg>=2 );
71206         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
71207         for(i=1; i<nFarg; i++){
71208           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
71209           sqlite3ExprCacheRemove(pParse, target, 1);
71210           sqlite3ExprCachePush(pParse);
71211           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
71212           sqlite3ExprCachePop(pParse, 1);
71213         }
71214         sqlite3VdbeResolveLabel(v, endCoalesce);
71215         break;
71216       }
71217
71218
71219       if( pFarg ){
71220         r1 = sqlite3GetTempRange(pParse, nFarg);
71221         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
71222         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
71223         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
71224       }else{
71225         r1 = 0;
71226       }
71227 #ifndef SQLITE_OMIT_VIRTUALTABLE
71228       /* Possibly overload the function if the first argument is
71229       ** a virtual table column.
71230       **
71231       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
71232       ** second argument, not the first, as the argument to test to
71233       ** see if it is a column in a virtual table.  This is done because
71234       ** the left operand of infix functions (the operand we want to
71235       ** control overloading) ends up as the second argument to the
71236       ** function.  The expression "A glob B" is equivalent to 
71237       ** "glob(B,A).  We want to use the A in "A glob B" to test
71238       ** for function overloading.  But we use the B term in "glob(B,A)".
71239       */
71240       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
71241         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
71242       }else if( nFarg>0 ){
71243         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
71244       }
71245 #endif
71246       for(i=0; i<nFarg; i++){
71247         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
71248           constMask |= (1<<i);
71249         }
71250         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
71251           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
71252         }
71253       }
71254       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
71255         if( !pColl ) pColl = db->pDfltColl; 
71256         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
71257       }
71258       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
71259                         (char*)pDef, P4_FUNCDEF);
71260       sqlite3VdbeChangeP5(v, (u8)nFarg);
71261       if( nFarg ){
71262         sqlite3ReleaseTempRange(pParse, r1, nFarg);
71263       }
71264       break;
71265     }
71266 #ifndef SQLITE_OMIT_SUBQUERY
71267     case TK_EXISTS:
71268     case TK_SELECT: {
71269       testcase( op==TK_EXISTS );
71270       testcase( op==TK_SELECT );
71271       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
71272       break;
71273     }
71274     case TK_IN: {
71275       int destIfFalse = sqlite3VdbeMakeLabel(v);
71276       int destIfNull = sqlite3VdbeMakeLabel(v);
71277       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
71278       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
71279       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
71280       sqlite3VdbeResolveLabel(v, destIfFalse);
71281       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
71282       sqlite3VdbeResolveLabel(v, destIfNull);
71283       break;
71284     }
71285 #endif /* SQLITE_OMIT_SUBQUERY */
71286
71287
71288     /*
71289     **    x BETWEEN y AND z
71290     **
71291     ** This is equivalent to
71292     **
71293     **    x>=y AND x<=z
71294     **
71295     ** X is stored in pExpr->pLeft.
71296     ** Y is stored in pExpr->pList->a[0].pExpr.
71297     ** Z is stored in pExpr->pList->a[1].pExpr.
71298     */
71299     case TK_BETWEEN: {
71300       Expr *pLeft = pExpr->pLeft;
71301       struct ExprList_item *pLItem = pExpr->x.pList->a;
71302       Expr *pRight = pLItem->pExpr;
71303
71304       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
71305       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
71306       testcase( regFree1==0 );
71307       testcase( regFree2==0 );
71308       r3 = sqlite3GetTempReg(pParse);
71309       r4 = sqlite3GetTempReg(pParse);
71310       codeCompare(pParse, pLeft, pRight, OP_Ge,
71311                   r1, r2, r3, SQLITE_STOREP2);
71312       pLItem++;
71313       pRight = pLItem->pExpr;
71314       sqlite3ReleaseTempReg(pParse, regFree2);
71315       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
71316       testcase( regFree2==0 );
71317       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
71318       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
71319       sqlite3ReleaseTempReg(pParse, r3);
71320       sqlite3ReleaseTempReg(pParse, r4);
71321       break;
71322     }
71323     case TK_UPLUS: {
71324       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
71325       break;
71326     }
71327
71328     case TK_TRIGGER: {
71329       /* If the opcode is TK_TRIGGER, then the expression is a reference
71330       ** to a column in the new.* or old.* pseudo-tables available to
71331       ** trigger programs. In this case Expr.iTable is set to 1 for the
71332       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
71333       ** is set to the column of the pseudo-table to read, or to -1 to
71334       ** read the rowid field.
71335       **
71336       ** The expression is implemented using an OP_Param opcode. The p1
71337       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
71338       ** to reference another column of the old.* pseudo-table, where 
71339       ** i is the index of the column. For a new.rowid reference, p1 is
71340       ** set to (n+1), where n is the number of columns in each pseudo-table.
71341       ** For a reference to any other column in the new.* pseudo-table, p1
71342       ** is set to (n+2+i), where n and i are as defined previously. For
71343       ** example, if the table on which triggers are being fired is
71344       ** declared as:
71345       **
71346       **   CREATE TABLE t1(a, b);
71347       **
71348       ** Then p1 is interpreted as follows:
71349       **
71350       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
71351       **   p1==1   ->    old.a         p1==4   ->    new.a
71352       **   p1==2   ->    old.b         p1==5   ->    new.b       
71353       */
71354       Table *pTab = pExpr->pTab;
71355       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
71356
71357       assert( pExpr->iTable==0 || pExpr->iTable==1 );
71358       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
71359       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
71360       assert( p1>=0 && p1<(pTab->nCol*2+2) );
71361
71362       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
71363       VdbeComment((v, "%s.%s -> $%d",
71364         (pExpr->iTable ? "new" : "old"),
71365         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
71366         target
71367       ));
71368
71369 #ifndef SQLITE_OMIT_FLOATING_POINT
71370       /* If the column has REAL affinity, it may currently be stored as an
71371       ** integer. Use OP_RealAffinity to make sure it is really real.  */
71372       if( pExpr->iColumn>=0 
71373        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
71374       ){
71375         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
71376       }
71377 #endif
71378       break;
71379     }
71380
71381
71382     /*
71383     ** Form A:
71384     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
71385     **
71386     ** Form B:
71387     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
71388     **
71389     ** Form A is can be transformed into the equivalent form B as follows:
71390     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
71391     **        WHEN x=eN THEN rN ELSE y END
71392     **
71393     ** X (if it exists) is in pExpr->pLeft.
71394     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
71395     ** ELSE clause and no other term matches, then the result of the
71396     ** exprssion is NULL.
71397     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
71398     **
71399     ** The result of the expression is the Ri for the first matching Ei,
71400     ** or if there is no matching Ei, the ELSE term Y, or if there is
71401     ** no ELSE term, NULL.
71402     */
71403     default: assert( op==TK_CASE ); {
71404       int endLabel;                     /* GOTO label for end of CASE stmt */
71405       int nextCase;                     /* GOTO label for next WHEN clause */
71406       int nExpr;                        /* 2x number of WHEN terms */
71407       int i;                            /* Loop counter */
71408       ExprList *pEList;                 /* List of WHEN terms */
71409       struct ExprList_item *aListelem;  /* Array of WHEN terms */
71410       Expr opCompare;                   /* The X==Ei expression */
71411       Expr cacheX;                      /* Cached expression X */
71412       Expr *pX;                         /* The X expression */
71413       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
71414       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
71415
71416       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
71417       assert((pExpr->x.pList->nExpr % 2) == 0);
71418       assert(pExpr->x.pList->nExpr > 0);
71419       pEList = pExpr->x.pList;
71420       aListelem = pEList->a;
71421       nExpr = pEList->nExpr;
71422       endLabel = sqlite3VdbeMakeLabel(v);
71423       if( (pX = pExpr->pLeft)!=0 ){
71424         cacheX = *pX;
71425         testcase( pX->op==TK_COLUMN );
71426         testcase( pX->op==TK_REGISTER );
71427         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
71428         testcase( regFree1==0 );
71429         cacheX.op = TK_REGISTER;
71430         opCompare.op = TK_EQ;
71431         opCompare.pLeft = &cacheX;
71432         pTest = &opCompare;
71433         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
71434         ** The value in regFree1 might get SCopy-ed into the file result.
71435         ** So make sure that the regFree1 register is not reused for other
71436         ** purposes and possibly overwritten.  */
71437         regFree1 = 0;
71438       }
71439       for(i=0; i<nExpr; i=i+2){
71440         sqlite3ExprCachePush(pParse);
71441         if( pX ){
71442           assert( pTest!=0 );
71443           opCompare.pRight = aListelem[i].pExpr;
71444         }else{
71445           pTest = aListelem[i].pExpr;
71446         }
71447         nextCase = sqlite3VdbeMakeLabel(v);
71448         testcase( pTest->op==TK_COLUMN );
71449         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
71450         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
71451         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
71452         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
71453         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
71454         sqlite3ExprCachePop(pParse, 1);
71455         sqlite3VdbeResolveLabel(v, nextCase);
71456       }
71457       if( pExpr->pRight ){
71458         sqlite3ExprCachePush(pParse);
71459         sqlite3ExprCode(pParse, pExpr->pRight, target);
71460         sqlite3ExprCachePop(pParse, 1);
71461       }else{
71462         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
71463       }
71464       assert( db->mallocFailed || pParse->nErr>0 
71465            || pParse->iCacheLevel==iCacheLevel );
71466       sqlite3VdbeResolveLabel(v, endLabel);
71467       break;
71468     }
71469 #ifndef SQLITE_OMIT_TRIGGER
71470     case TK_RAISE: {
71471       assert( pExpr->affinity==OE_Rollback 
71472            || pExpr->affinity==OE_Abort
71473            || pExpr->affinity==OE_Fail
71474            || pExpr->affinity==OE_Ignore
71475       );
71476       if( !pParse->pTriggerTab ){
71477         sqlite3ErrorMsg(pParse,
71478                        "RAISE() may only be used within a trigger-program");
71479         return 0;
71480       }
71481       if( pExpr->affinity==OE_Abort ){
71482         sqlite3MayAbort(pParse);
71483       }
71484       assert( !ExprHasProperty(pExpr, EP_IntValue) );
71485       if( pExpr->affinity==OE_Ignore ){
71486         sqlite3VdbeAddOp4(
71487             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
71488       }else{
71489         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
71490       }
71491
71492       break;
71493     }
71494 #endif
71495   }
71496   sqlite3ReleaseTempReg(pParse, regFree1);
71497   sqlite3ReleaseTempReg(pParse, regFree2);
71498   return inReg;
71499 }
71500
71501 /*
71502 ** Generate code to evaluate an expression and store the results
71503 ** into a register.  Return the register number where the results
71504 ** are stored.
71505 **
71506 ** If the register is a temporary register that can be deallocated,
71507 ** then write its number into *pReg.  If the result register is not
71508 ** a temporary, then set *pReg to zero.
71509 */
71510 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
71511   int r1 = sqlite3GetTempReg(pParse);
71512   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
71513   if( r2==r1 ){
71514     *pReg = r1;
71515   }else{
71516     sqlite3ReleaseTempReg(pParse, r1);
71517     *pReg = 0;
71518   }
71519   return r2;
71520 }
71521
71522 /*
71523 ** Generate code that will evaluate expression pExpr and store the
71524 ** results in register target.  The results are guaranteed to appear
71525 ** in register target.
71526 */
71527 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
71528   int inReg;
71529
71530   assert( target>0 && target<=pParse->nMem );
71531   if( pExpr && pExpr->op==TK_REGISTER ){
71532     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
71533   }else{
71534     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
71535     assert( pParse->pVdbe || pParse->db->mallocFailed );
71536     if( inReg!=target && pParse->pVdbe ){
71537       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
71538     }
71539   }
71540   return target;
71541 }
71542
71543 /*
71544 ** Generate code that evalutes the given expression and puts the result
71545 ** in register target.
71546 **
71547 ** Also make a copy of the expression results into another "cache" register
71548 ** and modify the expression so that the next time it is evaluated,
71549 ** the result is a copy of the cache register.
71550 **
71551 ** This routine is used for expressions that are used multiple 
71552 ** times.  They are evaluated once and the results of the expression
71553 ** are reused.
71554 */
71555 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
71556   Vdbe *v = pParse->pVdbe;
71557   int inReg;
71558   inReg = sqlite3ExprCode(pParse, pExpr, target);
71559   assert( target>0 );
71560   /* This routine is called for terms to INSERT or UPDATE.  And the only
71561   ** other place where expressions can be converted into TK_REGISTER is
71562   ** in WHERE clause processing.  So as currently implemented, there is
71563   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
71564   ** keep the ALWAYS() in case the conditions above change with future
71565   ** modifications or enhancements. */
71566   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
71567     int iMem;
71568     iMem = ++pParse->nMem;
71569     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
71570     pExpr->iTable = iMem;
71571     pExpr->op2 = pExpr->op;
71572     pExpr->op = TK_REGISTER;
71573   }
71574   return inReg;
71575 }
71576
71577 /*
71578 ** Return TRUE if pExpr is an constant expression that is appropriate
71579 ** for factoring out of a loop.  Appropriate expressions are:
71580 **
71581 **    *  Any expression that evaluates to two or more opcodes.
71582 **
71583 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
71584 **       or OP_Variable that does not need to be placed in a 
71585 **       specific register.
71586 **
71587 ** There is no point in factoring out single-instruction constant
71588 ** expressions that need to be placed in a particular register.  
71589 ** We could factor them out, but then we would end up adding an
71590 ** OP_SCopy instruction to move the value into the correct register
71591 ** later.  We might as well just use the original instruction and
71592 ** avoid the OP_SCopy.
71593 */
71594 static int isAppropriateForFactoring(Expr *p){
71595   if( !sqlite3ExprIsConstantNotJoin(p) ){
71596     return 0;  /* Only constant expressions are appropriate for factoring */
71597   }
71598   if( (p->flags & EP_FixedDest)==0 ){
71599     return 1;  /* Any constant without a fixed destination is appropriate */
71600   }
71601   while( p->op==TK_UPLUS ) p = p->pLeft;
71602   switch( p->op ){
71603 #ifndef SQLITE_OMIT_BLOB_LITERAL
71604     case TK_BLOB:
71605 #endif
71606     case TK_VARIABLE:
71607     case TK_INTEGER:
71608     case TK_FLOAT:
71609     case TK_NULL:
71610     case TK_STRING: {
71611       testcase( p->op==TK_BLOB );
71612       testcase( p->op==TK_VARIABLE );
71613       testcase( p->op==TK_INTEGER );
71614       testcase( p->op==TK_FLOAT );
71615       testcase( p->op==TK_NULL );
71616       testcase( p->op==TK_STRING );
71617       /* Single-instruction constants with a fixed destination are
71618       ** better done in-line.  If we factor them, they will just end
71619       ** up generating an OP_SCopy to move the value to the destination
71620       ** register. */
71621       return 0;
71622     }
71623     case TK_UMINUS: {
71624       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
71625         return 0;
71626       }
71627       break;
71628     }
71629     default: {
71630       break;
71631     }
71632   }
71633   return 1;
71634 }
71635
71636 /*
71637 ** If pExpr is a constant expression that is appropriate for
71638 ** factoring out of a loop, then evaluate the expression
71639 ** into a register and convert the expression into a TK_REGISTER
71640 ** expression.
71641 */
71642 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
71643   Parse *pParse = pWalker->pParse;
71644   switch( pExpr->op ){
71645     case TK_IN:
71646     case TK_REGISTER: {
71647       return WRC_Prune;
71648     }
71649     case TK_FUNCTION:
71650     case TK_AGG_FUNCTION:
71651     case TK_CONST_FUNC: {
71652       /* The arguments to a function have a fixed destination.
71653       ** Mark them this way to avoid generated unneeded OP_SCopy
71654       ** instructions. 
71655       */
71656       ExprList *pList = pExpr->x.pList;
71657       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
71658       if( pList ){
71659         int i = pList->nExpr;
71660         struct ExprList_item *pItem = pList->a;
71661         for(; i>0; i--, pItem++){
71662           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
71663         }
71664       }
71665       break;
71666     }
71667   }
71668   if( isAppropriateForFactoring(pExpr) ){
71669     int r1 = ++pParse->nMem;
71670     int r2;
71671     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
71672     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
71673     pExpr->op2 = pExpr->op;
71674     pExpr->op = TK_REGISTER;
71675     pExpr->iTable = r2;
71676     return WRC_Prune;
71677   }
71678   return WRC_Continue;
71679 }
71680
71681 /*
71682 ** Preevaluate constant subexpressions within pExpr and store the
71683 ** results in registers.  Modify pExpr so that the constant subexpresions
71684 ** are TK_REGISTER opcodes that refer to the precomputed values.
71685 **
71686 ** This routine is a no-op if the jump to the cookie-check code has
71687 ** already occur.  Since the cookie-check jump is generated prior to
71688 ** any other serious processing, this check ensures that there is no
71689 ** way to accidently bypass the constant initializations.
71690 **
71691 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
71692 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
71693 ** interface.  This allows test logic to verify that the same answer is
71694 ** obtained for queries regardless of whether or not constants are
71695 ** precomputed into registers or if they are inserted in-line.
71696 */
71697 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
71698   Walker w;
71699   if( pParse->cookieGoto ) return;
71700   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
71701   w.xExprCallback = evalConstExpr;
71702   w.xSelectCallback = 0;
71703   w.pParse = pParse;
71704   sqlite3WalkExpr(&w, pExpr);
71705 }
71706
71707
71708 /*
71709 ** Generate code that pushes the value of every element of the given
71710 ** expression list into a sequence of registers beginning at target.
71711 **
71712 ** Return the number of elements evaluated.
71713 */
71714 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
71715   Parse *pParse,     /* Parsing context */
71716   ExprList *pList,   /* The expression list to be coded */
71717   int target,        /* Where to write results */
71718   int doHardCopy     /* Make a hard copy of every element */
71719 ){
71720   struct ExprList_item *pItem;
71721   int i, n;
71722   assert( pList!=0 );
71723   assert( target>0 );
71724   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
71725   n = pList->nExpr;
71726   for(pItem=pList->a, i=0; i<n; i++, pItem++){
71727     Expr *pExpr = pItem->pExpr;
71728     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
71729     if( inReg!=target+i ){
71730       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
71731                         inReg, target+i);
71732     }
71733   }
71734   return n;
71735 }
71736
71737 /*
71738 ** Generate code for a BETWEEN operator.
71739 **
71740 **    x BETWEEN y AND z
71741 **
71742 ** The above is equivalent to 
71743 **
71744 **    x>=y AND x<=z
71745 **
71746 ** Code it as such, taking care to do the common subexpression
71747 ** elementation of x.
71748 */
71749 static void exprCodeBetween(
71750   Parse *pParse,    /* Parsing and code generating context */
71751   Expr *pExpr,      /* The BETWEEN expression */
71752   int dest,         /* Jump here if the jump is taken */
71753   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
71754   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
71755 ){
71756   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
71757   Expr compLeft;    /* The  x>=y  term */
71758   Expr compRight;   /* The  x<=z  term */
71759   Expr exprX;       /* The  x  subexpression */
71760   int regFree1 = 0; /* Temporary use register */
71761
71762   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
71763   exprX = *pExpr->pLeft;
71764   exprAnd.op = TK_AND;
71765   exprAnd.pLeft = &compLeft;
71766   exprAnd.pRight = &compRight;
71767   compLeft.op = TK_GE;
71768   compLeft.pLeft = &exprX;
71769   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
71770   compRight.op = TK_LE;
71771   compRight.pLeft = &exprX;
71772   compRight.pRight = pExpr->x.pList->a[1].pExpr;
71773   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
71774   exprX.op = TK_REGISTER;
71775   if( jumpIfTrue ){
71776     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
71777   }else{
71778     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
71779   }
71780   sqlite3ReleaseTempReg(pParse, regFree1);
71781
71782   /* Ensure adequate test coverage */
71783   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
71784   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
71785   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
71786   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
71787   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
71788   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
71789   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
71790   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
71791 }
71792
71793 /*
71794 ** Generate code for a boolean expression such that a jump is made
71795 ** to the label "dest" if the expression is true but execution
71796 ** continues straight thru if the expression is false.
71797 **
71798 ** If the expression evaluates to NULL (neither true nor false), then
71799 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
71800 **
71801 ** This code depends on the fact that certain token values (ex: TK_EQ)
71802 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
71803 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
71804 ** the make process cause these values to align.  Assert()s in the code
71805 ** below verify that the numbers are aligned correctly.
71806 */
71807 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
71808   Vdbe *v = pParse->pVdbe;
71809   int op = 0;
71810   int regFree1 = 0;
71811   int regFree2 = 0;
71812   int r1, r2;
71813
71814   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
71815   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
71816   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
71817   op = pExpr->op;
71818   switch( op ){
71819     case TK_AND: {
71820       int d2 = sqlite3VdbeMakeLabel(v);
71821       testcase( jumpIfNull==0 );
71822       sqlite3ExprCachePush(pParse);
71823       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
71824       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
71825       sqlite3VdbeResolveLabel(v, d2);
71826       sqlite3ExprCachePop(pParse, 1);
71827       break;
71828     }
71829     case TK_OR: {
71830       testcase( jumpIfNull==0 );
71831       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
71832       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
71833       break;
71834     }
71835     case TK_NOT: {
71836       testcase( jumpIfNull==0 );
71837       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
71838       break;
71839     }
71840     case TK_LT:
71841     case TK_LE:
71842     case TK_GT:
71843     case TK_GE:
71844     case TK_NE:
71845     case TK_EQ: {
71846       assert( TK_LT==OP_Lt );
71847       assert( TK_LE==OP_Le );
71848       assert( TK_GT==OP_Gt );
71849       assert( TK_GE==OP_Ge );
71850       assert( TK_EQ==OP_Eq );
71851       assert( TK_NE==OP_Ne );
71852       testcase( op==TK_LT );
71853       testcase( op==TK_LE );
71854       testcase( op==TK_GT );
71855       testcase( op==TK_GE );
71856       testcase( op==TK_EQ );
71857       testcase( op==TK_NE );
71858       testcase( jumpIfNull==0 );
71859       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71860       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71861       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71862                   r1, r2, dest, jumpIfNull);
71863       testcase( regFree1==0 );
71864       testcase( regFree2==0 );
71865       break;
71866     }
71867     case TK_IS:
71868     case TK_ISNOT: {
71869       testcase( op==TK_IS );
71870       testcase( op==TK_ISNOT );
71871       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71872       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
71873       op = (op==TK_IS) ? TK_EQ : TK_NE;
71874       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
71875                   r1, r2, dest, SQLITE_NULLEQ);
71876       testcase( regFree1==0 );
71877       testcase( regFree2==0 );
71878       break;
71879     }
71880     case TK_ISNULL:
71881     case TK_NOTNULL: {
71882       assert( TK_ISNULL==OP_IsNull );
71883       assert( TK_NOTNULL==OP_NotNull );
71884       testcase( op==TK_ISNULL );
71885       testcase( op==TK_NOTNULL );
71886       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
71887       sqlite3VdbeAddOp2(v, op, r1, dest);
71888       testcase( regFree1==0 );
71889       break;
71890     }
71891     case TK_BETWEEN: {
71892       testcase( jumpIfNull==0 );
71893       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
71894       break;
71895     }
71896     case TK_IN: {
71897       int destIfFalse = sqlite3VdbeMakeLabel(v);
71898       int destIfNull = jumpIfNull ? dest : destIfFalse;
71899       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
71900       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
71901       sqlite3VdbeResolveLabel(v, destIfFalse);
71902       break;
71903     }
71904     default: {
71905       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
71906       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
71907       testcase( regFree1==0 );
71908       testcase( jumpIfNull==0 );
71909       break;
71910     }
71911   }
71912   sqlite3ReleaseTempReg(pParse, regFree1);
71913   sqlite3ReleaseTempReg(pParse, regFree2);  
71914 }
71915
71916 /*
71917 ** Generate code for a boolean expression such that a jump is made
71918 ** to the label "dest" if the expression is false but execution
71919 ** continues straight thru if the expression is true.
71920 **
71921 ** If the expression evaluates to NULL (neither true nor false) then
71922 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
71923 ** is 0.
71924 */
71925 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
71926   Vdbe *v = pParse->pVdbe;
71927   int op = 0;
71928   int regFree1 = 0;
71929   int regFree2 = 0;
71930   int r1, r2;
71931
71932   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
71933   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
71934   if( pExpr==0 )    return;
71935
71936   /* The value of pExpr->op and op are related as follows:
71937   **
71938   **       pExpr->op            op
71939   **       ---------          ----------
71940   **       TK_ISNULL          OP_NotNull
71941   **       TK_NOTNULL         OP_IsNull
71942   **       TK_NE              OP_Eq
71943   **       TK_EQ              OP_Ne
71944   **       TK_GT              OP_Le
71945   **       TK_LE              OP_Gt
71946   **       TK_GE              OP_Lt
71947   **       TK_LT              OP_Ge
71948   **
71949   ** For other values of pExpr->op, op is undefined and unused.
71950   ** The value of TK_ and OP_ constants are arranged such that we
71951   ** can compute the mapping above using the following expression.
71952   ** Assert()s verify that the computation is correct.
71953   */
71954   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
71955
71956   /* Verify correct alignment of TK_ and OP_ constants
71957   */
71958   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
71959   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
71960   assert( pExpr->op!=TK_NE || op==OP_Eq );
71961   assert( pExpr->op!=TK_EQ || op==OP_Ne );
71962   assert( pExpr->op!=TK_LT || op==OP_Ge );
71963   assert( pExpr->op!=TK_LE || op==OP_Gt );
71964   assert( pExpr->op!=TK_GT || op==OP_Le );
71965   assert( pExpr->op!=TK_GE || op==OP_Lt );
71966
71967   switch( pExpr->op ){
71968     case TK_AND: {
71969       testcase( jumpIfNull==0 );
71970       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
71971       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
71972       break;
71973     }
71974     case TK_OR: {
71975       int d2 = sqlite3VdbeMakeLabel(v);
71976       testcase( jumpIfNull==0 );
71977       sqlite3ExprCachePush(pParse);
71978       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
71979       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
71980       sqlite3VdbeResolveLabel(v, d2);
71981       sqlite3ExprCachePop(pParse, 1);
71982       break;
71983     }
71984     case TK_NOT: {
71985       testcase( jumpIfNull==0 );
71986       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
71987       break;
71988     }
71989     case TK_LT:
71990     case TK_LE:
71991     case TK_GT:
71992     case TK_GE:
71993     case TK_NE:
71994     case TK_EQ: {
71995       testcase( op==TK_LT );
71996       testcase( op==TK_LE );
71997       testcase( op==TK_GT );
71998       testcase( op==TK_GE );
71999       testcase( op==TK_EQ );
72000       testcase( op==TK_NE );
72001       testcase( jumpIfNull==0 );
72002       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
72003       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
72004       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
72005                   r1, r2, dest, jumpIfNull);
72006       testcase( regFree1==0 );
72007       testcase( regFree2==0 );
72008       break;
72009     }
72010     case TK_IS:
72011     case TK_ISNOT: {
72012       testcase( pExpr->op==TK_IS );
72013       testcase( pExpr->op==TK_ISNOT );
72014       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
72015       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
72016       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
72017       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
72018                   r1, r2, dest, SQLITE_NULLEQ);
72019       testcase( regFree1==0 );
72020       testcase( regFree2==0 );
72021       break;
72022     }
72023     case TK_ISNULL:
72024     case TK_NOTNULL: {
72025       testcase( op==TK_ISNULL );
72026       testcase( op==TK_NOTNULL );
72027       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
72028       sqlite3VdbeAddOp2(v, op, r1, dest);
72029       testcase( regFree1==0 );
72030       break;
72031     }
72032     case TK_BETWEEN: {
72033       testcase( jumpIfNull==0 );
72034       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
72035       break;
72036     }
72037     case TK_IN: {
72038       if( jumpIfNull ){
72039         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
72040       }else{
72041         int destIfNull = sqlite3VdbeMakeLabel(v);
72042         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
72043         sqlite3VdbeResolveLabel(v, destIfNull);
72044       }
72045       break;
72046     }
72047     default: {
72048       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
72049       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
72050       testcase( regFree1==0 );
72051       testcase( jumpIfNull==0 );
72052       break;
72053     }
72054   }
72055   sqlite3ReleaseTempReg(pParse, regFree1);
72056   sqlite3ReleaseTempReg(pParse, regFree2);
72057 }
72058
72059 /*
72060 ** Do a deep comparison of two expression trees.  Return 0 if the two
72061 ** expressions are completely identical.  Return 1 if they differ only
72062 ** by a COLLATE operator at the top level.  Return 2 if there are differences
72063 ** other than the top-level COLLATE operator.
72064 **
72065 ** Sometimes this routine will return 2 even if the two expressions
72066 ** really are equivalent.  If we cannot prove that the expressions are
72067 ** identical, we return 2 just to be safe.  So if this routine
72068 ** returns 2, then you do not really know for certain if the two
72069 ** expressions are the same.  But if you get a 0 or 1 return, then you
72070 ** can be sure the expressions are the same.  In the places where
72071 ** this routine is used, it does not hurt to get an extra 2 - that
72072 ** just might result in some slightly slower code.  But returning
72073 ** an incorrect 0 or 1 could lead to a malfunction.
72074 */
72075 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
72076   if( pA==0||pB==0 ){
72077     return pB==pA ? 0 : 2;
72078   }
72079   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
72080   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
72081   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
72082     return 2;
72083   }
72084   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
72085   if( pA->op!=pB->op ) return 2;
72086   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
72087   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
72088   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
72089   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
72090   if( ExprHasProperty(pA, EP_IntValue) ){
72091     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
72092       return 2;
72093     }
72094   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
72095     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
72096     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
72097       return 2;
72098     }
72099   }
72100   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
72101   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
72102   return 0;
72103 }
72104
72105 /*
72106 ** Compare two ExprList objects.  Return 0 if they are identical and 
72107 ** non-zero if they differ in any way.
72108 **
72109 ** This routine might return non-zero for equivalent ExprLists.  The
72110 ** only consequence will be disabled optimizations.  But this routine
72111 ** must never return 0 if the two ExprList objects are different, or
72112 ** a malfunction will result.
72113 **
72114 ** Two NULL pointers are considered to be the same.  But a NULL pointer
72115 ** always differs from a non-NULL pointer.
72116 */
72117 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
72118   int i;
72119   if( pA==0 && pB==0 ) return 0;
72120   if( pA==0 || pB==0 ) return 1;
72121   if( pA->nExpr!=pB->nExpr ) return 1;
72122   for(i=0; i<pA->nExpr; i++){
72123     Expr *pExprA = pA->a[i].pExpr;
72124     Expr *pExprB = pB->a[i].pExpr;
72125     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
72126     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
72127   }
72128   return 0;
72129 }
72130
72131 /*
72132 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
72133 ** the new element.  Return a negative number if malloc fails.
72134 */
72135 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
72136   int i;
72137   pInfo->aCol = sqlite3ArrayAllocate(
72138        db,
72139        pInfo->aCol,
72140        sizeof(pInfo->aCol[0]),
72141        3,
72142        &pInfo->nColumn,
72143        &pInfo->nColumnAlloc,
72144        &i
72145   );
72146   return i;
72147 }    
72148
72149 /*
72150 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
72151 ** the new element.  Return a negative number if malloc fails.
72152 */
72153 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
72154   int i;
72155   pInfo->aFunc = sqlite3ArrayAllocate(
72156        db, 
72157        pInfo->aFunc,
72158        sizeof(pInfo->aFunc[0]),
72159        3,
72160        &pInfo->nFunc,
72161        &pInfo->nFuncAlloc,
72162        &i
72163   );
72164   return i;
72165 }    
72166
72167 /*
72168 ** This is the xExprCallback for a tree walker.  It is used to
72169 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
72170 ** for additional information.
72171 */
72172 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
72173   int i;
72174   NameContext *pNC = pWalker->u.pNC;
72175   Parse *pParse = pNC->pParse;
72176   SrcList *pSrcList = pNC->pSrcList;
72177   AggInfo *pAggInfo = pNC->pAggInfo;
72178
72179   switch( pExpr->op ){
72180     case TK_AGG_COLUMN:
72181     case TK_COLUMN: {
72182       testcase( pExpr->op==TK_AGG_COLUMN );
72183       testcase( pExpr->op==TK_COLUMN );
72184       /* Check to see if the column is in one of the tables in the FROM
72185       ** clause of the aggregate query */
72186       if( ALWAYS(pSrcList!=0) ){
72187         struct SrcList_item *pItem = pSrcList->a;
72188         for(i=0; i<pSrcList->nSrc; i++, pItem++){
72189           struct AggInfo_col *pCol;
72190           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
72191           if( pExpr->iTable==pItem->iCursor ){
72192             /* If we reach this point, it means that pExpr refers to a table
72193             ** that is in the FROM clause of the aggregate query.  
72194             **
72195             ** Make an entry for the column in pAggInfo->aCol[] if there
72196             ** is not an entry there already.
72197             */
72198             int k;
72199             pCol = pAggInfo->aCol;
72200             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
72201               if( pCol->iTable==pExpr->iTable &&
72202                   pCol->iColumn==pExpr->iColumn ){
72203                 break;
72204               }
72205             }
72206             if( (k>=pAggInfo->nColumn)
72207              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
72208             ){
72209               pCol = &pAggInfo->aCol[k];
72210               pCol->pTab = pExpr->pTab;
72211               pCol->iTable = pExpr->iTable;
72212               pCol->iColumn = pExpr->iColumn;
72213               pCol->iMem = ++pParse->nMem;
72214               pCol->iSorterColumn = -1;
72215               pCol->pExpr = pExpr;
72216               if( pAggInfo->pGroupBy ){
72217                 int j, n;
72218                 ExprList *pGB = pAggInfo->pGroupBy;
72219                 struct ExprList_item *pTerm = pGB->a;
72220                 n = pGB->nExpr;
72221                 for(j=0; j<n; j++, pTerm++){
72222                   Expr *pE = pTerm->pExpr;
72223                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
72224                       pE->iColumn==pExpr->iColumn ){
72225                     pCol->iSorterColumn = j;
72226                     break;
72227                   }
72228                 }
72229               }
72230               if( pCol->iSorterColumn<0 ){
72231                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
72232               }
72233             }
72234             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
72235             ** because it was there before or because we just created it).
72236             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
72237             ** pAggInfo->aCol[] entry.
72238             */
72239             ExprSetIrreducible(pExpr);
72240             pExpr->pAggInfo = pAggInfo;
72241             pExpr->op = TK_AGG_COLUMN;
72242             pExpr->iAgg = (i16)k;
72243             break;
72244           } /* endif pExpr->iTable==pItem->iCursor */
72245         } /* end loop over pSrcList */
72246       }
72247       return WRC_Prune;
72248     }
72249     case TK_AGG_FUNCTION: {
72250       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
72251       ** to be ignored */
72252       if( pNC->nDepth==0 ){
72253         /* Check to see if pExpr is a duplicate of another aggregate 
72254         ** function that is already in the pAggInfo structure
72255         */
72256         struct AggInfo_func *pItem = pAggInfo->aFunc;
72257         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
72258           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
72259             break;
72260           }
72261         }
72262         if( i>=pAggInfo->nFunc ){
72263           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
72264           */
72265           u8 enc = ENC(pParse->db);
72266           i = addAggInfoFunc(pParse->db, pAggInfo);
72267           if( i>=0 ){
72268             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72269             pItem = &pAggInfo->aFunc[i];
72270             pItem->pExpr = pExpr;
72271             pItem->iMem = ++pParse->nMem;
72272             assert( !ExprHasProperty(pExpr, EP_IntValue) );
72273             pItem->pFunc = sqlite3FindFunction(pParse->db,
72274                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
72275                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
72276             if( pExpr->flags & EP_Distinct ){
72277               pItem->iDistinct = pParse->nTab++;
72278             }else{
72279               pItem->iDistinct = -1;
72280             }
72281           }
72282         }
72283         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
72284         */
72285         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
72286         ExprSetIrreducible(pExpr);
72287         pExpr->iAgg = (i16)i;
72288         pExpr->pAggInfo = pAggInfo;
72289         return WRC_Prune;
72290       }
72291     }
72292   }
72293   return WRC_Continue;
72294 }
72295 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
72296   NameContext *pNC = pWalker->u.pNC;
72297   if( pNC->nDepth==0 ){
72298     pNC->nDepth++;
72299     sqlite3WalkSelect(pWalker, pSelect);
72300     pNC->nDepth--;
72301     return WRC_Prune;
72302   }else{
72303     return WRC_Continue;
72304   }
72305 }
72306
72307 /*
72308 ** Analyze the given expression looking for aggregate functions and
72309 ** for variables that need to be added to the pParse->aAgg[] array.
72310 ** Make additional entries to the pParse->aAgg[] array as necessary.
72311 **
72312 ** This routine should only be called after the expression has been
72313 ** analyzed by sqlite3ResolveExprNames().
72314 */
72315 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
72316   Walker w;
72317   w.xExprCallback = analyzeAggregate;
72318   w.xSelectCallback = analyzeAggregatesInSelect;
72319   w.u.pNC = pNC;
72320   assert( pNC->pSrcList!=0 );
72321   sqlite3WalkExpr(&w, pExpr);
72322 }
72323
72324 /*
72325 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
72326 ** expression list.  Return the number of errors.
72327 **
72328 ** If an error is found, the analysis is cut short.
72329 */
72330 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
72331   struct ExprList_item *pItem;
72332   int i;
72333   if( pList ){
72334     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
72335       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
72336     }
72337   }
72338 }
72339
72340 /*
72341 ** Allocate a single new register for use to hold some intermediate result.
72342 */
72343 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
72344   if( pParse->nTempReg==0 ){
72345     return ++pParse->nMem;
72346   }
72347   return pParse->aTempReg[--pParse->nTempReg];
72348 }
72349
72350 /*
72351 ** Deallocate a register, making available for reuse for some other
72352 ** purpose.
72353 **
72354 ** If a register is currently being used by the column cache, then
72355 ** the dallocation is deferred until the column cache line that uses
72356 ** the register becomes stale.
72357 */
72358 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
72359   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
72360     int i;
72361     struct yColCache *p;
72362     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
72363       if( p->iReg==iReg ){
72364         p->tempReg = 1;
72365         return;
72366       }
72367     }
72368     pParse->aTempReg[pParse->nTempReg++] = iReg;
72369   }
72370 }
72371
72372 /*
72373 ** Allocate or deallocate a block of nReg consecutive registers
72374 */
72375 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
72376   int i, n;
72377   i = pParse->iRangeReg;
72378   n = pParse->nRangeReg;
72379   if( nReg<=n ){
72380     assert( !usedAsColumnCache(pParse, i, i+n-1) );
72381     pParse->iRangeReg += nReg;
72382     pParse->nRangeReg -= nReg;
72383   }else{
72384     i = pParse->nMem+1;
72385     pParse->nMem += nReg;
72386   }
72387   return i;
72388 }
72389 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
72390   sqlite3ExprCacheRemove(pParse, iReg, nReg);
72391   if( nReg>pParse->nRangeReg ){
72392     pParse->nRangeReg = nReg;
72393     pParse->iRangeReg = iReg;
72394   }
72395 }
72396
72397 /************** End of expr.c ************************************************/
72398 /************** Begin file alter.c *******************************************/
72399 /*
72400 ** 2005 February 15
72401 **
72402 ** The author disclaims copyright to this source code.  In place of
72403 ** a legal notice, here is a blessing:
72404 **
72405 **    May you do good and not evil.
72406 **    May you find forgiveness for yourself and forgive others.
72407 **    May you share freely, never taking more than you give.
72408 **
72409 *************************************************************************
72410 ** This file contains C code routines that used to generate VDBE code
72411 ** that implements the ALTER TABLE command.
72412 */
72413
72414 /*
72415 ** The code in this file only exists if we are not omitting the
72416 ** ALTER TABLE logic from the build.
72417 */
72418 #ifndef SQLITE_OMIT_ALTERTABLE
72419
72420
72421 /*
72422 ** This function is used by SQL generated to implement the 
72423 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
72424 ** CREATE INDEX command. The second is a table name. The table name in 
72425 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
72426 ** argument and the result returned. Examples:
72427 **
72428 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
72429 **     -> 'CREATE TABLE def(a, b, c)'
72430 **
72431 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
72432 **     -> 'CREATE INDEX i ON def(a, b, c)'
72433 */
72434 static void renameTableFunc(
72435   sqlite3_context *context,
72436   int NotUsed,
72437   sqlite3_value **argv
72438 ){
72439   unsigned char const *zSql = sqlite3_value_text(argv[0]);
72440   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
72441
72442   int token;
72443   Token tname;
72444   unsigned char const *zCsr = zSql;
72445   int len = 0;
72446   char *zRet;
72447
72448   sqlite3 *db = sqlite3_context_db_handle(context);
72449
72450   UNUSED_PARAMETER(NotUsed);
72451
72452   /* The principle used to locate the table name in the CREATE TABLE 
72453   ** statement is that the table name is the first non-space token that
72454   ** is immediately followed by a TK_LP or TK_USING token.
72455   */
72456   if( zSql ){
72457     do {
72458       if( !*zCsr ){
72459         /* Ran out of input before finding an opening bracket. Return NULL. */
72460         return;
72461       }
72462
72463       /* Store the token that zCsr points to in tname. */
72464       tname.z = (char*)zCsr;
72465       tname.n = len;
72466
72467       /* Advance zCsr to the next token. Store that token type in 'token',
72468       ** and its length in 'len' (to be used next iteration of this loop).
72469       */
72470       do {
72471         zCsr += len;
72472         len = sqlite3GetToken(zCsr, &token);
72473       } while( token==TK_SPACE );
72474       assert( len>0 );
72475     } while( token!=TK_LP && token!=TK_USING );
72476
72477     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
72478        zTableName, tname.z+tname.n);
72479     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
72480   }
72481 }
72482
72483 /*
72484 ** This C function implements an SQL user function that is used by SQL code
72485 ** generated by the ALTER TABLE ... RENAME command to modify the definition
72486 ** of any foreign key constraints that use the table being renamed as the 
72487 ** parent table. It is passed three arguments:
72488 **
72489 **   1) The complete text of the CREATE TABLE statement being modified,
72490 **   2) The old name of the table being renamed, and
72491 **   3) The new name of the table being renamed.
72492 **
72493 ** It returns the new CREATE TABLE statement. For example:
72494 **
72495 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
72496 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
72497 */
72498 #ifndef SQLITE_OMIT_FOREIGN_KEY
72499 static void renameParentFunc(
72500   sqlite3_context *context,
72501   int NotUsed,
72502   sqlite3_value **argv
72503 ){
72504   sqlite3 *db = sqlite3_context_db_handle(context);
72505   char *zOutput = 0;
72506   char *zResult;
72507   unsigned char const *zInput = sqlite3_value_text(argv[0]);
72508   unsigned char const *zOld = sqlite3_value_text(argv[1]);
72509   unsigned char const *zNew = sqlite3_value_text(argv[2]);
72510
72511   unsigned const char *z;         /* Pointer to token */
72512   int n;                          /* Length of token z */
72513   int token;                      /* Type of token */
72514
72515   UNUSED_PARAMETER(NotUsed);
72516   for(z=zInput; *z; z=z+n){
72517     n = sqlite3GetToken(z, &token);
72518     if( token==TK_REFERENCES ){
72519       char *zParent;
72520       do {
72521         z += n;
72522         n = sqlite3GetToken(z, &token);
72523       }while( token==TK_SPACE );
72524
72525       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
72526       if( zParent==0 ) break;
72527       sqlite3Dequote(zParent);
72528       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
72529         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
72530             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
72531         );
72532         sqlite3DbFree(db, zOutput);
72533         zOutput = zOut;
72534         zInput = &z[n];
72535       }
72536       sqlite3DbFree(db, zParent);
72537     }
72538   }
72539
72540   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
72541   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
72542   sqlite3DbFree(db, zOutput);
72543 }
72544 #endif
72545
72546 #ifndef SQLITE_OMIT_TRIGGER
72547 /* This function is used by SQL generated to implement the
72548 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
72549 ** statement. The second is a table name. The table name in the CREATE 
72550 ** TRIGGER statement is replaced with the third argument and the result 
72551 ** returned. This is analagous to renameTableFunc() above, except for CREATE
72552 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
72553 */
72554 static void renameTriggerFunc(
72555   sqlite3_context *context,
72556   int NotUsed,
72557   sqlite3_value **argv
72558 ){
72559   unsigned char const *zSql = sqlite3_value_text(argv[0]);
72560   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
72561
72562   int token;
72563   Token tname;
72564   int dist = 3;
72565   unsigned char const *zCsr = zSql;
72566   int len = 0;
72567   char *zRet;
72568   sqlite3 *db = sqlite3_context_db_handle(context);
72569
72570   UNUSED_PARAMETER(NotUsed);
72571
72572   /* The principle used to locate the table name in the CREATE TRIGGER 
72573   ** statement is that the table name is the first token that is immediatedly
72574   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
72575   ** of TK_WHEN, TK_BEGIN or TK_FOR.
72576   */
72577   if( zSql ){
72578     do {
72579
72580       if( !*zCsr ){
72581         /* Ran out of input before finding the table name. Return NULL. */
72582         return;
72583       }
72584
72585       /* Store the token that zCsr points to in tname. */
72586       tname.z = (char*)zCsr;
72587       tname.n = len;
72588
72589       /* Advance zCsr to the next token. Store that token type in 'token',
72590       ** and its length in 'len' (to be used next iteration of this loop).
72591       */
72592       do {
72593         zCsr += len;
72594         len = sqlite3GetToken(zCsr, &token);
72595       }while( token==TK_SPACE );
72596       assert( len>0 );
72597
72598       /* Variable 'dist' stores the number of tokens read since the most
72599       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
72600       ** token is read and 'dist' equals 2, the condition stated above
72601       ** to be met.
72602       **
72603       ** Note that ON cannot be a database, table or column name, so
72604       ** there is no need to worry about syntax like 
72605       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
72606       */
72607       dist++;
72608       if( token==TK_DOT || token==TK_ON ){
72609         dist = 0;
72610       }
72611     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
72612
72613     /* Variable tname now contains the token that is the old table-name
72614     ** in the CREATE TRIGGER statement.
72615     */
72616     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
72617        zTableName, tname.z+tname.n);
72618     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
72619   }
72620 }
72621 #endif   /* !SQLITE_OMIT_TRIGGER */
72622
72623 /*
72624 ** Register built-in functions used to help implement ALTER TABLE
72625 */
72626 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
72627   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
72628     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
72629 #ifndef SQLITE_OMIT_TRIGGER
72630     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
72631 #endif
72632 #ifndef SQLITE_OMIT_FOREIGN_KEY
72633     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
72634 #endif
72635   };
72636   int i;
72637   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
72638   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
72639
72640   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
72641     sqlite3FuncDefInsert(pHash, &aFunc[i]);
72642   }
72643 }
72644
72645 /*
72646 ** This function is used to create the text of expressions of the form:
72647 **
72648 **   name=<constant1> OR name=<constant2> OR ...
72649 **
72650 ** If argument zWhere is NULL, then a pointer string containing the text 
72651 ** "name=<constant>" is returned, where <constant> is the quoted version
72652 ** of the string passed as argument zConstant. The returned buffer is
72653 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
72654 ** caller to ensure that it is eventually freed.
72655 **
72656 ** If argument zWhere is not NULL, then the string returned is 
72657 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
72658 ** In this case zWhere is passed to sqlite3DbFree() before returning.
72659 ** 
72660 */
72661 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
72662   char *zNew;
72663   if( !zWhere ){
72664     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
72665   }else{
72666     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
72667     sqlite3DbFree(db, zWhere);
72668   }
72669   return zNew;
72670 }
72671
72672 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
72673 /*
72674 ** Generate the text of a WHERE expression which can be used to select all
72675 ** tables that have foreign key constraints that refer to table pTab (i.e.
72676 ** constraints for which pTab is the parent table) from the sqlite_master
72677 ** table.
72678 */
72679 static char *whereForeignKeys(Parse *pParse, Table *pTab){
72680   FKey *p;
72681   char *zWhere = 0;
72682   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
72683     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
72684   }
72685   return zWhere;
72686 }
72687 #endif
72688
72689 /*
72690 ** Generate the text of a WHERE expression which can be used to select all
72691 ** temporary triggers on table pTab from the sqlite_temp_master table. If
72692 ** table pTab has no temporary triggers, or is itself stored in the 
72693 ** temporary database, NULL is returned.
72694 */
72695 static char *whereTempTriggers(Parse *pParse, Table *pTab){
72696   Trigger *pTrig;
72697   char *zWhere = 0;
72698   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
72699
72700   /* If the table is not located in the temp-db (in which case NULL is 
72701   ** returned, loop through the tables list of triggers. For each trigger
72702   ** that is not part of the temp-db schema, add a clause to the WHERE 
72703   ** expression being built up in zWhere.
72704   */
72705   if( pTab->pSchema!=pTempSchema ){
72706     sqlite3 *db = pParse->db;
72707     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
72708       if( pTrig->pSchema==pTempSchema ){
72709         zWhere = whereOrName(db, zWhere, pTrig->zName);
72710       }
72711     }
72712   }
72713   if( zWhere ){
72714     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
72715     sqlite3DbFree(pParse->db, zWhere);
72716     zWhere = zNew;
72717   }
72718   return zWhere;
72719 }
72720
72721 /*
72722 ** Generate code to drop and reload the internal representation of table
72723 ** pTab from the database, including triggers and temporary triggers.
72724 ** Argument zName is the name of the table in the database schema at
72725 ** the time the generated code is executed. This can be different from
72726 ** pTab->zName if this function is being called to code part of an 
72727 ** "ALTER TABLE RENAME TO" statement.
72728 */
72729 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
72730   Vdbe *v;
72731   char *zWhere;
72732   int iDb;                   /* Index of database containing pTab */
72733 #ifndef SQLITE_OMIT_TRIGGER
72734   Trigger *pTrig;
72735 #endif
72736
72737   v = sqlite3GetVdbe(pParse);
72738   if( NEVER(v==0) ) return;
72739   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
72740   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
72741   assert( iDb>=0 );
72742
72743 #ifndef SQLITE_OMIT_TRIGGER
72744   /* Drop any table triggers from the internal schema. */
72745   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
72746     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
72747     assert( iTrigDb==iDb || iTrigDb==1 );
72748     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
72749   }
72750 #endif
72751
72752   /* Drop the table and index from the internal schema.  */
72753   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
72754
72755   /* Reload the table, index and permanent trigger schemas. */
72756   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
72757   if( !zWhere ) return;
72758   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
72759
72760 #ifndef SQLITE_OMIT_TRIGGER
72761   /* Now, if the table is not stored in the temp database, reload any temp 
72762   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
72763   */
72764   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
72765     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
72766   }
72767 #endif
72768 }
72769
72770 /*
72771 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
72772 ** command. 
72773 */
72774 SQLITE_PRIVATE void sqlite3AlterRenameTable(
72775   Parse *pParse,            /* Parser context. */
72776   SrcList *pSrc,            /* The table to rename. */
72777   Token *pName              /* The new table name. */
72778 ){
72779   int iDb;                  /* Database that contains the table */
72780   char *zDb;                /* Name of database iDb */
72781   Table *pTab;              /* Table being renamed */
72782   char *zName = 0;          /* NULL-terminated version of pName */ 
72783   sqlite3 *db = pParse->db; /* Database connection */
72784   int nTabName;             /* Number of UTF-8 characters in zTabName */
72785   const char *zTabName;     /* Original name of the table */
72786   Vdbe *v;
72787 #ifndef SQLITE_OMIT_TRIGGER
72788   char *zWhere = 0;         /* Where clause to locate temp triggers */
72789 #endif
72790   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
72791   int savedDbFlags;         /* Saved value of db->flags */
72792
72793   savedDbFlags = db->flags;  
72794   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
72795   assert( pSrc->nSrc==1 );
72796   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
72797
72798   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
72799   if( !pTab ) goto exit_rename_table;
72800   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
72801   zDb = db->aDb[iDb].zName;
72802   db->flags |= SQLITE_PreferBuiltin;
72803
72804   /* Get a NULL terminated version of the new table name. */
72805   zName = sqlite3NameFromToken(db, pName);
72806   if( !zName ) goto exit_rename_table;
72807
72808   /* Check that a table or index named 'zName' does not already exist
72809   ** in database iDb. If so, this is an error.
72810   */
72811   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
72812     sqlite3ErrorMsg(pParse, 
72813         "there is already another table or index with this name: %s", zName);
72814     goto exit_rename_table;
72815   }
72816
72817   /* Make sure it is not a system table being altered, or a reserved name
72818   ** that the table is being renamed to.
72819   */
72820   if( sqlite3Strlen30(pTab->zName)>6 
72821    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
72822   ){
72823     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
72824     goto exit_rename_table;
72825   }
72826   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
72827     goto exit_rename_table;
72828   }
72829
72830 #ifndef SQLITE_OMIT_VIEW
72831   if( pTab->pSelect ){
72832     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
72833     goto exit_rename_table;
72834   }
72835 #endif
72836
72837 #ifndef SQLITE_OMIT_AUTHORIZATION
72838   /* Invoke the authorization callback. */
72839   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
72840     goto exit_rename_table;
72841   }
72842 #endif
72843
72844 #ifndef SQLITE_OMIT_VIRTUALTABLE
72845   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
72846     goto exit_rename_table;
72847   }
72848   if( IsVirtual(pTab) ){
72849     pVTab = sqlite3GetVTable(db, pTab);
72850     if( pVTab->pVtab->pModule->xRename==0 ){
72851       pVTab = 0;
72852     }
72853   }
72854 #endif
72855
72856   /* Begin a transaction and code the VerifyCookie for database iDb. 
72857   ** Then modify the schema cookie (since the ALTER TABLE modifies the
72858   ** schema). Open a statement transaction if the table is a virtual
72859   ** table.
72860   */
72861   v = sqlite3GetVdbe(pParse);
72862   if( v==0 ){
72863     goto exit_rename_table;
72864   }
72865   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
72866   sqlite3ChangeCookie(pParse, iDb);
72867
72868   /* If this is a virtual table, invoke the xRename() function if
72869   ** one is defined. The xRename() callback will modify the names
72870   ** of any resources used by the v-table implementation (including other
72871   ** SQLite tables) that are identified by the name of the virtual table.
72872   */
72873 #ifndef SQLITE_OMIT_VIRTUALTABLE
72874   if( pVTab ){
72875     int i = ++pParse->nMem;
72876     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
72877     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
72878     sqlite3MayAbort(pParse);
72879   }
72880 #endif
72881
72882   /* figure out how many UTF-8 characters are in zName */
72883   zTabName = pTab->zName;
72884   nTabName = sqlite3Utf8CharLen(zTabName, -1);
72885
72886 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
72887   if( db->flags&SQLITE_ForeignKeys ){
72888     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
72889     ** statements corresponding to all child tables of foreign key constraints
72890     ** for which the renamed table is the parent table.  */
72891     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
72892       sqlite3NestedParse(pParse, 
72893           "UPDATE \"%w\".%s SET "
72894               "sql = sqlite_rename_parent(sql, %Q, %Q) "
72895               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
72896       sqlite3DbFree(db, zWhere);
72897     }
72898   }
72899 #endif
72900
72901   /* Modify the sqlite_master table to use the new table name. */
72902   sqlite3NestedParse(pParse,
72903       "UPDATE %Q.%s SET "
72904 #ifdef SQLITE_OMIT_TRIGGER
72905           "sql = sqlite_rename_table(sql, %Q), "
72906 #else
72907           "sql = CASE "
72908             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
72909             "ELSE sqlite_rename_table(sql, %Q) END, "
72910 #endif
72911           "tbl_name = %Q, "
72912           "name = CASE "
72913             "WHEN type='table' THEN %Q "
72914             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
72915              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
72916             "ELSE name END "
72917       "WHERE tbl_name=%Q AND "
72918           "(type='table' OR type='index' OR type='trigger');", 
72919       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
72920 #ifndef SQLITE_OMIT_TRIGGER
72921       zName,
72922 #endif
72923       zName, nTabName, zTabName
72924   );
72925
72926 #ifndef SQLITE_OMIT_AUTOINCREMENT
72927   /* If the sqlite_sequence table exists in this database, then update 
72928   ** it with the new table name.
72929   */
72930   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
72931     sqlite3NestedParse(pParse,
72932         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
72933         zDb, zName, pTab->zName);
72934   }
72935 #endif
72936
72937 #ifndef SQLITE_OMIT_TRIGGER
72938   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
72939   ** table. Don't do this if the table being ALTERed is itself located in
72940   ** the temp database.
72941   */
72942   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
72943     sqlite3NestedParse(pParse, 
72944         "UPDATE sqlite_temp_master SET "
72945             "sql = sqlite_rename_trigger(sql, %Q), "
72946             "tbl_name = %Q "
72947             "WHERE %s;", zName, zName, zWhere);
72948     sqlite3DbFree(db, zWhere);
72949   }
72950 #endif
72951
72952 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
72953   if( db->flags&SQLITE_ForeignKeys ){
72954     FKey *p;
72955     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
72956       Table *pFrom = p->pFrom;
72957       if( pFrom!=pTab ){
72958         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
72959       }
72960     }
72961   }
72962 #endif
72963
72964   /* Drop and reload the internal table schema. */
72965   reloadTableSchema(pParse, pTab, zName);
72966
72967 exit_rename_table:
72968   sqlite3SrcListDelete(db, pSrc);
72969   sqlite3DbFree(db, zName);
72970   db->flags = savedDbFlags;
72971 }
72972
72973
72974 /*
72975 ** Generate code to make sure the file format number is at least minFormat.
72976 ** The generated code will increase the file format number if necessary.
72977 */
72978 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
72979   Vdbe *v;
72980   v = sqlite3GetVdbe(pParse);
72981   /* The VDBE should have been allocated before this routine is called.
72982   ** If that allocation failed, we would have quit before reaching this
72983   ** point */
72984   if( ALWAYS(v) ){
72985     int r1 = sqlite3GetTempReg(pParse);
72986     int r2 = sqlite3GetTempReg(pParse);
72987     int j1;
72988     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
72989     sqlite3VdbeUsesBtree(v, iDb);
72990     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
72991     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
72992     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
72993     sqlite3VdbeJumpHere(v, j1);
72994     sqlite3ReleaseTempReg(pParse, r1);
72995     sqlite3ReleaseTempReg(pParse, r2);
72996   }
72997 }
72998
72999 /*
73000 ** This function is called after an "ALTER TABLE ... ADD" statement
73001 ** has been parsed. Argument pColDef contains the text of the new
73002 ** column definition.
73003 **
73004 ** The Table structure pParse->pNewTable was extended to include
73005 ** the new column during parsing.
73006 */
73007 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
73008   Table *pNew;              /* Copy of pParse->pNewTable */
73009   Table *pTab;              /* Table being altered */
73010   int iDb;                  /* Database number */
73011   const char *zDb;          /* Database name */
73012   const char *zTab;         /* Table name */
73013   char *zCol;               /* Null-terminated column definition */
73014   Column *pCol;             /* The new column */
73015   Expr *pDflt;              /* Default value for the new column */
73016   sqlite3 *db;              /* The database connection; */
73017
73018   db = pParse->db;
73019   if( pParse->nErr || db->mallocFailed ) return;
73020   pNew = pParse->pNewTable;
73021   assert( pNew );
73022
73023   assert( sqlite3BtreeHoldsAllMutexes(db) );
73024   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
73025   zDb = db->aDb[iDb].zName;
73026   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
73027   pCol = &pNew->aCol[pNew->nCol-1];
73028   pDflt = pCol->pDflt;
73029   pTab = sqlite3FindTable(db, zTab, zDb);
73030   assert( pTab );
73031
73032 #ifndef SQLITE_OMIT_AUTHORIZATION
73033   /* Invoke the authorization callback. */
73034   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
73035     return;
73036   }
73037 #endif
73038
73039   /* If the default value for the new column was specified with a 
73040   ** literal NULL, then set pDflt to 0. This simplifies checking
73041   ** for an SQL NULL default below.
73042   */
73043   if( pDflt && pDflt->op==TK_NULL ){
73044     pDflt = 0;
73045   }
73046
73047   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
73048   ** If there is a NOT NULL constraint, then the default value for the
73049   ** column must not be NULL.
73050   */
73051   if( pCol->isPrimKey ){
73052     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
73053     return;
73054   }
73055   if( pNew->pIndex ){
73056     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
73057     return;
73058   }
73059   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
73060     sqlite3ErrorMsg(pParse, 
73061         "Cannot add a REFERENCES column with non-NULL default value");
73062     return;
73063   }
73064   if( pCol->notNull && !pDflt ){
73065     sqlite3ErrorMsg(pParse, 
73066         "Cannot add a NOT NULL column with default value NULL");
73067     return;
73068   }
73069
73070   /* Ensure the default expression is something that sqlite3ValueFromExpr()
73071   ** can handle (i.e. not CURRENT_TIME etc.)
73072   */
73073   if( pDflt ){
73074     sqlite3_value *pVal;
73075     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
73076       db->mallocFailed = 1;
73077       return;
73078     }
73079     if( !pVal ){
73080       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
73081       return;
73082     }
73083     sqlite3ValueFree(pVal);
73084   }
73085
73086   /* Modify the CREATE TABLE statement. */
73087   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
73088   if( zCol ){
73089     char *zEnd = &zCol[pColDef->n-1];
73090     int savedDbFlags = db->flags;
73091     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
73092       *zEnd-- = '\0';
73093     }
73094     db->flags |= SQLITE_PreferBuiltin;
73095     sqlite3NestedParse(pParse, 
73096         "UPDATE \"%w\".%s SET "
73097           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
73098         "WHERE type = 'table' AND name = %Q", 
73099       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
73100       zTab
73101     );
73102     sqlite3DbFree(db, zCol);
73103     db->flags = savedDbFlags;
73104   }
73105
73106   /* If the default value of the new column is NULL, then set the file
73107   ** format to 2. If the default value of the new column is not NULL,
73108   ** the file format becomes 3.
73109   */
73110   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
73111
73112   /* Reload the schema of the modified table. */
73113   reloadTableSchema(pParse, pTab, pTab->zName);
73114 }
73115
73116 /*
73117 ** This function is called by the parser after the table-name in
73118 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
73119 ** pSrc is the full-name of the table being altered.
73120 **
73121 ** This routine makes a (partial) copy of the Table structure
73122 ** for the table being altered and sets Parse.pNewTable to point
73123 ** to it. Routines called by the parser as the column definition
73124 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
73125 ** the copy. The copy of the Table structure is deleted by tokenize.c 
73126 ** after parsing is finished.
73127 **
73128 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
73129 ** coding the "ALTER TABLE ... ADD" statement.
73130 */
73131 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
73132   Table *pNew;
73133   Table *pTab;
73134   Vdbe *v;
73135   int iDb;
73136   int i;
73137   int nAlloc;
73138   sqlite3 *db = pParse->db;
73139
73140   /* Look up the table being altered. */
73141   assert( pParse->pNewTable==0 );
73142   assert( sqlite3BtreeHoldsAllMutexes(db) );
73143   if( db->mallocFailed ) goto exit_begin_add_column;
73144   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
73145   if( !pTab ) goto exit_begin_add_column;
73146
73147 #ifndef SQLITE_OMIT_VIRTUALTABLE
73148   if( IsVirtual(pTab) ){
73149     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
73150     goto exit_begin_add_column;
73151   }
73152 #endif
73153
73154   /* Make sure this is not an attempt to ALTER a view. */
73155   if( pTab->pSelect ){
73156     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
73157     goto exit_begin_add_column;
73158   }
73159
73160   assert( pTab->addColOffset>0 );
73161   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73162
73163   /* Put a copy of the Table struct in Parse.pNewTable for the
73164   ** sqlite3AddColumn() function and friends to modify.  But modify
73165   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
73166   ** prefix, we insure that the name will not collide with an existing
73167   ** table because user table are not allowed to have the "sqlite_"
73168   ** prefix on their name.
73169   */
73170   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
73171   if( !pNew ) goto exit_begin_add_column;
73172   pParse->pNewTable = pNew;
73173   pNew->nRef = 1;
73174   pNew->nCol = pTab->nCol;
73175   assert( pNew->nCol>0 );
73176   nAlloc = (((pNew->nCol-1)/8)*8)+8;
73177   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
73178   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
73179   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
73180   if( !pNew->aCol || !pNew->zName ){
73181     db->mallocFailed = 1;
73182     goto exit_begin_add_column;
73183   }
73184   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
73185   for(i=0; i<pNew->nCol; i++){
73186     Column *pCol = &pNew->aCol[i];
73187     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
73188     pCol->zColl = 0;
73189     pCol->zType = 0;
73190     pCol->pDflt = 0;
73191     pCol->zDflt = 0;
73192   }
73193   pNew->pSchema = db->aDb[iDb].pSchema;
73194   pNew->addColOffset = pTab->addColOffset;
73195   pNew->nRef = 1;
73196
73197   /* Begin a transaction and increment the schema cookie.  */
73198   sqlite3BeginWriteOperation(pParse, 0, iDb);
73199   v = sqlite3GetVdbe(pParse);
73200   if( !v ) goto exit_begin_add_column;
73201   sqlite3ChangeCookie(pParse, iDb);
73202
73203 exit_begin_add_column:
73204   sqlite3SrcListDelete(db, pSrc);
73205   return;
73206 }
73207 #endif  /* SQLITE_ALTER_TABLE */
73208
73209 /************** End of alter.c ***********************************************/
73210 /************** Begin file analyze.c *****************************************/
73211 /*
73212 ** 2005 July 8
73213 **
73214 ** The author disclaims copyright to this source code.  In place of
73215 ** a legal notice, here is a blessing:
73216 **
73217 **    May you do good and not evil.
73218 **    May you find forgiveness for yourself and forgive others.
73219 **    May you share freely, never taking more than you give.
73220 **
73221 *************************************************************************
73222 ** This file contains code associated with the ANALYZE command.
73223 */
73224 #ifndef SQLITE_OMIT_ANALYZE
73225
73226 /*
73227 ** This routine generates code that opens the sqlite_stat1 table for
73228 ** writing with cursor iStatCur. If the library was built with the
73229 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
73230 ** opened for writing using cursor (iStatCur+1)
73231 **
73232 ** If the sqlite_stat1 tables does not previously exist, it is created.
73233 ** Similarly, if the sqlite_stat2 table does not exist and the library
73234 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
73235 **
73236 ** Argument zWhere may be a pointer to a buffer containing a table name,
73237 ** or it may be a NULL pointer. If it is not NULL, then all entries in
73238 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
73239 ** with the named table are deleted. If zWhere==0, then code is generated
73240 ** to delete all stat table entries.
73241 */
73242 static void openStatTable(
73243   Parse *pParse,          /* Parsing context */
73244   int iDb,                /* The database we are looking in */
73245   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
73246   const char *zWhere      /* Delete entries associated with this table */
73247 ){
73248   static const struct {
73249     const char *zName;
73250     const char *zCols;
73251   } aTable[] = {
73252     { "sqlite_stat1", "tbl,idx,stat" },
73253 #ifdef SQLITE_ENABLE_STAT2
73254     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
73255 #endif
73256   };
73257
73258   int aRoot[] = {0, 0};
73259   u8 aCreateTbl[] = {0, 0};
73260
73261   int i;
73262   sqlite3 *db = pParse->db;
73263   Db *pDb;
73264   Vdbe *v = sqlite3GetVdbe(pParse);
73265   if( v==0 ) return;
73266   assert( sqlite3BtreeHoldsAllMutexes(db) );
73267   assert( sqlite3VdbeDb(v)==db );
73268   pDb = &db->aDb[iDb];
73269
73270   for(i=0; i<ArraySize(aTable); i++){
73271     const char *zTab = aTable[i].zName;
73272     Table *pStat;
73273     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
73274       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
73275       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
73276       ** of the new table in register pParse->regRoot. This is important 
73277       ** because the OpenWrite opcode below will be needing it. */
73278       sqlite3NestedParse(pParse,
73279           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
73280       );
73281       aRoot[i] = pParse->regRoot;
73282       aCreateTbl[i] = 1;
73283     }else{
73284       /* The table already exists. If zWhere is not NULL, delete all entries 
73285       ** associated with the table zWhere. If zWhere is NULL, delete the
73286       ** entire contents of the table. */
73287       aRoot[i] = pStat->tnum;
73288       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
73289       if( zWhere ){
73290         sqlite3NestedParse(pParse,
73291            "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
73292         );
73293       }else{
73294         /* The sqlite_stat[12] table already exists.  Delete all rows. */
73295         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
73296       }
73297     }
73298   }
73299
73300   /* Open the sqlite_stat[12] tables for writing. */
73301   for(i=0; i<ArraySize(aTable); i++){
73302     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
73303     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
73304     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
73305   }
73306 }
73307
73308 /*
73309 ** Generate code to do an analysis of all indices associated with
73310 ** a single table.
73311 */
73312 static void analyzeOneTable(
73313   Parse *pParse,   /* Parser context */
73314   Table *pTab,     /* Table whose indices are to be analyzed */
73315   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
73316   int iMem         /* Available memory locations begin here */
73317 ){
73318   sqlite3 *db = pParse->db;    /* Database handle */
73319   Index *pIdx;                 /* An index to being analyzed */
73320   int iIdxCur;                 /* Cursor open on index being analyzed */
73321   Vdbe *v;                     /* The virtual machine being built up */
73322   int i;                       /* Loop counter */
73323   int topOfLoop;               /* The top of the loop */
73324   int endOfLoop;               /* The end of the loop */
73325   int addr = 0;                /* The address of an instruction */
73326   int jZeroRows = 0;           /* Jump from here if number of rows is zero */
73327   int iDb;                     /* Index of database containing pTab */
73328   int regTabname = iMem++;     /* Register containing table name */
73329   int regIdxname = iMem++;     /* Register containing index name */
73330   int regSampleno = iMem++;    /* Register containing next sample number */
73331   int regCol = iMem++;         /* Content of a column analyzed table */
73332   int regRec = iMem++;         /* Register holding completed record */
73333   int regTemp = iMem++;        /* Temporary use register */
73334   int regRowid = iMem++;       /* Rowid for the inserted record */
73335
73336 #ifdef SQLITE_ENABLE_STAT2
73337   int regTemp2 = iMem++;       /* Temporary use register */
73338   int regSamplerecno = iMem++; /* Index of next sample to record */
73339   int regRecno = iMem++;       /* Current sample index */
73340   int regLast = iMem++;        /* Index of last sample to record */
73341   int regFirst = iMem++;       /* Index of first sample to record */
73342 #endif
73343
73344   v = sqlite3GetVdbe(pParse);
73345   if( v==0 || NEVER(pTab==0) ){
73346     return;
73347   }
73348   if( pTab->tnum==0 ){
73349     /* Do not gather statistics on views or virtual tables */
73350     return;
73351   }
73352   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
73353     /* Do not gather statistics on system tables */
73354     return;
73355   }
73356   assert( sqlite3BtreeHoldsAllMutexes(db) );
73357   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73358   assert( iDb>=0 );
73359 #ifndef SQLITE_OMIT_AUTHORIZATION
73360   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
73361       db->aDb[iDb].zName ) ){
73362     return;
73363   }
73364 #endif
73365
73366   /* Establish a read-lock on the table at the shared-cache level. */
73367   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
73368
73369   iIdxCur = pParse->nTab++;
73370   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
73371   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
73372     int nCol = pIdx->nColumn;
73373     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
73374
73375     if( iMem+1+(nCol*2)>pParse->nMem ){
73376       pParse->nMem = iMem+1+(nCol*2);
73377     }
73378
73379     /* Open a cursor to the index to be analyzed. */
73380     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
73381     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
73382         (char *)pKey, P4_KEYINFO_HANDOFF);
73383     VdbeComment((v, "%s", pIdx->zName));
73384
73385     /* Populate the register containing the index name. */
73386     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
73387
73388 #ifdef SQLITE_ENABLE_STAT2
73389
73390     /* If this iteration of the loop is generating code to analyze the
73391     ** first index in the pTab->pIndex list, then register regLast has
73392     ** not been populated. In this case populate it now.  */
73393     if( pTab->pIndex==pIdx ){
73394       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
73395       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
73396       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
73397
73398       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
73399       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
73400       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
73401       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
73402       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
73403       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
73404       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
73405       sqlite3VdbeJumpHere(v, addr);
73406     }
73407
73408     /* Zero the regSampleno and regRecno registers. */
73409     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
73410     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
73411     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
73412 #endif
73413
73414     /* The block of memory cells initialized here is used as follows.
73415     **
73416     **    iMem:                
73417     **        The total number of rows in the table.
73418     **
73419     **    iMem+1 .. iMem+nCol: 
73420     **        Number of distinct entries in index considering the 
73421     **        left-most N columns only, where N is between 1 and nCol, 
73422     **        inclusive.
73423     **
73424     **    iMem+nCol+1 .. Mem+2*nCol:  
73425     **        Previous value of indexed columns, from left to right.
73426     **
73427     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
73428     ** initialized to contain an SQL NULL.
73429     */
73430     for(i=0; i<=nCol; i++){
73431       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
73432     }
73433     for(i=0; i<nCol; i++){
73434       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
73435     }
73436
73437     /* Start the analysis loop. This loop runs through all the entries in
73438     ** the index b-tree.  */
73439     endOfLoop = sqlite3VdbeMakeLabel(v);
73440     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
73441     topOfLoop = sqlite3VdbeCurrentAddr(v);
73442     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
73443
73444     for(i=0; i<nCol; i++){
73445       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
73446 #ifdef SQLITE_ENABLE_STAT2
73447       if( i==0 ){
73448         /* Check if the record that cursor iIdxCur points to contains a
73449         ** value that should be stored in the sqlite_stat2 table. If so,
73450         ** store it.  */
73451         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
73452         assert( regTabname+1==regIdxname 
73453              && regTabname+2==regSampleno
73454              && regTabname+3==regCol
73455         );
73456         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
73457         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
73458         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
73459         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
73460
73461         /* Calculate new values for regSamplerecno and regSampleno.
73462         **
73463         **   sampleno = sampleno + 1
73464         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
73465         */
73466         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
73467         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
73468         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
73469         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
73470         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
73471         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
73472         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
73473
73474         sqlite3VdbeJumpHere(v, ne);
73475         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
73476       }
73477 #endif
73478
73479       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
73480       /**** TODO:  add collating sequence *****/
73481       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
73482     }
73483     if( db->mallocFailed ){
73484       /* If a malloc failure has occurred, then the result of the expression 
73485       ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
73486       ** below may be negative. Which causes an assert() to fail (or an
73487       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
73488       return;
73489     }
73490     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
73491     for(i=0; i<nCol; i++){
73492       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
73493       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
73494       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
73495     }
73496
73497     /* End of the analysis loop. */
73498     sqlite3VdbeResolveLabel(v, endOfLoop);
73499     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
73500     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
73501
73502     /* Store the results in sqlite_stat1.
73503     **
73504     ** The result is a single row of the sqlite_stat1 table.  The first
73505     ** two columns are the names of the table and index.  The third column
73506     ** is a string composed of a list of integer statistics about the
73507     ** index.  The first integer in the list is the total number of entries
73508     ** in the index.  There is one additional integer in the list for each
73509     ** column of the table.  This additional integer is a guess of how many
73510     ** rows of the table the index will select.  If D is the count of distinct
73511     ** values and K is the total number of rows, then the integer is computed
73512     ** as:
73513     **
73514     **        I = (K+D-1)/D
73515     **
73516     ** If K==0 then no entry is made into the sqlite_stat1 table.  
73517     ** If K>0 then it is always the case the D>0 so division by zero
73518     ** is never possible.
73519     */
73520     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
73521     if( jZeroRows==0 ){
73522       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
73523     }
73524     for(i=0; i<nCol; i++){
73525       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
73526       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
73527       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
73528       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
73529       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
73530       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
73531       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
73532     }
73533     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
73534     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
73535     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
73536     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73537   }
73538
73539   /* If the table has no indices, create a single sqlite_stat1 entry
73540   ** containing NULL as the index name and the row count as the content.
73541   */
73542   if( pTab->pIndex==0 ){
73543     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
73544     VdbeComment((v, "%s", pTab->zName));
73545     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
73546     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
73547   }else{
73548     assert( jZeroRows>0 );
73549     addr = sqlite3VdbeAddOp0(v, OP_Goto);
73550     sqlite3VdbeJumpHere(v, jZeroRows);
73551   }
73552   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
73553   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
73554   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
73555   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
73556   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
73557   if( pParse->nMem<regRec ) pParse->nMem = regRec;
73558   if( jZeroRows ){
73559     sqlite3VdbeJumpHere(v, addr);
73560   }
73561 }
73562
73563 /*
73564 ** Generate code that will cause the most recent index analysis to
73565 ** be loaded into internal hash tables where is can be used.
73566 */
73567 static void loadAnalysis(Parse *pParse, int iDb){
73568   Vdbe *v = sqlite3GetVdbe(pParse);
73569   if( v ){
73570     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
73571   }
73572 }
73573
73574 /*
73575 ** Generate code that will do an analysis of an entire database
73576 */
73577 static void analyzeDatabase(Parse *pParse, int iDb){
73578   sqlite3 *db = pParse->db;
73579   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
73580   HashElem *k;
73581   int iStatCur;
73582   int iMem;
73583
73584   sqlite3BeginWriteOperation(pParse, 0, iDb);
73585   iStatCur = pParse->nTab;
73586   pParse->nTab += 2;
73587   openStatTable(pParse, iDb, iStatCur, 0);
73588   iMem = pParse->nMem+1;
73589   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
73590     Table *pTab = (Table*)sqliteHashData(k);
73591     analyzeOneTable(pParse, pTab, iStatCur, iMem);
73592   }
73593   loadAnalysis(pParse, iDb);
73594 }
73595
73596 /*
73597 ** Generate code that will do an analysis of a single table in
73598 ** a database.
73599 */
73600 static void analyzeTable(Parse *pParse, Table *pTab){
73601   int iDb;
73602   int iStatCur;
73603
73604   assert( pTab!=0 );
73605   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
73606   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
73607   sqlite3BeginWriteOperation(pParse, 0, iDb);
73608   iStatCur = pParse->nTab;
73609   pParse->nTab += 2;
73610   openStatTable(pParse, iDb, iStatCur, pTab->zName);
73611   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
73612   loadAnalysis(pParse, iDb);
73613 }
73614
73615 /*
73616 ** Generate code for the ANALYZE command.  The parser calls this routine
73617 ** when it recognizes an ANALYZE command.
73618 **
73619 **        ANALYZE                            -- 1
73620 **        ANALYZE  <database>                -- 2
73621 **        ANALYZE  ?<database>.?<tablename>  -- 3
73622 **
73623 ** Form 1 causes all indices in all attached databases to be analyzed.
73624 ** Form 2 analyzes all indices the single database named.
73625 ** Form 3 analyzes all indices associated with the named table.
73626 */
73627 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
73628   sqlite3 *db = pParse->db;
73629   int iDb;
73630   int i;
73631   char *z, *zDb;
73632   Table *pTab;
73633   Token *pTableName;
73634
73635   /* Read the database schema. If an error occurs, leave an error message
73636   ** and code in pParse and return NULL. */
73637   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
73638   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
73639     return;
73640   }
73641
73642   assert( pName2!=0 || pName1==0 );
73643   if( pName1==0 ){
73644     /* Form 1:  Analyze everything */
73645     for(i=0; i<db->nDb; i++){
73646       if( i==1 ) continue;  /* Do not analyze the TEMP database */
73647       analyzeDatabase(pParse, i);
73648     }
73649   }else if( pName2->n==0 ){
73650     /* Form 2:  Analyze the database or table named */
73651     iDb = sqlite3FindDb(db, pName1);
73652     if( iDb>=0 ){
73653       analyzeDatabase(pParse, iDb);
73654     }else{
73655       z = sqlite3NameFromToken(db, pName1);
73656       if( z ){
73657         pTab = sqlite3LocateTable(pParse, 0, z, 0);
73658         sqlite3DbFree(db, z);
73659         if( pTab ){
73660           analyzeTable(pParse, pTab);
73661         }
73662       }
73663     }
73664   }else{
73665     /* Form 3: Analyze the fully qualified table name */
73666     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
73667     if( iDb>=0 ){
73668       zDb = db->aDb[iDb].zName;
73669       z = sqlite3NameFromToken(db, pTableName);
73670       if( z ){
73671         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
73672         sqlite3DbFree(db, z);
73673         if( pTab ){
73674           analyzeTable(pParse, pTab);
73675         }
73676       }
73677     }   
73678   }
73679 }
73680
73681 /*
73682 ** Used to pass information from the analyzer reader through to the
73683 ** callback routine.
73684 */
73685 typedef struct analysisInfo analysisInfo;
73686 struct analysisInfo {
73687   sqlite3 *db;
73688   const char *zDatabase;
73689 };
73690
73691 /*
73692 ** This callback is invoked once for each index when reading the
73693 ** sqlite_stat1 table.  
73694 **
73695 **     argv[0] = name of the table
73696 **     argv[1] = name of the index (might be NULL)
73697 **     argv[2] = results of analysis - on integer for each column
73698 **
73699 ** Entries for which argv[1]==NULL simply record the number of rows in
73700 ** the table.
73701 */
73702 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
73703   analysisInfo *pInfo = (analysisInfo*)pData;
73704   Index *pIndex;
73705   Table *pTable;
73706   int i, c, n;
73707   unsigned int v;
73708   const char *z;
73709
73710   assert( argc==3 );
73711   UNUSED_PARAMETER2(NotUsed, argc);
73712
73713   if( argv==0 || argv[0]==0 || argv[2]==0 ){
73714     return 0;
73715   }
73716   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
73717   if( pTable==0 ){
73718     return 0;
73719   }
73720   if( argv[1] ){
73721     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
73722   }else{
73723     pIndex = 0;
73724   }
73725   n = pIndex ? pIndex->nColumn : 0;
73726   z = argv[2];
73727   for(i=0; *z && i<=n; i++){
73728     v = 0;
73729     while( (c=z[0])>='0' && c<='9' ){
73730       v = v*10 + c - '0';
73731       z++;
73732     }
73733     if( i==0 ) pTable->nRowEst = v;
73734     if( pIndex==0 ) break;
73735     pIndex->aiRowEst[i] = v;
73736     if( *z==' ' ) z++;
73737   }
73738   return 0;
73739 }
73740
73741 /*
73742 ** If the Index.aSample variable is not NULL, delete the aSample[] array
73743 ** and its contents.
73744 */
73745 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
73746 #ifdef SQLITE_ENABLE_STAT2
73747   if( pIdx->aSample ){
73748     int j;
73749     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
73750       IndexSample *p = &pIdx->aSample[j];
73751       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
73752         sqlite3DbFree(db, p->u.z);
73753       }
73754     }
73755     sqlite3DbFree(db, pIdx->aSample);
73756   }
73757 #else
73758   UNUSED_PARAMETER(db);
73759   UNUSED_PARAMETER(pIdx);
73760 #endif
73761 }
73762
73763 /*
73764 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
73765 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
73766 ** arrays. The contents of sqlite_stat2 are used to populate the
73767 ** Index.aSample[] arrays.
73768 **
73769 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
73770 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
73771 ** during compilation and the sqlite_stat2 table is present, no data is 
73772 ** read from it.
73773 **
73774 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
73775 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
73776 ** returned. However, in this case, data is read from the sqlite_stat1
73777 ** table (if it is present) before returning.
73778 **
73779 ** If an OOM error occurs, this function always sets db->mallocFailed.
73780 ** This means if the caller does not care about other errors, the return
73781 ** code may be ignored.
73782 */
73783 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
73784   analysisInfo sInfo;
73785   HashElem *i;
73786   char *zSql;
73787   int rc;
73788
73789   assert( iDb>=0 && iDb<db->nDb );
73790   assert( db->aDb[iDb].pBt!=0 );
73791   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
73792
73793   /* Clear any prior statistics */
73794   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
73795     Index *pIdx = sqliteHashData(i);
73796     sqlite3DefaultRowEst(pIdx);
73797     sqlite3DeleteIndexSamples(db, pIdx);
73798     pIdx->aSample = 0;
73799   }
73800
73801   /* Check to make sure the sqlite_stat1 table exists */
73802   sInfo.db = db;
73803   sInfo.zDatabase = db->aDb[iDb].zName;
73804   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
73805     return SQLITE_ERROR;
73806   }
73807
73808   /* Load new statistics out of the sqlite_stat1 table */
73809   zSql = sqlite3MPrintf(db, 
73810       "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
73811   if( zSql==0 ){
73812     rc = SQLITE_NOMEM;
73813   }else{
73814     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
73815     sqlite3DbFree(db, zSql);
73816   }
73817
73818
73819   /* Load the statistics from the sqlite_stat2 table. */
73820 #ifdef SQLITE_ENABLE_STAT2
73821   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
73822     rc = SQLITE_ERROR;
73823   }
73824   if( rc==SQLITE_OK ){
73825     sqlite3_stmt *pStmt = 0;
73826
73827     zSql = sqlite3MPrintf(db, 
73828         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
73829     if( !zSql ){
73830       rc = SQLITE_NOMEM;
73831     }else{
73832       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
73833       sqlite3DbFree(db, zSql);
73834     }
73835
73836     if( rc==SQLITE_OK ){
73837       while( sqlite3_step(pStmt)==SQLITE_ROW ){
73838         char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
73839         Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
73840         if( pIdx ){
73841           int iSample = sqlite3_column_int(pStmt, 1);
73842           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
73843             int eType = sqlite3_column_type(pStmt, 2);
73844
73845             if( pIdx->aSample==0 ){
73846               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
73847               pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
73848               if( pIdx->aSample==0 ){
73849                 db->mallocFailed = 1;
73850                 break;
73851               }
73852               memset(pIdx->aSample, 0, sz);
73853             }
73854
73855             assert( pIdx->aSample );
73856             {
73857               IndexSample *pSample = &pIdx->aSample[iSample];
73858               pSample->eType = (u8)eType;
73859               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
73860                 pSample->u.r = sqlite3_column_double(pStmt, 2);
73861               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
73862                 const char *z = (const char *)(
73863                     (eType==SQLITE_BLOB) ?
73864                     sqlite3_column_blob(pStmt, 2):
73865                     sqlite3_column_text(pStmt, 2)
73866                 );
73867                 int n = sqlite3_column_bytes(pStmt, 2);
73868                 if( n>24 ){
73869                   n = 24;
73870                 }
73871                 pSample->nByte = (u8)n;
73872                 if( n < 1){
73873                   pSample->u.z = 0;
73874                 }else{
73875                   pSample->u.z = sqlite3DbStrNDup(0, z, n);
73876                   if( pSample->u.z==0 ){
73877                     db->mallocFailed = 1;
73878                     break;
73879                   }
73880                 }
73881               }
73882             }
73883           }
73884         }
73885       }
73886       rc = sqlite3_finalize(pStmt);
73887     }
73888   }
73889 #endif
73890
73891   if( rc==SQLITE_NOMEM ){
73892     db->mallocFailed = 1;
73893   }
73894   return rc;
73895 }
73896
73897
73898 #endif /* SQLITE_OMIT_ANALYZE */
73899
73900 /************** End of analyze.c *********************************************/
73901 /************** Begin file attach.c ******************************************/
73902 /*
73903 ** 2003 April 6
73904 **
73905 ** The author disclaims copyright to this source code.  In place of
73906 ** a legal notice, here is a blessing:
73907 **
73908 **    May you do good and not evil.
73909 **    May you find forgiveness for yourself and forgive others.
73910 **    May you share freely, never taking more than you give.
73911 **
73912 *************************************************************************
73913 ** This file contains code used to implement the ATTACH and DETACH commands.
73914 */
73915
73916 #ifndef SQLITE_OMIT_ATTACH
73917 /*
73918 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
73919 ** is slightly different from resolving a normal SQL expression, because simple
73920 ** identifiers are treated as strings, not possible column names or aliases.
73921 **
73922 ** i.e. if the parser sees:
73923 **
73924 **     ATTACH DATABASE abc AS def
73925 **
73926 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
73927 ** looking for columns of the same name.
73928 **
73929 ** This only applies to the root node of pExpr, so the statement:
73930 **
73931 **     ATTACH DATABASE abc||def AS 'db2'
73932 **
73933 ** will fail because neither abc or def can be resolved.
73934 */
73935 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
73936 {
73937   int rc = SQLITE_OK;
73938   if( pExpr ){
73939     if( pExpr->op!=TK_ID ){
73940       rc = sqlite3ResolveExprNames(pName, pExpr);
73941       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
73942         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
73943         return SQLITE_ERROR;
73944       }
73945     }else{
73946       pExpr->op = TK_STRING;
73947     }
73948   }
73949   return rc;
73950 }
73951
73952 /*
73953 ** An SQL user-function registered to do the work of an ATTACH statement. The
73954 ** three arguments to the function come directly from an attach statement:
73955 **
73956 **     ATTACH DATABASE x AS y KEY z
73957 **
73958 **     SELECT sqlite_attach(x, y, z)
73959 **
73960 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
73961 ** third argument.
73962 */
73963 static void attachFunc(
73964   sqlite3_context *context,
73965   int NotUsed,
73966   sqlite3_value **argv
73967 ){
73968   int i;
73969   int rc = 0;
73970   sqlite3 *db = sqlite3_context_db_handle(context);
73971   const char *zName;
73972   const char *zFile;
73973   Db *aNew;
73974   char *zErrDyn = 0;
73975
73976   UNUSED_PARAMETER(NotUsed);
73977
73978   zFile = (const char *)sqlite3_value_text(argv[0]);
73979   zName = (const char *)sqlite3_value_text(argv[1]);
73980   if( zFile==0 ) zFile = "";
73981   if( zName==0 ) zName = "";
73982
73983   /* Check for the following errors:
73984   **
73985   **     * Too many attached databases,
73986   **     * Transaction currently open
73987   **     * Specified database name already being used.
73988   */
73989   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
73990     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
73991       db->aLimit[SQLITE_LIMIT_ATTACHED]
73992     );
73993     goto attach_error;
73994   }
73995   if( !db->autoCommit ){
73996     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
73997     goto attach_error;
73998   }
73999   for(i=0; i<db->nDb; i++){
74000     char *z = db->aDb[i].zName;
74001     assert( z && zName );
74002     if( sqlite3StrICmp(z, zName)==0 ){
74003       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
74004       goto attach_error;
74005     }
74006   }
74007
74008   /* Allocate the new entry in the db->aDb[] array and initialise the schema
74009   ** hash tables.
74010   */
74011   if( db->aDb==db->aDbStatic ){
74012     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
74013     if( aNew==0 ) return;
74014     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
74015   }else{
74016     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
74017     if( aNew==0 ) return;
74018   }
74019   db->aDb = aNew;
74020   aNew = &db->aDb[db->nDb];
74021   memset(aNew, 0, sizeof(*aNew));
74022
74023   /* Open the database file. If the btree is successfully opened, use
74024   ** it to obtain the database schema. At this point the schema may
74025   ** or may not be initialised.
74026   */
74027   rc = sqlite3BtreeOpen(zFile, db, &aNew->pBt, 0,
74028                         db->openFlags | SQLITE_OPEN_MAIN_DB);
74029   db->nDb++;
74030   if( rc==SQLITE_CONSTRAINT ){
74031     rc = SQLITE_ERROR;
74032     zErrDyn = sqlite3MPrintf(db, "database is already attached");
74033   }else if( rc==SQLITE_OK ){
74034     Pager *pPager;
74035     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
74036     if( !aNew->pSchema ){
74037       rc = SQLITE_NOMEM;
74038     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
74039       zErrDyn = sqlite3MPrintf(db, 
74040         "attached databases must use the same text encoding as main database");
74041       rc = SQLITE_ERROR;
74042     }
74043     pPager = sqlite3BtreePager(aNew->pBt);
74044     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
74045     sqlite3BtreeSecureDelete(aNew->pBt,
74046                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
74047   }
74048   aNew->safety_level = 3;
74049   aNew->zName = sqlite3DbStrDup(db, zName);
74050   if( rc==SQLITE_OK && aNew->zName==0 ){
74051     rc = SQLITE_NOMEM;
74052   }
74053
74054
74055 #ifdef SQLITE_HAS_CODEC
74056   if( rc==SQLITE_OK ){
74057     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
74058     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
74059     int nKey;
74060     char *zKey;
74061     int t = sqlite3_value_type(argv[2]);
74062     switch( t ){
74063       case SQLITE_INTEGER:
74064       case SQLITE_FLOAT:
74065         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
74066         rc = SQLITE_ERROR;
74067         break;
74068         
74069       case SQLITE_TEXT:
74070       case SQLITE_BLOB:
74071         nKey = sqlite3_value_bytes(argv[2]);
74072         zKey = (char *)sqlite3_value_blob(argv[2]);
74073         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
74074         break;
74075
74076       case SQLITE_NULL:
74077         /* No key specified.  Use the key from the main database */
74078         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
74079         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
74080         break;
74081     }
74082   }
74083 #endif
74084
74085   /* If the file was opened successfully, read the schema for the new database.
74086   ** If this fails, or if opening the file failed, then close the file and 
74087   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
74088   ** we found it.
74089   */
74090   if( rc==SQLITE_OK ){
74091     sqlite3BtreeEnterAll(db);
74092     rc = sqlite3Init(db, &zErrDyn);
74093     sqlite3BtreeLeaveAll(db);
74094   }
74095   if( rc ){
74096     int iDb = db->nDb - 1;
74097     assert( iDb>=2 );
74098     if( db->aDb[iDb].pBt ){
74099       sqlite3BtreeClose(db->aDb[iDb].pBt);
74100       db->aDb[iDb].pBt = 0;
74101       db->aDb[iDb].pSchema = 0;
74102     }
74103     sqlite3ResetInternalSchema(db, 0);
74104     db->nDb = iDb;
74105     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
74106       db->mallocFailed = 1;
74107       sqlite3DbFree(db, zErrDyn);
74108       zErrDyn = sqlite3MPrintf(db, "out of memory");
74109     }else if( zErrDyn==0 ){
74110       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
74111     }
74112     goto attach_error;
74113   }
74114   
74115   return;
74116
74117 attach_error:
74118   /* Return an error if we get here */
74119   if( zErrDyn ){
74120     sqlite3_result_error(context, zErrDyn, -1);
74121     sqlite3DbFree(db, zErrDyn);
74122   }
74123   if( rc ) sqlite3_result_error_code(context, rc);
74124 }
74125
74126 /*
74127 ** An SQL user-function registered to do the work of an DETACH statement. The
74128 ** three arguments to the function come directly from a detach statement:
74129 **
74130 **     DETACH DATABASE x
74131 **
74132 **     SELECT sqlite_detach(x)
74133 */
74134 static void detachFunc(
74135   sqlite3_context *context,
74136   int NotUsed,
74137   sqlite3_value **argv
74138 ){
74139   const char *zName = (const char *)sqlite3_value_text(argv[0]);
74140   sqlite3 *db = sqlite3_context_db_handle(context);
74141   int i;
74142   Db *pDb = 0;
74143   char zErr[128];
74144
74145   UNUSED_PARAMETER(NotUsed);
74146
74147   if( zName==0 ) zName = "";
74148   for(i=0; i<db->nDb; i++){
74149     pDb = &db->aDb[i];
74150     if( pDb->pBt==0 ) continue;
74151     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
74152   }
74153
74154   if( i>=db->nDb ){
74155     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
74156     goto detach_error;
74157   }
74158   if( i<2 ){
74159     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
74160     goto detach_error;
74161   }
74162   if( !db->autoCommit ){
74163     sqlite3_snprintf(sizeof(zErr), zErr,
74164                      "cannot DETACH database within transaction");
74165     goto detach_error;
74166   }
74167   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
74168     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
74169     goto detach_error;
74170   }
74171
74172   sqlite3BtreeClose(pDb->pBt);
74173   pDb->pBt = 0;
74174   pDb->pSchema = 0;
74175   sqlite3ResetInternalSchema(db, 0);
74176   return;
74177
74178 detach_error:
74179   sqlite3_result_error(context, zErr, -1);
74180 }
74181
74182 /*
74183 ** This procedure generates VDBE code for a single invocation of either the
74184 ** sqlite_detach() or sqlite_attach() SQL user functions.
74185 */
74186 static void codeAttach(
74187   Parse *pParse,       /* The parser context */
74188   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
74189   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
74190   Expr *pAuthArg,      /* Expression to pass to authorization callback */
74191   Expr *pFilename,     /* Name of database file */
74192   Expr *pDbname,       /* Name of the database to use internally */
74193   Expr *pKey           /* Database key for encryption extension */
74194 ){
74195   int rc;
74196   NameContext sName;
74197   Vdbe *v;
74198   sqlite3* db = pParse->db;
74199   int regArgs;
74200
74201   memset(&sName, 0, sizeof(NameContext));
74202   sName.pParse = pParse;
74203
74204   if( 
74205       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
74206       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
74207       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
74208   ){
74209     pParse->nErr++;
74210     goto attach_end;
74211   }
74212
74213 #ifndef SQLITE_OMIT_AUTHORIZATION
74214   if( pAuthArg ){
74215     char *zAuthArg = pAuthArg->u.zToken;
74216     if( NEVER(zAuthArg==0) ){
74217       goto attach_end;
74218     }
74219     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
74220     if(rc!=SQLITE_OK ){
74221       goto attach_end;
74222     }
74223   }
74224 #endif /* SQLITE_OMIT_AUTHORIZATION */
74225
74226
74227   v = sqlite3GetVdbe(pParse);
74228   regArgs = sqlite3GetTempRange(pParse, 4);
74229   sqlite3ExprCode(pParse, pFilename, regArgs);
74230   sqlite3ExprCode(pParse, pDbname, regArgs+1);
74231   sqlite3ExprCode(pParse, pKey, regArgs+2);
74232
74233   assert( v || db->mallocFailed );
74234   if( v ){
74235     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
74236     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
74237     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
74238     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
74239
74240     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
74241     ** statement only). For DETACH, set it to false (expire all existing
74242     ** statements).
74243     */
74244     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
74245   }
74246   
74247 attach_end:
74248   sqlite3ExprDelete(db, pFilename);
74249   sqlite3ExprDelete(db, pDbname);
74250   sqlite3ExprDelete(db, pKey);
74251 }
74252
74253 /*
74254 ** Called by the parser to compile a DETACH statement.
74255 **
74256 **     DETACH pDbname
74257 */
74258 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
74259   static const FuncDef detach_func = {
74260     1,                /* nArg */
74261     SQLITE_UTF8,      /* iPrefEnc */
74262     0,                /* flags */
74263     0,                /* pUserData */
74264     0,                /* pNext */
74265     detachFunc,       /* xFunc */
74266     0,                /* xStep */
74267     0,                /* xFinalize */
74268     "sqlite_detach",  /* zName */
74269     0,                /* pHash */
74270     0                 /* pDestructor */
74271   };
74272   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
74273 }
74274
74275 /*
74276 ** Called by the parser to compile an ATTACH statement.
74277 **
74278 **     ATTACH p AS pDbname KEY pKey
74279 */
74280 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
74281   static const FuncDef attach_func = {
74282     3,                /* nArg */
74283     SQLITE_UTF8,      /* iPrefEnc */
74284     0,                /* flags */
74285     0,                /* pUserData */
74286     0,                /* pNext */
74287     attachFunc,       /* xFunc */
74288     0,                /* xStep */
74289     0,                /* xFinalize */
74290     "sqlite_attach",  /* zName */
74291     0,                /* pHash */
74292     0                 /* pDestructor */
74293   };
74294   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
74295 }
74296 #endif /* SQLITE_OMIT_ATTACH */
74297
74298 /*
74299 ** Initialize a DbFixer structure.  This routine must be called prior
74300 ** to passing the structure to one of the sqliteFixAAAA() routines below.
74301 **
74302 ** The return value indicates whether or not fixation is required.  TRUE
74303 ** means we do need to fix the database references, FALSE means we do not.
74304 */
74305 SQLITE_PRIVATE int sqlite3FixInit(
74306   DbFixer *pFix,      /* The fixer to be initialized */
74307   Parse *pParse,      /* Error messages will be written here */
74308   int iDb,            /* This is the database that must be used */
74309   const char *zType,  /* "view", "trigger", or "index" */
74310   const Token *pName  /* Name of the view, trigger, or index */
74311 ){
74312   sqlite3 *db;
74313
74314   if( NEVER(iDb<0) || iDb==1 ) return 0;
74315   db = pParse->db;
74316   assert( db->nDb>iDb );
74317   pFix->pParse = pParse;
74318   pFix->zDb = db->aDb[iDb].zName;
74319   pFix->zType = zType;
74320   pFix->pName = pName;
74321   return 1;
74322 }
74323
74324 /*
74325 ** The following set of routines walk through the parse tree and assign
74326 ** a specific database to all table references where the database name
74327 ** was left unspecified in the original SQL statement.  The pFix structure
74328 ** must have been initialized by a prior call to sqlite3FixInit().
74329 **
74330 ** These routines are used to make sure that an index, trigger, or
74331 ** view in one database does not refer to objects in a different database.
74332 ** (Exception: indices, triggers, and views in the TEMP database are
74333 ** allowed to refer to anything.)  If a reference is explicitly made
74334 ** to an object in a different database, an error message is added to
74335 ** pParse->zErrMsg and these routines return non-zero.  If everything
74336 ** checks out, these routines return 0.
74337 */
74338 SQLITE_PRIVATE int sqlite3FixSrcList(
74339   DbFixer *pFix,       /* Context of the fixation */
74340   SrcList *pList       /* The Source list to check and modify */
74341 ){
74342   int i;
74343   const char *zDb;
74344   struct SrcList_item *pItem;
74345
74346   if( NEVER(pList==0) ) return 0;
74347   zDb = pFix->zDb;
74348   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
74349     if( pItem->zDatabase==0 ){
74350       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
74351     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
74352       sqlite3ErrorMsg(pFix->pParse,
74353          "%s %T cannot reference objects in database %s",
74354          pFix->zType, pFix->pName, pItem->zDatabase);
74355       return 1;
74356     }
74357 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
74358     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
74359     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
74360 #endif
74361   }
74362   return 0;
74363 }
74364 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
74365 SQLITE_PRIVATE int sqlite3FixSelect(
74366   DbFixer *pFix,       /* Context of the fixation */
74367   Select *pSelect      /* The SELECT statement to be fixed to one database */
74368 ){
74369   while( pSelect ){
74370     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
74371       return 1;
74372     }
74373     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
74374       return 1;
74375     }
74376     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
74377       return 1;
74378     }
74379     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
74380       return 1;
74381     }
74382     pSelect = pSelect->pPrior;
74383   }
74384   return 0;
74385 }
74386 SQLITE_PRIVATE int sqlite3FixExpr(
74387   DbFixer *pFix,     /* Context of the fixation */
74388   Expr *pExpr        /* The expression to be fixed to one database */
74389 ){
74390   while( pExpr ){
74391     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
74392     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74393       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
74394     }else{
74395       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
74396     }
74397     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
74398       return 1;
74399     }
74400     pExpr = pExpr->pLeft;
74401   }
74402   return 0;
74403 }
74404 SQLITE_PRIVATE int sqlite3FixExprList(
74405   DbFixer *pFix,     /* Context of the fixation */
74406   ExprList *pList    /* The expression to be fixed to one database */
74407 ){
74408   int i;
74409   struct ExprList_item *pItem;
74410   if( pList==0 ) return 0;
74411   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
74412     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
74413       return 1;
74414     }
74415   }
74416   return 0;
74417 }
74418 #endif
74419
74420 #ifndef SQLITE_OMIT_TRIGGER
74421 SQLITE_PRIVATE int sqlite3FixTriggerStep(
74422   DbFixer *pFix,     /* Context of the fixation */
74423   TriggerStep *pStep /* The trigger step be fixed to one database */
74424 ){
74425   while( pStep ){
74426     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
74427       return 1;
74428     }
74429     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
74430       return 1;
74431     }
74432     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
74433       return 1;
74434     }
74435     pStep = pStep->pNext;
74436   }
74437   return 0;
74438 }
74439 #endif
74440
74441 /************** End of attach.c **********************************************/
74442 /************** Begin file auth.c ********************************************/
74443 /*
74444 ** 2003 January 11
74445 **
74446 ** The author disclaims copyright to this source code.  In place of
74447 ** a legal notice, here is a blessing:
74448 **
74449 **    May you do good and not evil.
74450 **    May you find forgiveness for yourself and forgive others.
74451 **    May you share freely, never taking more than you give.
74452 **
74453 *************************************************************************
74454 ** This file contains code used to implement the sqlite3_set_authorizer()
74455 ** API.  This facility is an optional feature of the library.  Embedded
74456 ** systems that do not need this facility may omit it by recompiling
74457 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
74458 */
74459
74460 /*
74461 ** All of the code in this file may be omitted by defining a single
74462 ** macro.
74463 */
74464 #ifndef SQLITE_OMIT_AUTHORIZATION
74465
74466 /*
74467 ** Set or clear the access authorization function.
74468 **
74469 ** The access authorization function is be called during the compilation
74470 ** phase to verify that the user has read and/or write access permission on
74471 ** various fields of the database.  The first argument to the auth function
74472 ** is a copy of the 3rd argument to this routine.  The second argument
74473 ** to the auth function is one of these constants:
74474 **
74475 **       SQLITE_CREATE_INDEX
74476 **       SQLITE_CREATE_TABLE
74477 **       SQLITE_CREATE_TEMP_INDEX
74478 **       SQLITE_CREATE_TEMP_TABLE
74479 **       SQLITE_CREATE_TEMP_TRIGGER
74480 **       SQLITE_CREATE_TEMP_VIEW
74481 **       SQLITE_CREATE_TRIGGER
74482 **       SQLITE_CREATE_VIEW
74483 **       SQLITE_DELETE
74484 **       SQLITE_DROP_INDEX
74485 **       SQLITE_DROP_TABLE
74486 **       SQLITE_DROP_TEMP_INDEX
74487 **       SQLITE_DROP_TEMP_TABLE
74488 **       SQLITE_DROP_TEMP_TRIGGER
74489 **       SQLITE_DROP_TEMP_VIEW
74490 **       SQLITE_DROP_TRIGGER
74491 **       SQLITE_DROP_VIEW
74492 **       SQLITE_INSERT
74493 **       SQLITE_PRAGMA
74494 **       SQLITE_READ
74495 **       SQLITE_SELECT
74496 **       SQLITE_TRANSACTION
74497 **       SQLITE_UPDATE
74498 **
74499 ** The third and fourth arguments to the auth function are the name of
74500 ** the table and the column that are being accessed.  The auth function
74501 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
74502 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
74503 ** means that the SQL statement will never-run - the sqlite3_exec() call
74504 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
74505 ** should run but attempts to read the specified column will return NULL
74506 ** and attempts to write the column will be ignored.
74507 **
74508 ** Setting the auth function to NULL disables this hook.  The default
74509 ** setting of the auth function is NULL.
74510 */
74511 SQLITE_API int sqlite3_set_authorizer(
74512   sqlite3 *db,
74513   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
74514   void *pArg
74515 ){
74516   sqlite3_mutex_enter(db->mutex);
74517   db->xAuth = xAuth;
74518   db->pAuthArg = pArg;
74519   sqlite3ExpirePreparedStatements(db);
74520   sqlite3_mutex_leave(db->mutex);
74521   return SQLITE_OK;
74522 }
74523
74524 /*
74525 ** Write an error message into pParse->zErrMsg that explains that the
74526 ** user-supplied authorization function returned an illegal value.
74527 */
74528 static void sqliteAuthBadReturnCode(Parse *pParse){
74529   sqlite3ErrorMsg(pParse, "authorizer malfunction");
74530   pParse->rc = SQLITE_ERROR;
74531 }
74532
74533 /*
74534 ** Invoke the authorization callback for permission to read column zCol from
74535 ** table zTab in database zDb. This function assumes that an authorization
74536 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
74537 **
74538 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
74539 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
74540 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
74541 */
74542 SQLITE_PRIVATE int sqlite3AuthReadCol(
74543   Parse *pParse,                  /* The parser context */
74544   const char *zTab,               /* Table name */
74545   const char *zCol,               /* Column name */
74546   int iDb                         /* Index of containing database. */
74547 ){
74548   sqlite3 *db = pParse->db;       /* Database handle */
74549   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
74550   int rc;                         /* Auth callback return code */
74551
74552   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
74553   if( rc==SQLITE_DENY ){
74554     if( db->nDb>2 || iDb!=0 ){
74555       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
74556     }else{
74557       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
74558     }
74559     pParse->rc = SQLITE_AUTH;
74560   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
74561     sqliteAuthBadReturnCode(pParse);
74562   }
74563   return rc;
74564 }
74565
74566 /*
74567 ** The pExpr should be a TK_COLUMN expression.  The table referred to
74568 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
74569 ** Check to see if it is OK to read this particular column.
74570 **
74571 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
74572 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
74573 ** then generate an error.
74574 */
74575 SQLITE_PRIVATE void sqlite3AuthRead(
74576   Parse *pParse,        /* The parser context */
74577   Expr *pExpr,          /* The expression to check authorization on */
74578   Schema *pSchema,      /* The schema of the expression */
74579   SrcList *pTabList     /* All table that pExpr might refer to */
74580 ){
74581   sqlite3 *db = pParse->db;
74582   Table *pTab = 0;      /* The table being read */
74583   const char *zCol;     /* Name of the column of the table */
74584   int iSrc;             /* Index in pTabList->a[] of table being read */
74585   int iDb;              /* The index of the database the expression refers to */
74586   int iCol;             /* Index of column in table */
74587
74588   if( db->xAuth==0 ) return;
74589   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
74590   if( iDb<0 ){
74591     /* An attempt to read a column out of a subquery or other
74592     ** temporary table. */
74593     return;
74594   }
74595
74596   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
74597   if( pExpr->op==TK_TRIGGER ){
74598     pTab = pParse->pTriggerTab;
74599   }else{
74600     assert( pTabList );
74601     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
74602       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
74603         pTab = pTabList->a[iSrc].pTab;
74604         break;
74605       }
74606     }
74607   }
74608   iCol = pExpr->iColumn;
74609   if( NEVER(pTab==0) ) return;
74610
74611   if( iCol>=0 ){
74612     assert( iCol<pTab->nCol );
74613     zCol = pTab->aCol[iCol].zName;
74614   }else if( pTab->iPKey>=0 ){
74615     assert( pTab->iPKey<pTab->nCol );
74616     zCol = pTab->aCol[pTab->iPKey].zName;
74617   }else{
74618     zCol = "ROWID";
74619   }
74620   assert( iDb>=0 && iDb<db->nDb );
74621   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
74622     pExpr->op = TK_NULL;
74623   }
74624 }
74625
74626 /*
74627 ** Do an authorization check using the code and arguments given.  Return
74628 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
74629 ** is returned, then the error count and error message in pParse are
74630 ** modified appropriately.
74631 */
74632 SQLITE_PRIVATE int sqlite3AuthCheck(
74633   Parse *pParse,
74634   int code,
74635   const char *zArg1,
74636   const char *zArg2,
74637   const char *zArg3
74638 ){
74639   sqlite3 *db = pParse->db;
74640   int rc;
74641
74642   /* Don't do any authorization checks if the database is initialising
74643   ** or if the parser is being invoked from within sqlite3_declare_vtab.
74644   */
74645   if( db->init.busy || IN_DECLARE_VTAB ){
74646     return SQLITE_OK;
74647   }
74648
74649   if( db->xAuth==0 ){
74650     return SQLITE_OK;
74651   }
74652   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
74653   if( rc==SQLITE_DENY ){
74654     sqlite3ErrorMsg(pParse, "not authorized");
74655     pParse->rc = SQLITE_AUTH;
74656   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
74657     rc = SQLITE_DENY;
74658     sqliteAuthBadReturnCode(pParse);
74659   }
74660   return rc;
74661 }
74662
74663 /*
74664 ** Push an authorization context.  After this routine is called, the
74665 ** zArg3 argument to authorization callbacks will be zContext until
74666 ** popped.  Or if pParse==0, this routine is a no-op.
74667 */
74668 SQLITE_PRIVATE void sqlite3AuthContextPush(
74669   Parse *pParse,
74670   AuthContext *pContext, 
74671   const char *zContext
74672 ){
74673   assert( pParse );
74674   pContext->pParse = pParse;
74675   pContext->zAuthContext = pParse->zAuthContext;
74676   pParse->zAuthContext = zContext;
74677 }
74678
74679 /*
74680 ** Pop an authorization context that was previously pushed
74681 ** by sqlite3AuthContextPush
74682 */
74683 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
74684   if( pContext->pParse ){
74685     pContext->pParse->zAuthContext = pContext->zAuthContext;
74686     pContext->pParse = 0;
74687   }
74688 }
74689
74690 #endif /* SQLITE_OMIT_AUTHORIZATION */
74691
74692 /************** End of auth.c ************************************************/
74693 /************** Begin file build.c *******************************************/
74694 /*
74695 ** 2001 September 15
74696 **
74697 ** The author disclaims copyright to this source code.  In place of
74698 ** a legal notice, here is a blessing:
74699 **
74700 **    May you do good and not evil.
74701 **    May you find forgiveness for yourself and forgive others.
74702 **    May you share freely, never taking more than you give.
74703 **
74704 *************************************************************************
74705 ** This file contains C code routines that are called by the SQLite parser
74706 ** when syntax rules are reduced.  The routines in this file handle the
74707 ** following kinds of SQL syntax:
74708 **
74709 **     CREATE TABLE
74710 **     DROP TABLE
74711 **     CREATE INDEX
74712 **     DROP INDEX
74713 **     creating ID lists
74714 **     BEGIN TRANSACTION
74715 **     COMMIT
74716 **     ROLLBACK
74717 */
74718
74719 /*
74720 ** This routine is called when a new SQL statement is beginning to
74721 ** be parsed.  Initialize the pParse structure as needed.
74722 */
74723 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
74724   pParse->explain = (u8)explainFlag;
74725   pParse->nVar = 0;
74726 }
74727
74728 #ifndef SQLITE_OMIT_SHARED_CACHE
74729 /*
74730 ** The TableLock structure is only used by the sqlite3TableLock() and
74731 ** codeTableLocks() functions.
74732 */
74733 struct TableLock {
74734   int iDb;             /* The database containing the table to be locked */
74735   int iTab;            /* The root page of the table to be locked */
74736   u8 isWriteLock;      /* True for write lock.  False for a read lock */
74737   const char *zName;   /* Name of the table */
74738 };
74739
74740 /*
74741 ** Record the fact that we want to lock a table at run-time.  
74742 **
74743 ** The table to be locked has root page iTab and is found in database iDb.
74744 ** A read or a write lock can be taken depending on isWritelock.
74745 **
74746 ** This routine just records the fact that the lock is desired.  The
74747 ** code to make the lock occur is generated by a later call to
74748 ** codeTableLocks() which occurs during sqlite3FinishCoding().
74749 */
74750 SQLITE_PRIVATE void sqlite3TableLock(
74751   Parse *pParse,     /* Parsing context */
74752   int iDb,           /* Index of the database containing the table to lock */
74753   int iTab,          /* Root page number of the table to be locked */
74754   u8 isWriteLock,    /* True for a write lock */
74755   const char *zName  /* Name of the table to be locked */
74756 ){
74757   Parse *pToplevel = sqlite3ParseToplevel(pParse);
74758   int i;
74759   int nBytes;
74760   TableLock *p;
74761   assert( iDb>=0 );
74762
74763   for(i=0; i<pToplevel->nTableLock; i++){
74764     p = &pToplevel->aTableLock[i];
74765     if( p->iDb==iDb && p->iTab==iTab ){
74766       p->isWriteLock = (p->isWriteLock || isWriteLock);
74767       return;
74768     }
74769   }
74770
74771   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
74772   pToplevel->aTableLock =
74773       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
74774   if( pToplevel->aTableLock ){
74775     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
74776     p->iDb = iDb;
74777     p->iTab = iTab;
74778     p->isWriteLock = isWriteLock;
74779     p->zName = zName;
74780   }else{
74781     pToplevel->nTableLock = 0;
74782     pToplevel->db->mallocFailed = 1;
74783   }
74784 }
74785
74786 /*
74787 ** Code an OP_TableLock instruction for each table locked by the
74788 ** statement (configured by calls to sqlite3TableLock()).
74789 */
74790 static void codeTableLocks(Parse *pParse){
74791   int i;
74792   Vdbe *pVdbe; 
74793
74794   pVdbe = sqlite3GetVdbe(pParse);
74795   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
74796
74797   for(i=0; i<pParse->nTableLock; i++){
74798     TableLock *p = &pParse->aTableLock[i];
74799     int p1 = p->iDb;
74800     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
74801                       p->zName, P4_STATIC);
74802   }
74803 }
74804 #else
74805   #define codeTableLocks(x)
74806 #endif
74807
74808 /*
74809 ** This routine is called after a single SQL statement has been
74810 ** parsed and a VDBE program to execute that statement has been
74811 ** prepared.  This routine puts the finishing touches on the
74812 ** VDBE program and resets the pParse structure for the next
74813 ** parse.
74814 **
74815 ** Note that if an error occurred, it might be the case that
74816 ** no VDBE code was generated.
74817 */
74818 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
74819   sqlite3 *db;
74820   Vdbe *v;
74821
74822   db = pParse->db;
74823   if( db->mallocFailed ) return;
74824   if( pParse->nested ) return;
74825   if( pParse->nErr ) return;
74826
74827   /* Begin by generating some termination code at the end of the
74828   ** vdbe program
74829   */
74830   v = sqlite3GetVdbe(pParse);
74831   assert( !pParse->isMultiWrite 
74832        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
74833   if( v ){
74834     sqlite3VdbeAddOp0(v, OP_Halt);
74835
74836     /* The cookie mask contains one bit for each database file open.
74837     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
74838     ** set for each database that is used.  Generate code to start a
74839     ** transaction on each used database and to verify the schema cookie
74840     ** on each used database.
74841     */
74842     if( pParse->cookieGoto>0 ){
74843       u32 mask;
74844       int iDb;
74845       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
74846       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
74847         if( (mask & pParse->cookieMask)==0 ) continue;
74848         sqlite3VdbeUsesBtree(v, iDb);
74849         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
74850         if( db->init.busy==0 ){
74851           sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
74852         }
74853       }
74854 #ifndef SQLITE_OMIT_VIRTUALTABLE
74855       {
74856         int i;
74857         for(i=0; i<pParse->nVtabLock; i++){
74858           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
74859           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
74860         }
74861         pParse->nVtabLock = 0;
74862       }
74863 #endif
74864
74865       /* Once all the cookies have been verified and transactions opened, 
74866       ** obtain the required table-locks. This is a no-op unless the 
74867       ** shared-cache feature is enabled.
74868       */
74869       codeTableLocks(pParse);
74870
74871       /* Initialize any AUTOINCREMENT data structures required.
74872       */
74873       sqlite3AutoincrementBegin(pParse);
74874
74875       /* Finally, jump back to the beginning of the executable code. */
74876       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
74877     }
74878   }
74879
74880
74881   /* Get the VDBE program ready for execution
74882   */
74883   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
74884 #ifdef SQLITE_DEBUG
74885     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
74886     sqlite3VdbeTrace(v, trace);
74887 #endif
74888     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
74889     /* A minimum of one cursor is required if autoincrement is used
74890     *  See ticket [a696379c1f08866] */
74891     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
74892     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
74893                          pParse->nTab, pParse->nMaxArg, pParse->explain,
74894                          pParse->isMultiWrite && pParse->mayAbort);
74895     pParse->rc = SQLITE_DONE;
74896     pParse->colNamesSet = 0;
74897   }else{
74898     pParse->rc = SQLITE_ERROR;
74899   }
74900   pParse->nTab = 0;
74901   pParse->nMem = 0;
74902   pParse->nSet = 0;
74903   pParse->nVar = 0;
74904   pParse->cookieMask = 0;
74905   pParse->cookieGoto = 0;
74906 }
74907
74908 /*
74909 ** Run the parser and code generator recursively in order to generate
74910 ** code for the SQL statement given onto the end of the pParse context
74911 ** currently under construction.  When the parser is run recursively
74912 ** this way, the final OP_Halt is not appended and other initialization
74913 ** and finalization steps are omitted because those are handling by the
74914 ** outermost parser.
74915 **
74916 ** Not everything is nestable.  This facility is designed to permit
74917 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
74918 ** care if you decide to try to use this routine for some other purposes.
74919 */
74920 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
74921   va_list ap;
74922   char *zSql;
74923   char *zErrMsg = 0;
74924   sqlite3 *db = pParse->db;
74925 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
74926   char saveBuf[SAVE_SZ];
74927
74928   if( pParse->nErr ) return;
74929   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
74930   va_start(ap, zFormat);
74931   zSql = sqlite3VMPrintf(db, zFormat, ap);
74932   va_end(ap);
74933   if( zSql==0 ){
74934     return;   /* A malloc must have failed */
74935   }
74936   pParse->nested++;
74937   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
74938   memset(&pParse->nVar, 0, SAVE_SZ);
74939   sqlite3RunParser(pParse, zSql, &zErrMsg);
74940   sqlite3DbFree(db, zErrMsg);
74941   sqlite3DbFree(db, zSql);
74942   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
74943   pParse->nested--;
74944 }
74945
74946 /*
74947 ** Locate the in-memory structure that describes a particular database
74948 ** table given the name of that table and (optionally) the name of the
74949 ** database containing the table.  Return NULL if not found.
74950 **
74951 ** If zDatabase is 0, all databases are searched for the table and the
74952 ** first matching table is returned.  (No checking for duplicate table
74953 ** names is done.)  The search order is TEMP first, then MAIN, then any
74954 ** auxiliary databases added using the ATTACH command.
74955 **
74956 ** See also sqlite3LocateTable().
74957 */
74958 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
74959   Table *p = 0;
74960   int i;
74961   int nName;
74962   assert( zName!=0 );
74963   nName = sqlite3Strlen30(zName);
74964   for(i=OMIT_TEMPDB; i<db->nDb; i++){
74965     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
74966     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
74967     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
74968     if( p ) break;
74969   }
74970   return p;
74971 }
74972
74973 /*
74974 ** Locate the in-memory structure that describes a particular database
74975 ** table given the name of that table and (optionally) the name of the
74976 ** database containing the table.  Return NULL if not found.  Also leave an
74977 ** error message in pParse->zErrMsg.
74978 **
74979 ** The difference between this routine and sqlite3FindTable() is that this
74980 ** routine leaves an error message in pParse->zErrMsg where
74981 ** sqlite3FindTable() does not.
74982 */
74983 SQLITE_PRIVATE Table *sqlite3LocateTable(
74984   Parse *pParse,         /* context in which to report errors */
74985   int isView,            /* True if looking for a VIEW rather than a TABLE */
74986   const char *zName,     /* Name of the table we are looking for */
74987   const char *zDbase     /* Name of the database.  Might be NULL */
74988 ){
74989   Table *p;
74990
74991   /* Read the database schema. If an error occurs, leave an error message
74992   ** and code in pParse and return NULL. */
74993   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
74994     return 0;
74995   }
74996
74997   p = sqlite3FindTable(pParse->db, zName, zDbase);
74998   if( p==0 ){
74999     const char *zMsg = isView ? "no such view" : "no such table";
75000     if( zDbase ){
75001       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
75002     }else{
75003       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
75004     }
75005     pParse->checkSchema = 1;
75006   }
75007   return p;
75008 }
75009
75010 /*
75011 ** Locate the in-memory structure that describes 
75012 ** a particular index given the name of that index
75013 ** and the name of the database that contains the index.
75014 ** Return NULL if not found.
75015 **
75016 ** If zDatabase is 0, all databases are searched for the
75017 ** table and the first matching index is returned.  (No checking
75018 ** for duplicate index names is done.)  The search order is
75019 ** TEMP first, then MAIN, then any auxiliary databases added
75020 ** using the ATTACH command.
75021 */
75022 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
75023   Index *p = 0;
75024   int i;
75025   int nName = sqlite3Strlen30(zName);
75026   for(i=OMIT_TEMPDB; i<db->nDb; i++){
75027     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
75028     Schema *pSchema = db->aDb[j].pSchema;
75029     assert( pSchema );
75030     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
75031     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
75032     if( p ) break;
75033   }
75034   return p;
75035 }
75036
75037 /*
75038 ** Reclaim the memory used by an index
75039 */
75040 static void freeIndex(sqlite3 *db, Index *p){
75041 #ifndef SQLITE_OMIT_ANALYZE
75042   sqlite3DeleteIndexSamples(db, p);
75043 #endif
75044   sqlite3DbFree(db, p->zColAff);
75045   sqlite3DbFree(db, p);
75046 }
75047
75048 /*
75049 ** For the index called zIdxName which is found in the database iDb,
75050 ** unlike that index from its Table then remove the index from
75051 ** the index hash table and free all memory structures associated
75052 ** with the index.
75053 */
75054 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
75055   Index *pIndex;
75056   int len;
75057   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
75058
75059   len = sqlite3Strlen30(zIdxName);
75060   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
75061   if( pIndex ){
75062     if( pIndex->pTable->pIndex==pIndex ){
75063       pIndex->pTable->pIndex = pIndex->pNext;
75064     }else{
75065       Index *p;
75066       /* Justification of ALWAYS();  The index must be on the list of
75067       ** indices. */
75068       p = pIndex->pTable->pIndex;
75069       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
75070       if( ALWAYS(p && p->pNext==pIndex) ){
75071         p->pNext = pIndex->pNext;
75072       }
75073     }
75074     freeIndex(db, pIndex);
75075   }
75076   db->flags |= SQLITE_InternChanges;
75077 }
75078
75079 /*
75080 ** Erase all schema information from the in-memory hash tables of
75081 ** a single database.  This routine is called to reclaim memory
75082 ** before the database closes.  It is also called during a rollback
75083 ** if there were schema changes during the transaction or if a
75084 ** schema-cookie mismatch occurs.
75085 **
75086 ** If iDb==0 then reset the internal schema tables for all database
75087 ** files.  If iDb>=1 then reset the internal schema for only the
75088 ** single file indicated.
75089 */
75090 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
75091   int i, j;
75092   assert( iDb>=0 && iDb<db->nDb );
75093
75094   if( iDb==0 ){
75095     sqlite3BtreeEnterAll(db);
75096   }
75097   for(i=iDb; i<db->nDb; i++){
75098     Db *pDb = &db->aDb[i];
75099     if( pDb->pSchema ){
75100       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
75101       sqlite3SchemaFree(pDb->pSchema);
75102     }
75103     if( iDb>0 ) return;
75104   }
75105   assert( iDb==0 );
75106   db->flags &= ~SQLITE_InternChanges;
75107   sqlite3VtabUnlockList(db);
75108   sqlite3BtreeLeaveAll(db);
75109
75110   /* If one or more of the auxiliary database files has been closed,
75111   ** then remove them from the auxiliary database list.  We take the
75112   ** opportunity to do this here since we have just deleted all of the
75113   ** schema hash tables and therefore do not have to make any changes
75114   ** to any of those tables.
75115   */
75116   for(i=j=2; i<db->nDb; i++){
75117     struct Db *pDb = &db->aDb[i];
75118     if( pDb->pBt==0 ){
75119       sqlite3DbFree(db, pDb->zName);
75120       pDb->zName = 0;
75121       continue;
75122     }
75123     if( j<i ){
75124       db->aDb[j] = db->aDb[i];
75125     }
75126     j++;
75127   }
75128   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
75129   db->nDb = j;
75130   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
75131     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
75132     sqlite3DbFree(db, db->aDb);
75133     db->aDb = db->aDbStatic;
75134   }
75135 }
75136
75137 /*
75138 ** This routine is called when a commit occurs.
75139 */
75140 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
75141   db->flags &= ~SQLITE_InternChanges;
75142 }
75143
75144 /*
75145 ** Delete memory allocated for the column names of a table or view (the
75146 ** Table.aCol[] array).
75147 */
75148 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
75149   int i;
75150   Column *pCol;
75151   assert( pTable!=0 );
75152   if( (pCol = pTable->aCol)!=0 ){
75153     for(i=0; i<pTable->nCol; i++, pCol++){
75154       sqlite3DbFree(db, pCol->zName);
75155       sqlite3ExprDelete(db, pCol->pDflt);
75156       sqlite3DbFree(db, pCol->zDflt);
75157       sqlite3DbFree(db, pCol->zType);
75158       sqlite3DbFree(db, pCol->zColl);
75159     }
75160     sqlite3DbFree(db, pTable->aCol);
75161   }
75162 }
75163
75164 /*
75165 ** Remove the memory data structures associated with the given
75166 ** Table.  No changes are made to disk by this routine.
75167 **
75168 ** This routine just deletes the data structure.  It does not unlink
75169 ** the table data structure from the hash table.  But it does destroy
75170 ** memory structures of the indices and foreign keys associated with 
75171 ** the table.
75172 */
75173 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
75174   Index *pIndex, *pNext;
75175
75176   assert( !pTable || pTable->nRef>0 );
75177
75178   /* Do not delete the table until the reference count reaches zero. */
75179   if( !pTable ) return;
75180   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
75181
75182   /* Delete all indices associated with this table. */
75183   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
75184     pNext = pIndex->pNext;
75185     assert( pIndex->pSchema==pTable->pSchema );
75186     if( !db || db->pnBytesFreed==0 ){
75187       char *zName = pIndex->zName; 
75188       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
75189           &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
75190       );
75191       assert( pOld==pIndex || pOld==0 );
75192     }
75193     freeIndex(db, pIndex);
75194   }
75195
75196   /* Delete any foreign keys attached to this table. */
75197   sqlite3FkDelete(db, pTable);
75198
75199   /* Delete the Table structure itself.
75200   */
75201   sqliteDeleteColumnNames(db, pTable);
75202   sqlite3DbFree(db, pTable->zName);
75203   sqlite3DbFree(db, pTable->zColAff);
75204   sqlite3SelectDelete(db, pTable->pSelect);
75205 #ifndef SQLITE_OMIT_CHECK
75206   sqlite3ExprDelete(db, pTable->pCheck);
75207 #endif
75208 #ifndef SQLITE_OMIT_VIRTUALTABLE
75209   sqlite3VtabClear(db, pTable);
75210 #endif
75211   sqlite3DbFree(db, pTable);
75212 }
75213
75214 /*
75215 ** Unlink the given table from the hash tables and the delete the
75216 ** table structure with all its indices and foreign keys.
75217 */
75218 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
75219   Table *p;
75220   Db *pDb;
75221
75222   assert( db!=0 );
75223   assert( iDb>=0 && iDb<db->nDb );
75224   assert( zTabName );
75225   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
75226   pDb = &db->aDb[iDb];
75227   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
75228                         sqlite3Strlen30(zTabName),0);
75229   sqlite3DeleteTable(db, p);
75230   db->flags |= SQLITE_InternChanges;
75231 }
75232
75233 /*
75234 ** Given a token, return a string that consists of the text of that
75235 ** token.  Space to hold the returned string
75236 ** is obtained from sqliteMalloc() and must be freed by the calling
75237 ** function.
75238 **
75239 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
75240 ** surround the body of the token are removed.
75241 **
75242 ** Tokens are often just pointers into the original SQL text and so
75243 ** are not \000 terminated and are not persistent.  The returned string
75244 ** is \000 terminated and is persistent.
75245 */
75246 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
75247   char *zName;
75248   if( pName ){
75249     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
75250     sqlite3Dequote(zName);
75251   }else{
75252     zName = 0;
75253   }
75254   return zName;
75255 }
75256
75257 /*
75258 ** Open the sqlite_master table stored in database number iDb for
75259 ** writing. The table is opened using cursor 0.
75260 */
75261 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
75262   Vdbe *v = sqlite3GetVdbe(p);
75263   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
75264   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
75265   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
75266   if( p->nTab==0 ){
75267     p->nTab = 1;
75268   }
75269 }
75270
75271 /*
75272 ** Parameter zName points to a nul-terminated buffer containing the name
75273 ** of a database ("main", "temp" or the name of an attached db). This
75274 ** function returns the index of the named database in db->aDb[], or
75275 ** -1 if the named db cannot be found.
75276 */
75277 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
75278   int i = -1;         /* Database number */
75279   if( zName ){
75280     Db *pDb;
75281     int n = sqlite3Strlen30(zName);
75282     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
75283       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
75284           0==sqlite3StrICmp(pDb->zName, zName) ){
75285         break;
75286       }
75287     }
75288   }
75289   return i;
75290 }
75291
75292 /*
75293 ** The token *pName contains the name of a database (either "main" or
75294 ** "temp" or the name of an attached db). This routine returns the
75295 ** index of the named database in db->aDb[], or -1 if the named db 
75296 ** does not exist.
75297 */
75298 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
75299   int i;                               /* Database number */
75300   char *zName;                         /* Name we are searching for */
75301   zName = sqlite3NameFromToken(db, pName);
75302   i = sqlite3FindDbName(db, zName);
75303   sqlite3DbFree(db, zName);
75304   return i;
75305 }
75306
75307 /* The table or view or trigger name is passed to this routine via tokens
75308 ** pName1 and pName2. If the table name was fully qualified, for example:
75309 **
75310 ** CREATE TABLE xxx.yyy (...);
75311 ** 
75312 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
75313 ** the table name is not fully qualified, i.e.:
75314 **
75315 ** CREATE TABLE yyy(...);
75316 **
75317 ** Then pName1 is set to "yyy" and pName2 is "".
75318 **
75319 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
75320 ** pName2) that stores the unqualified table name.  The index of the
75321 ** database "xxx" is returned.
75322 */
75323 SQLITE_PRIVATE int sqlite3TwoPartName(
75324   Parse *pParse,      /* Parsing and code generating context */
75325   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
75326   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
75327   Token **pUnqual     /* Write the unqualified object name here */
75328 ){
75329   int iDb;                    /* Database holding the object */
75330   sqlite3 *db = pParse->db;
75331
75332   if( ALWAYS(pName2!=0) && pName2->n>0 ){
75333     if( db->init.busy ) {
75334       sqlite3ErrorMsg(pParse, "corrupt database");
75335       pParse->nErr++;
75336       return -1;
75337     }
75338     *pUnqual = pName2;
75339     iDb = sqlite3FindDb(db, pName1);
75340     if( iDb<0 ){
75341       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
75342       pParse->nErr++;
75343       return -1;
75344     }
75345   }else{
75346     assert( db->init.iDb==0 || db->init.busy );
75347     iDb = db->init.iDb;
75348     *pUnqual = pName1;
75349   }
75350   return iDb;
75351 }
75352
75353 /*
75354 ** This routine is used to check if the UTF-8 string zName is a legal
75355 ** unqualified name for a new schema object (table, index, view or
75356 ** trigger). All names are legal except those that begin with the string
75357 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
75358 ** is reserved for internal use.
75359 */
75360 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
75361   if( !pParse->db->init.busy && pParse->nested==0 
75362           && (pParse->db->flags & SQLITE_WriteSchema)==0
75363           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
75364     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
75365     return SQLITE_ERROR;
75366   }
75367   return SQLITE_OK;
75368 }
75369
75370 /*
75371 ** Begin constructing a new table representation in memory.  This is
75372 ** the first of several action routines that get called in response
75373 ** to a CREATE TABLE statement.  In particular, this routine is called
75374 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
75375 ** flag is true if the table should be stored in the auxiliary database
75376 ** file instead of in the main database file.  This is normally the case
75377 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
75378 ** CREATE and TABLE.
75379 **
75380 ** The new table record is initialized and put in pParse->pNewTable.
75381 ** As more of the CREATE TABLE statement is parsed, additional action
75382 ** routines will be called to add more information to this record.
75383 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
75384 ** is called to complete the construction of the new table record.
75385 */
75386 SQLITE_PRIVATE void sqlite3StartTable(
75387   Parse *pParse,   /* Parser context */
75388   Token *pName1,   /* First part of the name of the table or view */
75389   Token *pName2,   /* Second part of the name of the table or view */
75390   int isTemp,      /* True if this is a TEMP table */
75391   int isView,      /* True if this is a VIEW */
75392   int isVirtual,   /* True if this is a VIRTUAL table */
75393   int noErr        /* Do nothing if table already exists */
75394 ){
75395   Table *pTable;
75396   char *zName = 0; /* The name of the new table */
75397   sqlite3 *db = pParse->db;
75398   Vdbe *v;
75399   int iDb;         /* Database number to create the table in */
75400   Token *pName;    /* Unqualified name of the table to create */
75401
75402   /* The table or view name to create is passed to this routine via tokens
75403   ** pName1 and pName2. If the table name was fully qualified, for example:
75404   **
75405   ** CREATE TABLE xxx.yyy (...);
75406   ** 
75407   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
75408   ** the table name is not fully qualified, i.e.:
75409   **
75410   ** CREATE TABLE yyy(...);
75411   **
75412   ** Then pName1 is set to "yyy" and pName2 is "".
75413   **
75414   ** The call below sets the pName pointer to point at the token (pName1 or
75415   ** pName2) that stores the unqualified table name. The variable iDb is
75416   ** set to the index of the database that the table or view is to be
75417   ** created in.
75418   */
75419   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
75420   if( iDb<0 ) return;
75421   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
75422     /* If creating a temp table, the name may not be qualified. Unless 
75423     ** the database name is "temp" anyway.  */
75424     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
75425     return;
75426   }
75427   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
75428
75429   pParse->sNameToken = *pName;
75430   zName = sqlite3NameFromToken(db, pName);
75431   if( zName==0 ) return;
75432   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
75433     goto begin_table_error;
75434   }
75435   if( db->init.iDb==1 ) isTemp = 1;
75436 #ifndef SQLITE_OMIT_AUTHORIZATION
75437   assert( (isTemp & 1)==isTemp );
75438   {
75439     int code;
75440     char *zDb = db->aDb[iDb].zName;
75441     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
75442       goto begin_table_error;
75443     }
75444     if( isView ){
75445       if( !OMIT_TEMPDB && isTemp ){
75446         code = SQLITE_CREATE_TEMP_VIEW;
75447       }else{
75448         code = SQLITE_CREATE_VIEW;
75449       }
75450     }else{
75451       if( !OMIT_TEMPDB && isTemp ){
75452         code = SQLITE_CREATE_TEMP_TABLE;
75453       }else{
75454         code = SQLITE_CREATE_TABLE;
75455       }
75456     }
75457     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
75458       goto begin_table_error;
75459     }
75460   }
75461 #endif
75462
75463   /* Make sure the new table name does not collide with an existing
75464   ** index or table name in the same database.  Issue an error message if
75465   ** it does. The exception is if the statement being parsed was passed
75466   ** to an sqlite3_declare_vtab() call. In that case only the column names
75467   ** and types will be used, so there is no need to test for namespace
75468   ** collisions.
75469   */
75470   if( !IN_DECLARE_VTAB ){
75471     char *zDb = db->aDb[iDb].zName;
75472     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
75473       goto begin_table_error;
75474     }
75475     pTable = sqlite3FindTable(db, zName, zDb);
75476     if( pTable ){
75477       if( !noErr ){
75478         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
75479       }
75480       goto begin_table_error;
75481     }
75482     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
75483       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
75484       goto begin_table_error;
75485     }
75486   }
75487
75488   pTable = sqlite3DbMallocZero(db, sizeof(Table));
75489   if( pTable==0 ){
75490     db->mallocFailed = 1;
75491     pParse->rc = SQLITE_NOMEM;
75492     pParse->nErr++;
75493     goto begin_table_error;
75494   }
75495   pTable->zName = zName;
75496   pTable->iPKey = -1;
75497   pTable->pSchema = db->aDb[iDb].pSchema;
75498   pTable->nRef = 1;
75499   pTable->nRowEst = 1000000;
75500   assert( pParse->pNewTable==0 );
75501   pParse->pNewTable = pTable;
75502
75503   /* If this is the magic sqlite_sequence table used by autoincrement,
75504   ** then record a pointer to this table in the main database structure
75505   ** so that INSERT can find the table easily.
75506   */
75507 #ifndef SQLITE_OMIT_AUTOINCREMENT
75508   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
75509     pTable->pSchema->pSeqTab = pTable;
75510   }
75511 #endif
75512
75513   /* Begin generating the code that will insert the table record into
75514   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
75515   ** and allocate the record number for the table entry now.  Before any
75516   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
75517   ** indices to be created and the table record must come before the 
75518   ** indices.  Hence, the record number for the table must be allocated
75519   ** now.
75520   */
75521   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
75522     int j1;
75523     int fileFormat;
75524     int reg1, reg2, reg3;
75525     sqlite3BeginWriteOperation(pParse, 0, iDb);
75526
75527 #ifndef SQLITE_OMIT_VIRTUALTABLE
75528     if( isVirtual ){
75529       sqlite3VdbeAddOp0(v, OP_VBegin);
75530     }
75531 #endif
75532
75533     /* If the file format and encoding in the database have not been set, 
75534     ** set them now.
75535     */
75536     reg1 = pParse->regRowid = ++pParse->nMem;
75537     reg2 = pParse->regRoot = ++pParse->nMem;
75538     reg3 = ++pParse->nMem;
75539     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
75540     sqlite3VdbeUsesBtree(v, iDb);
75541     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
75542     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
75543                   1 : SQLITE_MAX_FILE_FORMAT;
75544     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
75545     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
75546     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
75547     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
75548     sqlite3VdbeJumpHere(v, j1);
75549
75550     /* This just creates a place-holder record in the sqlite_master table.
75551     ** The record created does not contain anything yet.  It will be replaced
75552     ** by the real entry in code generated at sqlite3EndTable().
75553     **
75554     ** The rowid for the new entry is left in register pParse->regRowid.
75555     ** The root page number of the new table is left in reg pParse->regRoot.
75556     ** The rowid and root page number values are needed by the code that
75557     ** sqlite3EndTable will generate.
75558     */
75559 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
75560     if( isView || isVirtual ){
75561       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
75562     }else
75563 #endif
75564     {
75565       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
75566     }
75567     sqlite3OpenMasterTable(pParse, iDb);
75568     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
75569     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
75570     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
75571     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75572     sqlite3VdbeAddOp0(v, OP_Close);
75573   }
75574
75575   /* Normal (non-error) return. */
75576   return;
75577
75578   /* If an error occurs, we jump here */
75579 begin_table_error:
75580   sqlite3DbFree(db, zName);
75581   return;
75582 }
75583
75584 /*
75585 ** This macro is used to compare two strings in a case-insensitive manner.
75586 ** It is slightly faster than calling sqlite3StrICmp() directly, but
75587 ** produces larger code.
75588 **
75589 ** WARNING: This macro is not compatible with the strcmp() family. It
75590 ** returns true if the two strings are equal, otherwise false.
75591 */
75592 #define STRICMP(x, y) (\
75593 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
75594 sqlite3UpperToLower[*(unsigned char *)(y)]     \
75595 && sqlite3StrICmp((x)+1,(y)+1)==0 )
75596
75597 /*
75598 ** Add a new column to the table currently being constructed.
75599 **
75600 ** The parser calls this routine once for each column declaration
75601 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
75602 ** first to get things going.  Then this routine is called for each
75603 ** column.
75604 */
75605 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
75606   Table *p;
75607   int i;
75608   char *z;
75609   Column *pCol;
75610   sqlite3 *db = pParse->db;
75611   if( (p = pParse->pNewTable)==0 ) return;
75612 #if SQLITE_MAX_COLUMN
75613   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
75614     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
75615     return;
75616   }
75617 #endif
75618   z = sqlite3NameFromToken(db, pName);
75619   if( z==0 ) return;
75620   for(i=0; i<p->nCol; i++){
75621     if( STRICMP(z, p->aCol[i].zName) ){
75622       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
75623       sqlite3DbFree(db, z);
75624       return;
75625     }
75626   }
75627   if( (p->nCol & 0x7)==0 ){
75628     Column *aNew;
75629     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
75630     if( aNew==0 ){
75631       sqlite3DbFree(db, z);
75632       return;
75633     }
75634     p->aCol = aNew;
75635   }
75636   pCol = &p->aCol[p->nCol];
75637   memset(pCol, 0, sizeof(p->aCol[0]));
75638   pCol->zName = z;
75639  
75640   /* If there is no type specified, columns have the default affinity
75641   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
75642   ** be called next to set pCol->affinity correctly.
75643   */
75644   pCol->affinity = SQLITE_AFF_NONE;
75645   p->nCol++;
75646 }
75647
75648 /*
75649 ** This routine is called by the parser while in the middle of
75650 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
75651 ** been seen on a column.  This routine sets the notNull flag on
75652 ** the column currently under construction.
75653 */
75654 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
75655   Table *p;
75656   p = pParse->pNewTable;
75657   if( p==0 || NEVER(p->nCol<1) ) return;
75658   p->aCol[p->nCol-1].notNull = (u8)onError;
75659 }
75660
75661 /*
75662 ** Scan the column type name zType (length nType) and return the
75663 ** associated affinity type.
75664 **
75665 ** This routine does a case-independent search of zType for the 
75666 ** substrings in the following table. If one of the substrings is
75667 ** found, the corresponding affinity is returned. If zType contains
75668 ** more than one of the substrings, entries toward the top of 
75669 ** the table take priority. For example, if zType is 'BLOBINT', 
75670 ** SQLITE_AFF_INTEGER is returned.
75671 **
75672 ** Substring     | Affinity
75673 ** --------------------------------
75674 ** 'INT'         | SQLITE_AFF_INTEGER
75675 ** 'CHAR'        | SQLITE_AFF_TEXT
75676 ** 'CLOB'        | SQLITE_AFF_TEXT
75677 ** 'TEXT'        | SQLITE_AFF_TEXT
75678 ** 'BLOB'        | SQLITE_AFF_NONE
75679 ** 'REAL'        | SQLITE_AFF_REAL
75680 ** 'FLOA'        | SQLITE_AFF_REAL
75681 ** 'DOUB'        | SQLITE_AFF_REAL
75682 **
75683 ** If none of the substrings in the above table are found,
75684 ** SQLITE_AFF_NUMERIC is returned.
75685 */
75686 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
75687   u32 h = 0;
75688   char aff = SQLITE_AFF_NUMERIC;
75689
75690   if( zIn ) while( zIn[0] ){
75691     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
75692     zIn++;
75693     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
75694       aff = SQLITE_AFF_TEXT; 
75695     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
75696       aff = SQLITE_AFF_TEXT;
75697     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
75698       aff = SQLITE_AFF_TEXT;
75699     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
75700         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
75701       aff = SQLITE_AFF_NONE;
75702 #ifndef SQLITE_OMIT_FLOATING_POINT
75703     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
75704         && aff==SQLITE_AFF_NUMERIC ){
75705       aff = SQLITE_AFF_REAL;
75706     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
75707         && aff==SQLITE_AFF_NUMERIC ){
75708       aff = SQLITE_AFF_REAL;
75709     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
75710         && aff==SQLITE_AFF_NUMERIC ){
75711       aff = SQLITE_AFF_REAL;
75712 #endif
75713     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
75714       aff = SQLITE_AFF_INTEGER;
75715       break;
75716     }
75717   }
75718
75719   return aff;
75720 }
75721
75722 /*
75723 ** This routine is called by the parser while in the middle of
75724 ** parsing a CREATE TABLE statement.  The pFirst token is the first
75725 ** token in the sequence of tokens that describe the type of the
75726 ** column currently under construction.   pLast is the last token
75727 ** in the sequence.  Use this information to construct a string
75728 ** that contains the typename of the column and store that string
75729 ** in zType.
75730 */ 
75731 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
75732   Table *p;
75733   Column *pCol;
75734
75735   p = pParse->pNewTable;
75736   if( p==0 || NEVER(p->nCol<1) ) return;
75737   pCol = &p->aCol[p->nCol-1];
75738   assert( pCol->zType==0 );
75739   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
75740   pCol->affinity = sqlite3AffinityType(pCol->zType);
75741 }
75742
75743 /*
75744 ** The expression is the default value for the most recently added column
75745 ** of the table currently under construction.
75746 **
75747 ** Default value expressions must be constant.  Raise an exception if this
75748 ** is not the case.
75749 **
75750 ** This routine is called by the parser while in the middle of
75751 ** parsing a CREATE TABLE statement.
75752 */
75753 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
75754   Table *p;
75755   Column *pCol;
75756   sqlite3 *db = pParse->db;
75757   p = pParse->pNewTable;
75758   if( p!=0 ){
75759     pCol = &(p->aCol[p->nCol-1]);
75760     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
75761       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
75762           pCol->zName);
75763     }else{
75764       /* A copy of pExpr is used instead of the original, as pExpr contains
75765       ** tokens that point to volatile memory. The 'span' of the expression
75766       ** is required by pragma table_info.
75767       */
75768       sqlite3ExprDelete(db, pCol->pDflt);
75769       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
75770       sqlite3DbFree(db, pCol->zDflt);
75771       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
75772                                      (int)(pSpan->zEnd - pSpan->zStart));
75773     }
75774   }
75775   sqlite3ExprDelete(db, pSpan->pExpr);
75776 }
75777
75778 /*
75779 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
75780 ** of columns that form the primary key.  If pList is NULL, then the
75781 ** most recently added column of the table is the primary key.
75782 **
75783 ** A table can have at most one primary key.  If the table already has
75784 ** a primary key (and this is the second primary key) then create an
75785 ** error.
75786 **
75787 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
75788 ** then we will try to use that column as the rowid.  Set the Table.iPKey
75789 ** field of the table under construction to be the index of the
75790 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
75791 ** no INTEGER PRIMARY KEY.
75792 **
75793 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
75794 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
75795 */
75796 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
75797   Parse *pParse,    /* Parsing context */
75798   ExprList *pList,  /* List of field names to be indexed */
75799   int onError,      /* What to do with a uniqueness conflict */
75800   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
75801   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
75802 ){
75803   Table *pTab = pParse->pNewTable;
75804   char *zType = 0;
75805   int iCol = -1, i;
75806   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
75807   if( pTab->tabFlags & TF_HasPrimaryKey ){
75808     sqlite3ErrorMsg(pParse, 
75809       "table \"%s\" has more than one primary key", pTab->zName);
75810     goto primary_key_exit;
75811   }
75812   pTab->tabFlags |= TF_HasPrimaryKey;
75813   if( pList==0 ){
75814     iCol = pTab->nCol - 1;
75815     pTab->aCol[iCol].isPrimKey = 1;
75816   }else{
75817     for(i=0; i<pList->nExpr; i++){
75818       for(iCol=0; iCol<pTab->nCol; iCol++){
75819         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
75820           break;
75821         }
75822       }
75823       if( iCol<pTab->nCol ){
75824         pTab->aCol[iCol].isPrimKey = 1;
75825       }
75826     }
75827     if( pList->nExpr>1 ) iCol = -1;
75828   }
75829   if( iCol>=0 && iCol<pTab->nCol ){
75830     zType = pTab->aCol[iCol].zType;
75831   }
75832   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
75833         && sortOrder==SQLITE_SO_ASC ){
75834     pTab->iPKey = iCol;
75835     pTab->keyConf = (u8)onError;
75836     assert( autoInc==0 || autoInc==1 );
75837     pTab->tabFlags |= autoInc*TF_Autoincrement;
75838   }else if( autoInc ){
75839 #ifndef SQLITE_OMIT_AUTOINCREMENT
75840     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
75841        "INTEGER PRIMARY KEY");
75842 #endif
75843   }else{
75844     Index *p;
75845     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
75846     if( p ){
75847       p->autoIndex = 2;
75848     }
75849     pList = 0;
75850   }
75851
75852 primary_key_exit:
75853   sqlite3ExprListDelete(pParse->db, pList);
75854   return;
75855 }
75856
75857 /*
75858 ** Add a new CHECK constraint to the table currently under construction.
75859 */
75860 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
75861   Parse *pParse,    /* Parsing context */
75862   Expr *pCheckExpr  /* The check expression */
75863 ){
75864   sqlite3 *db = pParse->db;
75865 #ifndef SQLITE_OMIT_CHECK
75866   Table *pTab = pParse->pNewTable;
75867   if( pTab && !IN_DECLARE_VTAB ){
75868     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
75869   }else
75870 #endif
75871   {
75872     sqlite3ExprDelete(db, pCheckExpr);
75873   }
75874 }
75875
75876 /*
75877 ** Set the collation function of the most recently parsed table column
75878 ** to the CollSeq given.
75879 */
75880 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
75881   Table *p;
75882   int i;
75883   char *zColl;              /* Dequoted name of collation sequence */
75884   sqlite3 *db;
75885
75886   if( (p = pParse->pNewTable)==0 ) return;
75887   i = p->nCol-1;
75888   db = pParse->db;
75889   zColl = sqlite3NameFromToken(db, pToken);
75890   if( !zColl ) return;
75891
75892   if( sqlite3LocateCollSeq(pParse, zColl) ){
75893     Index *pIdx;
75894     p->aCol[i].zColl = zColl;
75895   
75896     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
75897     ** then an index may have been created on this column before the
75898     ** collation type was added. Correct this if it is the case.
75899     */
75900     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
75901       assert( pIdx->nColumn==1 );
75902       if( pIdx->aiColumn[0]==i ){
75903         pIdx->azColl[0] = p->aCol[i].zColl;
75904       }
75905     }
75906   }else{
75907     sqlite3DbFree(db, zColl);
75908   }
75909 }
75910
75911 /*
75912 ** This function returns the collation sequence for database native text
75913 ** encoding identified by the string zName, length nName.
75914 **
75915 ** If the requested collation sequence is not available, or not available
75916 ** in the database native encoding, the collation factory is invoked to
75917 ** request it. If the collation factory does not supply such a sequence,
75918 ** and the sequence is available in another text encoding, then that is
75919 ** returned instead.
75920 **
75921 ** If no versions of the requested collations sequence are available, or
75922 ** another error occurs, NULL is returned and an error message written into
75923 ** pParse.
75924 **
75925 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
75926 ** invokes the collation factory if the named collation cannot be found
75927 ** and generates an error message.
75928 **
75929 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
75930 */
75931 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
75932   sqlite3 *db = pParse->db;
75933   u8 enc = ENC(db);
75934   u8 initbusy = db->init.busy;
75935   CollSeq *pColl;
75936
75937   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
75938   if( !initbusy && (!pColl || !pColl->xCmp) ){
75939     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
75940     if( !pColl ){
75941       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
75942     }
75943   }
75944
75945   return pColl;
75946 }
75947
75948
75949 /*
75950 ** Generate code that will increment the schema cookie.
75951 **
75952 ** The schema cookie is used to determine when the schema for the
75953 ** database changes.  After each schema change, the cookie value
75954 ** changes.  When a process first reads the schema it records the
75955 ** cookie.  Thereafter, whenever it goes to access the database,
75956 ** it checks the cookie to make sure the schema has not changed
75957 ** since it was last read.
75958 **
75959 ** This plan is not completely bullet-proof.  It is possible for
75960 ** the schema to change multiple times and for the cookie to be
75961 ** set back to prior value.  But schema changes are infrequent
75962 ** and the probability of hitting the same cookie value is only
75963 ** 1 chance in 2^32.  So we're safe enough.
75964 */
75965 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
75966   int r1 = sqlite3GetTempReg(pParse);
75967   sqlite3 *db = pParse->db;
75968   Vdbe *v = pParse->pVdbe;
75969   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
75970   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
75971   sqlite3ReleaseTempReg(pParse, r1);
75972 }
75973
75974 /*
75975 ** Measure the number of characters needed to output the given
75976 ** identifier.  The number returned includes any quotes used
75977 ** but does not include the null terminator.
75978 **
75979 ** The estimate is conservative.  It might be larger that what is
75980 ** really needed.
75981 */
75982 static int identLength(const char *z){
75983   int n;
75984   for(n=0; *z; n++, z++){
75985     if( *z=='"' ){ n++; }
75986   }
75987   return n + 2;
75988 }
75989
75990 /*
75991 ** The first parameter is a pointer to an output buffer. The second 
75992 ** parameter is a pointer to an integer that contains the offset at
75993 ** which to write into the output buffer. This function copies the
75994 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
75995 ** to the specified offset in the buffer and updates *pIdx to refer
75996 ** to the first byte after the last byte written before returning.
75997 ** 
75998 ** If the string zSignedIdent consists entirely of alpha-numeric
75999 ** characters, does not begin with a digit and is not an SQL keyword,
76000 ** then it is copied to the output buffer exactly as it is. Otherwise,
76001 ** it is quoted using double-quotes.
76002 */
76003 static void identPut(char *z, int *pIdx, char *zSignedIdent){
76004   unsigned char *zIdent = (unsigned char*)zSignedIdent;
76005   int i, j, needQuote;
76006   i = *pIdx;
76007
76008   for(j=0; zIdent[j]; j++){
76009     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
76010   }
76011   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
76012   if( !needQuote ){
76013     needQuote = zIdent[j];
76014   }
76015
76016   if( needQuote ) z[i++] = '"';
76017   for(j=0; zIdent[j]; j++){
76018     z[i++] = zIdent[j];
76019     if( zIdent[j]=='"' ) z[i++] = '"';
76020   }
76021   if( needQuote ) z[i++] = '"';
76022   z[i] = 0;
76023   *pIdx = i;
76024 }
76025
76026 /*
76027 ** Generate a CREATE TABLE statement appropriate for the given
76028 ** table.  Memory to hold the text of the statement is obtained
76029 ** from sqliteMalloc() and must be freed by the calling function.
76030 */
76031 static char *createTableStmt(sqlite3 *db, Table *p){
76032   int i, k, n;
76033   char *zStmt;
76034   char *zSep, *zSep2, *zEnd;
76035   Column *pCol;
76036   n = 0;
76037   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
76038     n += identLength(pCol->zName) + 5;
76039   }
76040   n += identLength(p->zName);
76041   if( n<50 ){ 
76042     zSep = "";
76043     zSep2 = ",";
76044     zEnd = ")";
76045   }else{
76046     zSep = "\n  ";
76047     zSep2 = ",\n  ";
76048     zEnd = "\n)";
76049   }
76050   n += 35 + 6*p->nCol;
76051   zStmt = sqlite3DbMallocRaw(0, n);
76052   if( zStmt==0 ){
76053     db->mallocFailed = 1;
76054     return 0;
76055   }
76056   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
76057   k = sqlite3Strlen30(zStmt);
76058   identPut(zStmt, &k, p->zName);
76059   zStmt[k++] = '(';
76060   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
76061     static const char * const azType[] = {
76062         /* SQLITE_AFF_TEXT    */ " TEXT",
76063         /* SQLITE_AFF_NONE    */ "",
76064         /* SQLITE_AFF_NUMERIC */ " NUM",
76065         /* SQLITE_AFF_INTEGER */ " INT",
76066         /* SQLITE_AFF_REAL    */ " REAL"
76067     };
76068     int len;
76069     const char *zType;
76070
76071     sqlite3_snprintf(n-k, &zStmt[k], zSep);
76072     k += sqlite3Strlen30(&zStmt[k]);
76073     zSep = zSep2;
76074     identPut(zStmt, &k, pCol->zName);
76075     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
76076     assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
76077     testcase( pCol->affinity==SQLITE_AFF_TEXT );
76078     testcase( pCol->affinity==SQLITE_AFF_NONE );
76079     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
76080     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
76081     testcase( pCol->affinity==SQLITE_AFF_REAL );
76082     
76083     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
76084     len = sqlite3Strlen30(zType);
76085     assert( pCol->affinity==SQLITE_AFF_NONE 
76086             || pCol->affinity==sqlite3AffinityType(zType) );
76087     memcpy(&zStmt[k], zType, len);
76088     k += len;
76089     assert( k<=n );
76090   }
76091   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
76092   return zStmt;
76093 }
76094
76095 /*
76096 ** This routine is called to report the final ")" that terminates
76097 ** a CREATE TABLE statement.
76098 **
76099 ** The table structure that other action routines have been building
76100 ** is added to the internal hash tables, assuming no errors have
76101 ** occurred.
76102 **
76103 ** An entry for the table is made in the master table on disk, unless
76104 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
76105 ** it means we are reading the sqlite_master table because we just
76106 ** connected to the database or because the sqlite_master table has
76107 ** recently changed, so the entry for this table already exists in
76108 ** the sqlite_master table.  We do not want to create it again.
76109 **
76110 ** If the pSelect argument is not NULL, it means that this routine
76111 ** was called to create a table generated from a 
76112 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
76113 ** the new table will match the result set of the SELECT.
76114 */
76115 SQLITE_PRIVATE void sqlite3EndTable(
76116   Parse *pParse,          /* Parse context */
76117   Token *pCons,           /* The ',' token after the last column defn. */
76118   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
76119   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
76120 ){
76121   Table *p;
76122   sqlite3 *db = pParse->db;
76123   int iDb;
76124
76125   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
76126     return;
76127   }
76128   p = pParse->pNewTable;
76129   if( p==0 ) return;
76130
76131   assert( !db->init.busy || !pSelect );
76132
76133   iDb = sqlite3SchemaToIndex(db, p->pSchema);
76134
76135 #ifndef SQLITE_OMIT_CHECK
76136   /* Resolve names in all CHECK constraint expressions.
76137   */
76138   if( p->pCheck ){
76139     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
76140     NameContext sNC;                /* Name context for pParse->pNewTable */
76141
76142     memset(&sNC, 0, sizeof(sNC));
76143     memset(&sSrc, 0, sizeof(sSrc));
76144     sSrc.nSrc = 1;
76145     sSrc.a[0].zName = p->zName;
76146     sSrc.a[0].pTab = p;
76147     sSrc.a[0].iCursor = -1;
76148     sNC.pParse = pParse;
76149     sNC.pSrcList = &sSrc;
76150     sNC.isCheck = 1;
76151     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
76152       return;
76153     }
76154   }
76155 #endif /* !defined(SQLITE_OMIT_CHECK) */
76156
76157   /* If the db->init.busy is 1 it means we are reading the SQL off the
76158   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
76159   ** So do not write to the disk again.  Extract the root page number
76160   ** for the table from the db->init.newTnum field.  (The page number
76161   ** should have been put there by the sqliteOpenCb routine.)
76162   */
76163   if( db->init.busy ){
76164     p->tnum = db->init.newTnum;
76165   }
76166
76167   /* If not initializing, then create a record for the new table
76168   ** in the SQLITE_MASTER table of the database.
76169   **
76170   ** If this is a TEMPORARY table, write the entry into the auxiliary
76171   ** file instead of into the main database file.
76172   */
76173   if( !db->init.busy ){
76174     int n;
76175     Vdbe *v;
76176     char *zType;    /* "view" or "table" */
76177     char *zType2;   /* "VIEW" or "TABLE" */
76178     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
76179
76180     v = sqlite3GetVdbe(pParse);
76181     if( NEVER(v==0) ) return;
76182
76183     sqlite3VdbeAddOp1(v, OP_Close, 0);
76184
76185     /* 
76186     ** Initialize zType for the new view or table.
76187     */
76188     if( p->pSelect==0 ){
76189       /* A regular table */
76190       zType = "table";
76191       zType2 = "TABLE";
76192 #ifndef SQLITE_OMIT_VIEW
76193     }else{
76194       /* A view */
76195       zType = "view";
76196       zType2 = "VIEW";
76197 #endif
76198     }
76199
76200     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
76201     ** statement to populate the new table. The root-page number for the
76202     ** new table is in register pParse->regRoot.
76203     **
76204     ** Once the SELECT has been coded by sqlite3Select(), it is in a
76205     ** suitable state to query for the column names and types to be used
76206     ** by the new table.
76207     **
76208     ** A shared-cache write-lock is not required to write to the new table,
76209     ** as a schema-lock must have already been obtained to create it. Since
76210     ** a schema-lock excludes all other database users, the write-lock would
76211     ** be redundant.
76212     */
76213     if( pSelect ){
76214       SelectDest dest;
76215       Table *pSelTab;
76216
76217       assert(pParse->nTab==1);
76218       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
76219       sqlite3VdbeChangeP5(v, 1);
76220       pParse->nTab = 2;
76221       sqlite3SelectDestInit(&dest, SRT_Table, 1);
76222       sqlite3Select(pParse, pSelect, &dest);
76223       sqlite3VdbeAddOp1(v, OP_Close, 1);
76224       if( pParse->nErr==0 ){
76225         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
76226         if( pSelTab==0 ) return;
76227         assert( p->aCol==0 );
76228         p->nCol = pSelTab->nCol;
76229         p->aCol = pSelTab->aCol;
76230         pSelTab->nCol = 0;
76231         pSelTab->aCol = 0;
76232         sqlite3DeleteTable(db, pSelTab);
76233       }
76234     }
76235
76236     /* Compute the complete text of the CREATE statement */
76237     if( pSelect ){
76238       zStmt = createTableStmt(db, p);
76239     }else{
76240       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
76241       zStmt = sqlite3MPrintf(db, 
76242           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
76243       );
76244     }
76245
76246     /* A slot for the record has already been allocated in the 
76247     ** SQLITE_MASTER table.  We just need to update that slot with all
76248     ** the information we've collected.
76249     */
76250     sqlite3NestedParse(pParse,
76251       "UPDATE %Q.%s "
76252          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
76253        "WHERE rowid=#%d",
76254       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
76255       zType,
76256       p->zName,
76257       p->zName,
76258       pParse->regRoot,
76259       zStmt,
76260       pParse->regRowid
76261     );
76262     sqlite3DbFree(db, zStmt);
76263     sqlite3ChangeCookie(pParse, iDb);
76264
76265 #ifndef SQLITE_OMIT_AUTOINCREMENT
76266     /* Check to see if we need to create an sqlite_sequence table for
76267     ** keeping track of autoincrement keys.
76268     */
76269     if( p->tabFlags & TF_Autoincrement ){
76270       Db *pDb = &db->aDb[iDb];
76271       if( pDb->pSchema->pSeqTab==0 ){
76272         sqlite3NestedParse(pParse,
76273           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
76274           pDb->zName
76275         );
76276       }
76277     }
76278 #endif
76279
76280     /* Reparse everything to update our internal data structures */
76281     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
76282         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
76283   }
76284
76285
76286   /* Add the table to the in-memory representation of the database.
76287   */
76288   if( db->init.busy ){
76289     Table *pOld;
76290     Schema *pSchema = p->pSchema;
76291     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
76292                              sqlite3Strlen30(p->zName),p);
76293     if( pOld ){
76294       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
76295       db->mallocFailed = 1;
76296       return;
76297     }
76298     pParse->pNewTable = 0;
76299     db->nTable++;
76300     db->flags |= SQLITE_InternChanges;
76301
76302 #ifndef SQLITE_OMIT_ALTERTABLE
76303     if( !p->pSelect ){
76304       const char *zName = (const char *)pParse->sNameToken.z;
76305       int nName;
76306       assert( !pSelect && pCons && pEnd );
76307       if( pCons->z==0 ){
76308         pCons = pEnd;
76309       }
76310       nName = (int)((const char *)pCons->z - zName);
76311       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
76312     }
76313 #endif
76314   }
76315 }
76316
76317 #ifndef SQLITE_OMIT_VIEW
76318 /*
76319 ** The parser calls this routine in order to create a new VIEW
76320 */
76321 SQLITE_PRIVATE void sqlite3CreateView(
76322   Parse *pParse,     /* The parsing context */
76323   Token *pBegin,     /* The CREATE token that begins the statement */
76324   Token *pName1,     /* The token that holds the name of the view */
76325   Token *pName2,     /* The token that holds the name of the view */
76326   Select *pSelect,   /* A SELECT statement that will become the new view */
76327   int isTemp,        /* TRUE for a TEMPORARY view */
76328   int noErr          /* Suppress error messages if VIEW already exists */
76329 ){
76330   Table *p;
76331   int n;
76332   const char *z;
76333   Token sEnd;
76334   DbFixer sFix;
76335   Token *pName;
76336   int iDb;
76337   sqlite3 *db = pParse->db;
76338
76339   if( pParse->nVar>0 ){
76340     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
76341     sqlite3SelectDelete(db, pSelect);
76342     return;
76343   }
76344   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
76345   p = pParse->pNewTable;
76346   if( p==0 || pParse->nErr ){
76347     sqlite3SelectDelete(db, pSelect);
76348     return;
76349   }
76350   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
76351   iDb = sqlite3SchemaToIndex(db, p->pSchema);
76352   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
76353     && sqlite3FixSelect(&sFix, pSelect)
76354   ){
76355     sqlite3SelectDelete(db, pSelect);
76356     return;
76357   }
76358
76359   /* Make a copy of the entire SELECT statement that defines the view.
76360   ** This will force all the Expr.token.z values to be dynamically
76361   ** allocated rather than point to the input string - which means that
76362   ** they will persist after the current sqlite3_exec() call returns.
76363   */
76364   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
76365   sqlite3SelectDelete(db, pSelect);
76366   if( db->mallocFailed ){
76367     return;
76368   }
76369   if( !db->init.busy ){
76370     sqlite3ViewGetColumnNames(pParse, p);
76371   }
76372
76373   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
76374   ** the end.
76375   */
76376   sEnd = pParse->sLastToken;
76377   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
76378     sEnd.z += sEnd.n;
76379   }
76380   sEnd.n = 0;
76381   n = (int)(sEnd.z - pBegin->z);
76382   z = pBegin->z;
76383   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
76384   sEnd.z = &z[n-1];
76385   sEnd.n = 1;
76386
76387   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
76388   sqlite3EndTable(pParse, 0, &sEnd, 0);
76389   return;
76390 }
76391 #endif /* SQLITE_OMIT_VIEW */
76392
76393 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
76394 /*
76395 ** The Table structure pTable is really a VIEW.  Fill in the names of
76396 ** the columns of the view in the pTable structure.  Return the number
76397 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
76398 */
76399 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
76400   Table *pSelTab;   /* A fake table from which we get the result set */
76401   Select *pSel;     /* Copy of the SELECT that implements the view */
76402   int nErr = 0;     /* Number of errors encountered */
76403   int n;            /* Temporarily holds the number of cursors assigned */
76404   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
76405   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
76406
76407   assert( pTable );
76408
76409 #ifndef SQLITE_OMIT_VIRTUALTABLE
76410   if( sqlite3VtabCallConnect(pParse, pTable) ){
76411     return SQLITE_ERROR;
76412   }
76413   if( IsVirtual(pTable) ) return 0;
76414 #endif
76415
76416 #ifndef SQLITE_OMIT_VIEW
76417   /* A positive nCol means the columns names for this view are
76418   ** already known.
76419   */
76420   if( pTable->nCol>0 ) return 0;
76421
76422   /* A negative nCol is a special marker meaning that we are currently
76423   ** trying to compute the column names.  If we enter this routine with
76424   ** a negative nCol, it means two or more views form a loop, like this:
76425   **
76426   **     CREATE VIEW one AS SELECT * FROM two;
76427   **     CREATE VIEW two AS SELECT * FROM one;
76428   **
76429   ** Actually, the error above is now caught prior to reaching this point.
76430   ** But the following test is still important as it does come up
76431   ** in the following:
76432   ** 
76433   **     CREATE TABLE main.ex1(a);
76434   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
76435   **     SELECT * FROM temp.ex1;
76436   */
76437   if( pTable->nCol<0 ){
76438     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
76439     return 1;
76440   }
76441   assert( pTable->nCol>=0 );
76442
76443   /* If we get this far, it means we need to compute the table names.
76444   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
76445   ** "*" elements in the results set of the view and will assign cursors
76446   ** to the elements of the FROM clause.  But we do not want these changes
76447   ** to be permanent.  So the computation is done on a copy of the SELECT
76448   ** statement that defines the view.
76449   */
76450   assert( pTable->pSelect );
76451   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
76452   if( pSel ){
76453     u8 enableLookaside = db->lookaside.bEnabled;
76454     n = pParse->nTab;
76455     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
76456     pTable->nCol = -1;
76457     db->lookaside.bEnabled = 0;
76458 #ifndef SQLITE_OMIT_AUTHORIZATION
76459     xAuth = db->xAuth;
76460     db->xAuth = 0;
76461     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
76462     db->xAuth = xAuth;
76463 #else
76464     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
76465 #endif
76466     db->lookaside.bEnabled = enableLookaside;
76467     pParse->nTab = n;
76468     if( pSelTab ){
76469       assert( pTable->aCol==0 );
76470       pTable->nCol = pSelTab->nCol;
76471       pTable->aCol = pSelTab->aCol;
76472       pSelTab->nCol = 0;
76473       pSelTab->aCol = 0;
76474       sqlite3DeleteTable(db, pSelTab);
76475       pTable->pSchema->flags |= DB_UnresetViews;
76476     }else{
76477       pTable->nCol = 0;
76478       nErr++;
76479     }
76480     sqlite3SelectDelete(db, pSel);
76481   } else {
76482     nErr++;
76483   }
76484 #endif /* SQLITE_OMIT_VIEW */
76485   return nErr;  
76486 }
76487 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
76488
76489 #ifndef SQLITE_OMIT_VIEW
76490 /*
76491 ** Clear the column names from every VIEW in database idx.
76492 */
76493 static void sqliteViewResetAll(sqlite3 *db, int idx){
76494   HashElem *i;
76495   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
76496   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
76497     Table *pTab = sqliteHashData(i);
76498     if( pTab->pSelect ){
76499       sqliteDeleteColumnNames(db, pTab);
76500       pTab->aCol = 0;
76501       pTab->nCol = 0;
76502     }
76503   }
76504   DbClearProperty(db, idx, DB_UnresetViews);
76505 }
76506 #else
76507 # define sqliteViewResetAll(A,B)
76508 #endif /* SQLITE_OMIT_VIEW */
76509
76510 /*
76511 ** This function is called by the VDBE to adjust the internal schema
76512 ** used by SQLite when the btree layer moves a table root page. The
76513 ** root-page of a table or index in database iDb has changed from iFrom
76514 ** to iTo.
76515 **
76516 ** Ticket #1728:  The symbol table might still contain information
76517 ** on tables and/or indices that are the process of being deleted.
76518 ** If you are unlucky, one of those deleted indices or tables might
76519 ** have the same rootpage number as the real table or index that is
76520 ** being moved.  So we cannot stop searching after the first match 
76521 ** because the first match might be for one of the deleted indices
76522 ** or tables and not the table/index that is actually being moved.
76523 ** We must continue looping until all tables and indices with
76524 ** rootpage==iFrom have been converted to have a rootpage of iTo
76525 ** in order to be certain that we got the right one.
76526 */
76527 #ifndef SQLITE_OMIT_AUTOVACUUM
76528 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
76529   HashElem *pElem;
76530   Hash *pHash;
76531
76532   pHash = &pDb->pSchema->tblHash;
76533   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
76534     Table *pTab = sqliteHashData(pElem);
76535     if( pTab->tnum==iFrom ){
76536       pTab->tnum = iTo;
76537     }
76538   }
76539   pHash = &pDb->pSchema->idxHash;
76540   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
76541     Index *pIdx = sqliteHashData(pElem);
76542     if( pIdx->tnum==iFrom ){
76543       pIdx->tnum = iTo;
76544     }
76545   }
76546 }
76547 #endif
76548
76549 /*
76550 ** Write code to erase the table with root-page iTable from database iDb.
76551 ** Also write code to modify the sqlite_master table and internal schema
76552 ** if a root-page of another table is moved by the btree-layer whilst
76553 ** erasing iTable (this can happen with an auto-vacuum database).
76554 */ 
76555 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
76556   Vdbe *v = sqlite3GetVdbe(pParse);
76557   int r1 = sqlite3GetTempReg(pParse);
76558   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
76559   sqlite3MayAbort(pParse);
76560 #ifndef SQLITE_OMIT_AUTOVACUUM
76561   /* OP_Destroy stores an in integer r1. If this integer
76562   ** is non-zero, then it is the root page number of a table moved to
76563   ** location iTable. The following code modifies the sqlite_master table to
76564   ** reflect this.
76565   **
76566   ** The "#NNN" in the SQL is a special constant that means whatever value
76567   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
76568   ** token for additional information.
76569   */
76570   sqlite3NestedParse(pParse, 
76571      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
76572      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
76573 #endif
76574   sqlite3ReleaseTempReg(pParse, r1);
76575 }
76576
76577 /*
76578 ** Write VDBE code to erase table pTab and all associated indices on disk.
76579 ** Code to update the sqlite_master tables and internal schema definitions
76580 ** in case a root-page belonging to another table is moved by the btree layer
76581 ** is also added (this can happen with an auto-vacuum database).
76582 */
76583 static void destroyTable(Parse *pParse, Table *pTab){
76584 #ifdef SQLITE_OMIT_AUTOVACUUM
76585   Index *pIdx;
76586   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76587   destroyRootPage(pParse, pTab->tnum, iDb);
76588   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
76589     destroyRootPage(pParse, pIdx->tnum, iDb);
76590   }
76591 #else
76592   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
76593   ** is not defined), then it is important to call OP_Destroy on the
76594   ** table and index root-pages in order, starting with the numerically 
76595   ** largest root-page number. This guarantees that none of the root-pages
76596   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
76597   ** following were coded:
76598   **
76599   ** OP_Destroy 4 0
76600   ** ...
76601   ** OP_Destroy 5 0
76602   **
76603   ** and root page 5 happened to be the largest root-page number in the
76604   ** database, then root page 5 would be moved to page 4 by the 
76605   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
76606   ** a free-list page.
76607   */
76608   int iTab = pTab->tnum;
76609   int iDestroyed = 0;
76610
76611   while( 1 ){
76612     Index *pIdx;
76613     int iLargest = 0;
76614
76615     if( iDestroyed==0 || iTab<iDestroyed ){
76616       iLargest = iTab;
76617     }
76618     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
76619       int iIdx = pIdx->tnum;
76620       assert( pIdx->pSchema==pTab->pSchema );
76621       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
76622         iLargest = iIdx;
76623       }
76624     }
76625     if( iLargest==0 ){
76626       return;
76627     }else{
76628       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76629       destroyRootPage(pParse, iLargest, iDb);
76630       iDestroyed = iLargest;
76631     }
76632   }
76633 #endif
76634 }
76635
76636 /*
76637 ** This routine is called to do the work of a DROP TABLE statement.
76638 ** pName is the name of the table to be dropped.
76639 */
76640 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
76641   Table *pTab;
76642   Vdbe *v;
76643   sqlite3 *db = pParse->db;
76644   int iDb;
76645
76646   if( db->mallocFailed ){
76647     goto exit_drop_table;
76648   }
76649   assert( pParse->nErr==0 );
76650   assert( pName->nSrc==1 );
76651   if( noErr ) db->suppressErr++;
76652   pTab = sqlite3LocateTable(pParse, isView, 
76653                             pName->a[0].zName, pName->a[0].zDatabase);
76654   if( noErr ) db->suppressErr--;
76655
76656   if( pTab==0 ){
76657     goto exit_drop_table;
76658   }
76659   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76660   assert( iDb>=0 && iDb<db->nDb );
76661
76662   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
76663   ** it is initialized.
76664   */
76665   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
76666     goto exit_drop_table;
76667   }
76668 #ifndef SQLITE_OMIT_AUTHORIZATION
76669   {
76670     int code;
76671     const char *zTab = SCHEMA_TABLE(iDb);
76672     const char *zDb = db->aDb[iDb].zName;
76673     const char *zArg2 = 0;
76674     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
76675       goto exit_drop_table;
76676     }
76677     if( isView ){
76678       if( !OMIT_TEMPDB && iDb==1 ){
76679         code = SQLITE_DROP_TEMP_VIEW;
76680       }else{
76681         code = SQLITE_DROP_VIEW;
76682       }
76683 #ifndef SQLITE_OMIT_VIRTUALTABLE
76684     }else if( IsVirtual(pTab) ){
76685       code = SQLITE_DROP_VTABLE;
76686       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
76687 #endif
76688     }else{
76689       if( !OMIT_TEMPDB && iDb==1 ){
76690         code = SQLITE_DROP_TEMP_TABLE;
76691       }else{
76692         code = SQLITE_DROP_TABLE;
76693       }
76694     }
76695     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
76696       goto exit_drop_table;
76697     }
76698     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
76699       goto exit_drop_table;
76700     }
76701   }
76702 #endif
76703   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
76704     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
76705     goto exit_drop_table;
76706   }
76707
76708 #ifndef SQLITE_OMIT_VIEW
76709   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
76710   ** on a table.
76711   */
76712   if( isView && pTab->pSelect==0 ){
76713     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
76714     goto exit_drop_table;
76715   }
76716   if( !isView && pTab->pSelect ){
76717     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
76718     goto exit_drop_table;
76719   }
76720 #endif
76721
76722   /* Generate code to remove the table from the master table
76723   ** on disk.
76724   */
76725   v = sqlite3GetVdbe(pParse);
76726   if( v ){
76727     Trigger *pTrigger;
76728     Db *pDb = &db->aDb[iDb];
76729     sqlite3BeginWriteOperation(pParse, 1, iDb);
76730
76731 #ifndef SQLITE_OMIT_VIRTUALTABLE
76732     if( IsVirtual(pTab) ){
76733       sqlite3VdbeAddOp0(v, OP_VBegin);
76734     }
76735 #endif
76736     sqlite3FkDropTable(pParse, pName, pTab);
76737
76738     /* Drop all triggers associated with the table being dropped. Code
76739     ** is generated to remove entries from sqlite_master and/or
76740     ** sqlite_temp_master if required.
76741     */
76742     pTrigger = sqlite3TriggerList(pParse, pTab);
76743     while( pTrigger ){
76744       assert( pTrigger->pSchema==pTab->pSchema || 
76745           pTrigger->pSchema==db->aDb[1].pSchema );
76746       sqlite3DropTriggerPtr(pParse, pTrigger);
76747       pTrigger = pTrigger->pNext;
76748     }
76749
76750 #ifndef SQLITE_OMIT_AUTOINCREMENT
76751     /* Remove any entries of the sqlite_sequence table associated with
76752     ** the table being dropped. This is done before the table is dropped
76753     ** at the btree level, in case the sqlite_sequence table needs to
76754     ** move as a result of the drop (can happen in auto-vacuum mode).
76755     */
76756     if( pTab->tabFlags & TF_Autoincrement ){
76757       sqlite3NestedParse(pParse,
76758         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
76759         pDb->zName, pTab->zName
76760       );
76761     }
76762 #endif
76763
76764     /* Drop all SQLITE_MASTER table and index entries that refer to the
76765     ** table. The program name loops through the master table and deletes
76766     ** every row that refers to a table of the same name as the one being
76767     ** dropped. Triggers are handled seperately because a trigger can be
76768     ** created in the temp database that refers to a table in another
76769     ** database.
76770     */
76771     sqlite3NestedParse(pParse, 
76772         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
76773         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
76774
76775     /* Drop any statistics from the sqlite_stat1 table, if it exists */
76776     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
76777       sqlite3NestedParse(pParse,
76778         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
76779       );
76780     }
76781
76782     if( !isView && !IsVirtual(pTab) ){
76783       destroyTable(pParse, pTab);
76784     }
76785
76786     /* Remove the table entry from SQLite's internal schema and modify
76787     ** the schema cookie.
76788     */
76789     if( IsVirtual(pTab) ){
76790       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
76791     }
76792     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
76793     sqlite3ChangeCookie(pParse, iDb);
76794   }
76795   sqliteViewResetAll(db, iDb);
76796
76797 exit_drop_table:
76798   sqlite3SrcListDelete(db, pName);
76799 }
76800
76801 /*
76802 ** This routine is called to create a new foreign key on the table
76803 ** currently under construction.  pFromCol determines which columns
76804 ** in the current table point to the foreign key.  If pFromCol==0 then
76805 ** connect the key to the last column inserted.  pTo is the name of
76806 ** the table referred to.  pToCol is a list of tables in the other
76807 ** pTo table that the foreign key points to.  flags contains all
76808 ** information about the conflict resolution algorithms specified
76809 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
76810 **
76811 ** An FKey structure is created and added to the table currently
76812 ** under construction in the pParse->pNewTable field.
76813 **
76814 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
76815 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
76816 */
76817 SQLITE_PRIVATE void sqlite3CreateForeignKey(
76818   Parse *pParse,       /* Parsing context */
76819   ExprList *pFromCol,  /* Columns in this table that point to other table */
76820   Token *pTo,          /* Name of the other table */
76821   ExprList *pToCol,    /* Columns in the other table */
76822   int flags            /* Conflict resolution algorithms. */
76823 ){
76824   sqlite3 *db = pParse->db;
76825 #ifndef SQLITE_OMIT_FOREIGN_KEY
76826   FKey *pFKey = 0;
76827   FKey *pNextTo;
76828   Table *p = pParse->pNewTable;
76829   int nByte;
76830   int i;
76831   int nCol;
76832   char *z;
76833
76834   assert( pTo!=0 );
76835   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
76836   if( pFromCol==0 ){
76837     int iCol = p->nCol-1;
76838     if( NEVER(iCol<0) ) goto fk_end;
76839     if( pToCol && pToCol->nExpr!=1 ){
76840       sqlite3ErrorMsg(pParse, "foreign key on %s"
76841          " should reference only one column of table %T",
76842          p->aCol[iCol].zName, pTo);
76843       goto fk_end;
76844     }
76845     nCol = 1;
76846   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
76847     sqlite3ErrorMsg(pParse,
76848         "number of columns in foreign key does not match the number of "
76849         "columns in the referenced table");
76850     goto fk_end;
76851   }else{
76852     nCol = pFromCol->nExpr;
76853   }
76854   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
76855   if( pToCol ){
76856     for(i=0; i<pToCol->nExpr; i++){
76857       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
76858     }
76859   }
76860   pFKey = sqlite3DbMallocZero(db, nByte );
76861   if( pFKey==0 ){
76862     goto fk_end;
76863   }
76864   pFKey->pFrom = p;
76865   pFKey->pNextFrom = p->pFKey;
76866   z = (char*)&pFKey->aCol[nCol];
76867   pFKey->zTo = z;
76868   memcpy(z, pTo->z, pTo->n);
76869   z[pTo->n] = 0;
76870   sqlite3Dequote(z);
76871   z += pTo->n+1;
76872   pFKey->nCol = nCol;
76873   if( pFromCol==0 ){
76874     pFKey->aCol[0].iFrom = p->nCol-1;
76875   }else{
76876     for(i=0; i<nCol; i++){
76877       int j;
76878       for(j=0; j<p->nCol; j++){
76879         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
76880           pFKey->aCol[i].iFrom = j;
76881           break;
76882         }
76883       }
76884       if( j>=p->nCol ){
76885         sqlite3ErrorMsg(pParse, 
76886           "unknown column \"%s\" in foreign key definition", 
76887           pFromCol->a[i].zName);
76888         goto fk_end;
76889       }
76890     }
76891   }
76892   if( pToCol ){
76893     for(i=0; i<nCol; i++){
76894       int n = sqlite3Strlen30(pToCol->a[i].zName);
76895       pFKey->aCol[i].zCol = z;
76896       memcpy(z, pToCol->a[i].zName, n);
76897       z[n] = 0;
76898       z += n+1;
76899     }
76900   }
76901   pFKey->isDeferred = 0;
76902   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
76903   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
76904
76905   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
76906       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
76907   );
76908   if( pNextTo==pFKey ){
76909     db->mallocFailed = 1;
76910     goto fk_end;
76911   }
76912   if( pNextTo ){
76913     assert( pNextTo->pPrevTo==0 );
76914     pFKey->pNextTo = pNextTo;
76915     pNextTo->pPrevTo = pFKey;
76916   }
76917
76918   /* Link the foreign key to the table as the last step.
76919   */
76920   p->pFKey = pFKey;
76921   pFKey = 0;
76922
76923 fk_end:
76924   sqlite3DbFree(db, pFKey);
76925 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
76926   sqlite3ExprListDelete(db, pFromCol);
76927   sqlite3ExprListDelete(db, pToCol);
76928 }
76929
76930 /*
76931 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
76932 ** clause is seen as part of a foreign key definition.  The isDeferred
76933 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
76934 ** The behavior of the most recently created foreign key is adjusted
76935 ** accordingly.
76936 */
76937 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
76938 #ifndef SQLITE_OMIT_FOREIGN_KEY
76939   Table *pTab;
76940   FKey *pFKey;
76941   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
76942   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
76943   pFKey->isDeferred = (u8)isDeferred;
76944 #endif
76945 }
76946
76947 /*
76948 ** Generate code that will erase and refill index *pIdx.  This is
76949 ** used to initialize a newly created index or to recompute the
76950 ** content of an index in response to a REINDEX command.
76951 **
76952 ** if memRootPage is not negative, it means that the index is newly
76953 ** created.  The register specified by memRootPage contains the
76954 ** root page number of the index.  If memRootPage is negative, then
76955 ** the index already exists and must be cleared before being refilled and
76956 ** the root page number of the index is taken from pIndex->tnum.
76957 */
76958 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
76959   Table *pTab = pIndex->pTable;  /* The table that is indexed */
76960   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
76961   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
76962   int addr1;                     /* Address of top of loop */
76963   int tnum;                      /* Root page of index */
76964   Vdbe *v;                       /* Generate code into this virtual machine */
76965   KeyInfo *pKey;                 /* KeyInfo for index */
76966   int regIdxKey;                 /* Registers containing the index key */
76967   int regRecord;                 /* Register holding assemblied index record */
76968   sqlite3 *db = pParse->db;      /* The database connection */
76969   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
76970
76971 #ifndef SQLITE_OMIT_AUTHORIZATION
76972   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
76973       db->aDb[iDb].zName ) ){
76974     return;
76975   }
76976 #endif
76977
76978   /* Require a write-lock on the table to perform this operation */
76979   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
76980
76981   v = sqlite3GetVdbe(pParse);
76982   if( v==0 ) return;
76983   if( memRootPage>=0 ){
76984     tnum = memRootPage;
76985   }else{
76986     tnum = pIndex->tnum;
76987     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
76988   }
76989   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
76990   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
76991                     (char *)pKey, P4_KEYINFO_HANDOFF);
76992   if( memRootPage>=0 ){
76993     sqlite3VdbeChangeP5(v, 1);
76994   }
76995   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
76996   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
76997   regRecord = sqlite3GetTempReg(pParse);
76998   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
76999   if( pIndex->onError!=OE_None ){
77000     const int regRowid = regIdxKey + pIndex->nColumn;
77001     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
77002     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
77003
77004     /* The registers accessed by the OP_IsUnique opcode were allocated
77005     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
77006     ** call above. Just before that function was freed they were released
77007     ** (made available to the compiler for reuse) using 
77008     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
77009     ** opcode use the values stored within seems dangerous. However, since
77010     ** we can be sure that no other temp registers have been allocated
77011     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
77012     */
77013     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
77014     sqlite3HaltConstraint(
77015         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
77016   }
77017   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
77018   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
77019   sqlite3ReleaseTempReg(pParse, regRecord);
77020   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
77021   sqlite3VdbeJumpHere(v, addr1);
77022   sqlite3VdbeAddOp1(v, OP_Close, iTab);
77023   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
77024 }
77025
77026 /*
77027 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
77028 ** and pTblList is the name of the table that is to be indexed.  Both will 
77029 ** be NULL for a primary key or an index that is created to satisfy a
77030 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
77031 ** as the table to be indexed.  pParse->pNewTable is a table that is
77032 ** currently being constructed by a CREATE TABLE statement.
77033 **
77034 ** pList is a list of columns to be indexed.  pList will be NULL if this
77035 ** is a primary key or unique-constraint on the most recent column added
77036 ** to the table currently under construction.  
77037 **
77038 ** If the index is created successfully, return a pointer to the new Index
77039 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
77040 ** as the tables primary key (Index.autoIndex==2).
77041 */
77042 SQLITE_PRIVATE Index *sqlite3CreateIndex(
77043   Parse *pParse,     /* All information about this parse */
77044   Token *pName1,     /* First part of index name. May be NULL */
77045   Token *pName2,     /* Second part of index name. May be NULL */
77046   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
77047   ExprList *pList,   /* A list of columns to be indexed */
77048   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
77049   Token *pStart,     /* The CREATE token that begins this statement */
77050   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
77051   int sortOrder,     /* Sort order of primary key when pList==NULL */
77052   int ifNotExist     /* Omit error if index already exists */
77053 ){
77054   Index *pRet = 0;     /* Pointer to return */
77055   Table *pTab = 0;     /* Table to be indexed */
77056   Index *pIndex = 0;   /* The index to be created */
77057   char *zName = 0;     /* Name of the index */
77058   int nName;           /* Number of characters in zName */
77059   int i, j;
77060   Token nullId;        /* Fake token for an empty ID list */
77061   DbFixer sFix;        /* For assigning database names to pTable */
77062   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
77063   sqlite3 *db = pParse->db;
77064   Db *pDb;             /* The specific table containing the indexed database */
77065   int iDb;             /* Index of the database that is being written */
77066   Token *pName = 0;    /* Unqualified name of the index to create */
77067   struct ExprList_item *pListItem; /* For looping over pList */
77068   int nCol;
77069   int nExtra = 0;
77070   char *zExtra;
77071
77072   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
77073   assert( pParse->nErr==0 );      /* Never called with prior errors */
77074   if( db->mallocFailed || IN_DECLARE_VTAB ){
77075     goto exit_create_index;
77076   }
77077   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77078     goto exit_create_index;
77079   }
77080
77081   /*
77082   ** Find the table that is to be indexed.  Return early if not found.
77083   */
77084   if( pTblName!=0 ){
77085
77086     /* Use the two-part index name to determine the database 
77087     ** to search for the table. 'Fix' the table name to this db
77088     ** before looking up the table.
77089     */
77090     assert( pName1 && pName2 );
77091     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
77092     if( iDb<0 ) goto exit_create_index;
77093
77094 #ifndef SQLITE_OMIT_TEMPDB
77095     /* If the index name was unqualified, check if the the table
77096     ** is a temp table. If so, set the database to 1. Do not do this
77097     ** if initialising a database schema.
77098     */
77099     if( !db->init.busy ){
77100       pTab = sqlite3SrcListLookup(pParse, pTblName);
77101       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
77102         iDb = 1;
77103       }
77104     }
77105 #endif
77106
77107     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
77108         sqlite3FixSrcList(&sFix, pTblName)
77109     ){
77110       /* Because the parser constructs pTblName from a single identifier,
77111       ** sqlite3FixSrcList can never fail. */
77112       assert(0);
77113     }
77114     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
77115         pTblName->a[0].zDatabase);
77116     if( !pTab || db->mallocFailed ) goto exit_create_index;
77117     assert( db->aDb[iDb].pSchema==pTab->pSchema );
77118   }else{
77119     assert( pName==0 );
77120     pTab = pParse->pNewTable;
77121     if( !pTab ) goto exit_create_index;
77122     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77123   }
77124   pDb = &db->aDb[iDb];
77125
77126   assert( pTab!=0 );
77127   assert( pParse->nErr==0 );
77128   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
77129        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
77130     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
77131     goto exit_create_index;
77132   }
77133 #ifndef SQLITE_OMIT_VIEW
77134   if( pTab->pSelect ){
77135     sqlite3ErrorMsg(pParse, "views may not be indexed");
77136     goto exit_create_index;
77137   }
77138 #endif
77139 #ifndef SQLITE_OMIT_VIRTUALTABLE
77140   if( IsVirtual(pTab) ){
77141     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
77142     goto exit_create_index;
77143   }
77144 #endif
77145
77146   /*
77147   ** Find the name of the index.  Make sure there is not already another
77148   ** index or table with the same name.  
77149   **
77150   ** Exception:  If we are reading the names of permanent indices from the
77151   ** sqlite_master table (because some other process changed the schema) and
77152   ** one of the index names collides with the name of a temporary table or
77153   ** index, then we will continue to process this index.
77154   **
77155   ** If pName==0 it means that we are
77156   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
77157   ** own name.
77158   */
77159   if( pName ){
77160     zName = sqlite3NameFromToken(db, pName);
77161     if( zName==0 ) goto exit_create_index;
77162     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
77163       goto exit_create_index;
77164     }
77165     if( !db->init.busy ){
77166       if( sqlite3FindTable(db, zName, 0)!=0 ){
77167         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
77168         goto exit_create_index;
77169       }
77170     }
77171     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
77172       if( !ifNotExist ){
77173         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
77174       }
77175       goto exit_create_index;
77176     }
77177   }else{
77178     int n;
77179     Index *pLoop;
77180     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
77181     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
77182     if( zName==0 ){
77183       goto exit_create_index;
77184     }
77185   }
77186
77187   /* Check for authorization to create an index.
77188   */
77189 #ifndef SQLITE_OMIT_AUTHORIZATION
77190   {
77191     const char *zDb = pDb->zName;
77192     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
77193       goto exit_create_index;
77194     }
77195     i = SQLITE_CREATE_INDEX;
77196     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
77197     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
77198       goto exit_create_index;
77199     }
77200   }
77201 #endif
77202
77203   /* If pList==0, it means this routine was called to make a primary
77204   ** key out of the last column added to the table under construction.
77205   ** So create a fake list to simulate this.
77206   */
77207   if( pList==0 ){
77208     nullId.z = pTab->aCol[pTab->nCol-1].zName;
77209     nullId.n = sqlite3Strlen30((char*)nullId.z);
77210     pList = sqlite3ExprListAppend(pParse, 0, 0);
77211     if( pList==0 ) goto exit_create_index;
77212     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
77213     pList->a[0].sortOrder = (u8)sortOrder;
77214   }
77215
77216   /* Figure out how many bytes of space are required to store explicitly
77217   ** specified collation sequence names.
77218   */
77219   for(i=0; i<pList->nExpr; i++){
77220     Expr *pExpr = pList->a[i].pExpr;
77221     if( pExpr ){
77222       CollSeq *pColl = pExpr->pColl;
77223       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
77224       ** failure we have quit before reaching this point. */
77225       if( ALWAYS(pColl) ){
77226         nExtra += (1 + sqlite3Strlen30(pColl->zName));
77227       }
77228     }
77229   }
77230
77231   /* 
77232   ** Allocate the index structure. 
77233   */
77234   nName = sqlite3Strlen30(zName);
77235   nCol = pList->nExpr;
77236   pIndex = sqlite3DbMallocZero(db, 
77237       sizeof(Index) +              /* Index structure  */
77238       sizeof(int)*nCol +           /* Index.aiColumn   */
77239       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
77240       sizeof(char *)*nCol +        /* Index.azColl     */
77241       sizeof(u8)*nCol +            /* Index.aSortOrder */
77242       nName + 1 +                  /* Index.zName      */
77243       nExtra                       /* Collation sequence names */
77244   );
77245   if( db->mallocFailed ){
77246     goto exit_create_index;
77247   }
77248   pIndex->azColl = (char**)(&pIndex[1]);
77249   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
77250   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
77251   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
77252   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
77253   zExtra = (char *)(&pIndex->zName[nName+1]);
77254   memcpy(pIndex->zName, zName, nName+1);
77255   pIndex->pTable = pTab;
77256   pIndex->nColumn = pList->nExpr;
77257   pIndex->onError = (u8)onError;
77258   pIndex->autoIndex = (u8)(pName==0);
77259   pIndex->pSchema = db->aDb[iDb].pSchema;
77260
77261   /* Check to see if we should honor DESC requests on index columns
77262   */
77263   if( pDb->pSchema->file_format>=4 ){
77264     sortOrderMask = -1;   /* Honor DESC */
77265   }else{
77266     sortOrderMask = 0;    /* Ignore DESC */
77267   }
77268
77269   /* Scan the names of the columns of the table to be indexed and
77270   ** load the column indices into the Index structure.  Report an error
77271   ** if any column is not found.
77272   **
77273   ** TODO:  Add a test to make sure that the same column is not named
77274   ** more than once within the same index.  Only the first instance of
77275   ** the column will ever be used by the optimizer.  Note that using the
77276   ** same column more than once cannot be an error because that would 
77277   ** break backwards compatibility - it needs to be a warning.
77278   */
77279   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
77280     const char *zColName = pListItem->zName;
77281     Column *pTabCol;
77282     int requestedSortOrder;
77283     char *zColl;                   /* Collation sequence name */
77284
77285     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
77286       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
77287     }
77288     if( j>=pTab->nCol ){
77289       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
77290         pTab->zName, zColName);
77291       pParse->checkSchema = 1;
77292       goto exit_create_index;
77293     }
77294     pIndex->aiColumn[i] = j;
77295     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
77296     ** the way the "idxlist" non-terminal is constructed by the parser,
77297     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
77298     ** must exist or else there must have been an OOM error.  But if there
77299     ** was an OOM error, we would never reach this point. */
77300     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
77301       int nColl;
77302       zColl = pListItem->pExpr->pColl->zName;
77303       nColl = sqlite3Strlen30(zColl) + 1;
77304       assert( nExtra>=nColl );
77305       memcpy(zExtra, zColl, nColl);
77306       zColl = zExtra;
77307       zExtra += nColl;
77308       nExtra -= nColl;
77309     }else{
77310       zColl = pTab->aCol[j].zColl;
77311       if( !zColl ){
77312         zColl = db->pDfltColl->zName;
77313       }
77314     }
77315     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
77316       goto exit_create_index;
77317     }
77318     pIndex->azColl[i] = zColl;
77319     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
77320     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
77321   }
77322   sqlite3DefaultRowEst(pIndex);
77323
77324   if( pTab==pParse->pNewTable ){
77325     /* This routine has been called to create an automatic index as a
77326     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
77327     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
77328     ** i.e. one of:
77329     **
77330     ** CREATE TABLE t(x PRIMARY KEY, y);
77331     ** CREATE TABLE t(x, y, UNIQUE(x, y));
77332     **
77333     ** Either way, check to see if the table already has such an index. If
77334     ** so, don't bother creating this one. This only applies to
77335     ** automatically created indices. Users can do as they wish with
77336     ** explicit indices.
77337     **
77338     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
77339     ** (and thus suppressing the second one) even if they have different
77340     ** sort orders.
77341     **
77342     ** If there are different collating sequences or if the columns of
77343     ** the constraint occur in different orders, then the constraints are
77344     ** considered distinct and both result in separate indices.
77345     */
77346     Index *pIdx;
77347     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77348       int k;
77349       assert( pIdx->onError!=OE_None );
77350       assert( pIdx->autoIndex );
77351       assert( pIndex->onError!=OE_None );
77352
77353       if( pIdx->nColumn!=pIndex->nColumn ) continue;
77354       for(k=0; k<pIdx->nColumn; k++){
77355         const char *z1;
77356         const char *z2;
77357         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
77358         z1 = pIdx->azColl[k];
77359         z2 = pIndex->azColl[k];
77360         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
77361       }
77362       if( k==pIdx->nColumn ){
77363         if( pIdx->onError!=pIndex->onError ){
77364           /* This constraint creates the same index as a previous
77365           ** constraint specified somewhere in the CREATE TABLE statement.
77366           ** However the ON CONFLICT clauses are different. If both this 
77367           ** constraint and the previous equivalent constraint have explicit
77368           ** ON CONFLICT clauses this is an error. Otherwise, use the
77369           ** explicitly specified behaviour for the index.
77370           */
77371           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
77372             sqlite3ErrorMsg(pParse, 
77373                 "conflicting ON CONFLICT clauses specified", 0);
77374           }
77375           if( pIdx->onError==OE_Default ){
77376             pIdx->onError = pIndex->onError;
77377           }
77378         }
77379         goto exit_create_index;
77380       }
77381     }
77382   }
77383
77384   /* Link the new Index structure to its table and to the other
77385   ** in-memory database structures. 
77386   */
77387   if( db->init.busy ){
77388     Index *p;
77389     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
77390                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
77391                           pIndex);
77392     if( p ){
77393       assert( p==pIndex );  /* Malloc must have failed */
77394       db->mallocFailed = 1;
77395       goto exit_create_index;
77396     }
77397     db->flags |= SQLITE_InternChanges;
77398     if( pTblName!=0 ){
77399       pIndex->tnum = db->init.newTnum;
77400     }
77401   }
77402
77403   /* If the db->init.busy is 0 then create the index on disk.  This
77404   ** involves writing the index into the master table and filling in the
77405   ** index with the current table contents.
77406   **
77407   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
77408   ** command.  db->init.busy is 1 when a database is opened and 
77409   ** CREATE INDEX statements are read out of the master table.  In
77410   ** the latter case the index already exists on disk, which is why
77411   ** we don't want to recreate it.
77412   **
77413   ** If pTblName==0 it means this index is generated as a primary key
77414   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
77415   ** has just been created, it contains no data and the index initialization
77416   ** step can be skipped.
77417   */
77418   else{ /* if( db->init.busy==0 ) */
77419     Vdbe *v;
77420     char *zStmt;
77421     int iMem = ++pParse->nMem;
77422
77423     v = sqlite3GetVdbe(pParse);
77424     if( v==0 ) goto exit_create_index;
77425
77426
77427     /* Create the rootpage for the index
77428     */
77429     sqlite3BeginWriteOperation(pParse, 1, iDb);
77430     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
77431
77432     /* Gather the complete text of the CREATE INDEX statement into
77433     ** the zStmt variable
77434     */
77435     if( pStart ){
77436       assert( pEnd!=0 );
77437       /* A named index with an explicit CREATE INDEX statement */
77438       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
77439         onError==OE_None ? "" : " UNIQUE",
77440         pEnd->z - pName->z + 1,
77441         pName->z);
77442     }else{
77443       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
77444       /* zStmt = sqlite3MPrintf(""); */
77445       zStmt = 0;
77446     }
77447
77448     /* Add an entry in sqlite_master for this index
77449     */
77450     sqlite3NestedParse(pParse, 
77451         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
77452         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
77453         pIndex->zName,
77454         pTab->zName,
77455         iMem,
77456         zStmt
77457     );
77458     sqlite3DbFree(db, zStmt);
77459
77460     /* Fill the index with data and reparse the schema. Code an OP_Expire
77461     ** to invalidate all pre-compiled statements.
77462     */
77463     if( pTblName ){
77464       sqlite3RefillIndex(pParse, pIndex, iMem);
77465       sqlite3ChangeCookie(pParse, iDb);
77466       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
77467          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 
77468          P4_DYNAMIC);
77469       sqlite3VdbeAddOp1(v, OP_Expire, 0);
77470     }
77471   }
77472
77473   /* When adding an index to the list of indices for a table, make
77474   ** sure all indices labeled OE_Replace come after all those labeled
77475   ** OE_Ignore.  This is necessary for the correct constraint check
77476   ** processing (in sqlite3GenerateConstraintChecks()) as part of
77477   ** UPDATE and INSERT statements.  
77478   */
77479   if( db->init.busy || pTblName==0 ){
77480     if( onError!=OE_Replace || pTab->pIndex==0
77481          || pTab->pIndex->onError==OE_Replace){
77482       pIndex->pNext = pTab->pIndex;
77483       pTab->pIndex = pIndex;
77484     }else{
77485       Index *pOther = pTab->pIndex;
77486       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
77487         pOther = pOther->pNext;
77488       }
77489       pIndex->pNext = pOther->pNext;
77490       pOther->pNext = pIndex;
77491     }
77492     pRet = pIndex;
77493     pIndex = 0;
77494   }
77495
77496   /* Clean up before exiting */
77497 exit_create_index:
77498   if( pIndex ){
77499     sqlite3DbFree(db, pIndex->zColAff);
77500     sqlite3DbFree(db, pIndex);
77501   }
77502   sqlite3ExprListDelete(db, pList);
77503   sqlite3SrcListDelete(db, pTblName);
77504   sqlite3DbFree(db, zName);
77505   return pRet;
77506 }
77507
77508 /*
77509 ** Fill the Index.aiRowEst[] array with default information - information
77510 ** to be used when we have not run the ANALYZE command.
77511 **
77512 ** aiRowEst[0] is suppose to contain the number of elements in the index.
77513 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
77514 ** number of rows in the table that match any particular value of the
77515 ** first column of the index.  aiRowEst[2] is an estimate of the number
77516 ** of rows that match any particular combiniation of the first 2 columns
77517 ** of the index.  And so forth.  It must always be the case that
77518 *
77519 **           aiRowEst[N]<=aiRowEst[N-1]
77520 **           aiRowEst[N]>=1
77521 **
77522 ** Apart from that, we have little to go on besides intuition as to
77523 ** how aiRowEst[] should be initialized.  The numbers generated here
77524 ** are based on typical values found in actual indices.
77525 */
77526 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
77527   unsigned *a = pIdx->aiRowEst;
77528   int i;
77529   unsigned n;
77530   assert( a!=0 );
77531   a[0] = pIdx->pTable->nRowEst;
77532   if( a[0]<10 ) a[0] = 10;
77533   n = 10;
77534   for(i=1; i<=pIdx->nColumn; i++){
77535     a[i] = n;
77536     if( n>5 ) n--;
77537   }
77538   if( pIdx->onError!=OE_None ){
77539     a[pIdx->nColumn] = 1;
77540   }
77541 }
77542
77543 /*
77544 ** This routine will drop an existing named index.  This routine
77545 ** implements the DROP INDEX statement.
77546 */
77547 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
77548   Index *pIndex;
77549   Vdbe *v;
77550   sqlite3 *db = pParse->db;
77551   int iDb;
77552
77553   assert( pParse->nErr==0 );   /* Never called with prior errors */
77554   if( db->mallocFailed ){
77555     goto exit_drop_index;
77556   }
77557   assert( pName->nSrc==1 );
77558   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
77559     goto exit_drop_index;
77560   }
77561   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
77562   if( pIndex==0 ){
77563     if( !ifExists ){
77564       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
77565     }
77566     pParse->checkSchema = 1;
77567     goto exit_drop_index;
77568   }
77569   if( pIndex->autoIndex ){
77570     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
77571       "or PRIMARY KEY constraint cannot be dropped", 0);
77572     goto exit_drop_index;
77573   }
77574   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
77575 #ifndef SQLITE_OMIT_AUTHORIZATION
77576   {
77577     int code = SQLITE_DROP_INDEX;
77578     Table *pTab = pIndex->pTable;
77579     const char *zDb = db->aDb[iDb].zName;
77580     const char *zTab = SCHEMA_TABLE(iDb);
77581     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
77582       goto exit_drop_index;
77583     }
77584     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
77585     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
77586       goto exit_drop_index;
77587     }
77588   }
77589 #endif
77590
77591   /* Generate code to remove the index and from the master table */
77592   v = sqlite3GetVdbe(pParse);
77593   if( v ){
77594     sqlite3BeginWriteOperation(pParse, 1, iDb);
77595     sqlite3NestedParse(pParse,
77596        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
77597        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
77598        pIndex->zName
77599     );
77600     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
77601       sqlite3NestedParse(pParse,
77602         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
77603         db->aDb[iDb].zName, pIndex->zName
77604       );
77605     }
77606     sqlite3ChangeCookie(pParse, iDb);
77607     destroyRootPage(pParse, pIndex->tnum, iDb);
77608     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
77609   }
77610
77611 exit_drop_index:
77612   sqlite3SrcListDelete(db, pName);
77613 }
77614
77615 /*
77616 ** pArray is a pointer to an array of objects.  Each object in the
77617 ** array is szEntry bytes in size.  This routine allocates a new
77618 ** object on the end of the array.
77619 **
77620 ** *pnEntry is the number of entries already in use.  *pnAlloc is
77621 ** the previously allocated size of the array.  initSize is the
77622 ** suggested initial array size allocation.
77623 **
77624 ** The index of the new entry is returned in *pIdx.
77625 **
77626 ** This routine returns a pointer to the array of objects.  This
77627 ** might be the same as the pArray parameter or it might be a different
77628 ** pointer if the array was resized.
77629 */
77630 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
77631   sqlite3 *db,      /* Connection to notify of malloc failures */
77632   void *pArray,     /* Array of objects.  Might be reallocated */
77633   int szEntry,      /* Size of each object in the array */
77634   int initSize,     /* Suggested initial allocation, in elements */
77635   int *pnEntry,     /* Number of objects currently in use */
77636   int *pnAlloc,     /* Current size of the allocation, in elements */
77637   int *pIdx         /* Write the index of a new slot here */
77638 ){
77639   char *z;
77640   if( *pnEntry >= *pnAlloc ){
77641     void *pNew;
77642     int newSize;
77643     newSize = (*pnAlloc)*2 + initSize;
77644     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
77645     if( pNew==0 ){
77646       *pIdx = -1;
77647       return pArray;
77648     }
77649     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
77650     pArray = pNew;
77651   }
77652   z = (char*)pArray;
77653   memset(&z[*pnEntry * szEntry], 0, szEntry);
77654   *pIdx = *pnEntry;
77655   ++*pnEntry;
77656   return pArray;
77657 }
77658
77659 /*
77660 ** Append a new element to the given IdList.  Create a new IdList if
77661 ** need be.
77662 **
77663 ** A new IdList is returned, or NULL if malloc() fails.
77664 */
77665 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
77666   int i;
77667   if( pList==0 ){
77668     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
77669     if( pList==0 ) return 0;
77670     pList->nAlloc = 0;
77671   }
77672   pList->a = sqlite3ArrayAllocate(
77673       db,
77674       pList->a,
77675       sizeof(pList->a[0]),
77676       5,
77677       &pList->nId,
77678       &pList->nAlloc,
77679       &i
77680   );
77681   if( i<0 ){
77682     sqlite3IdListDelete(db, pList);
77683     return 0;
77684   }
77685   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
77686   return pList;
77687 }
77688
77689 /*
77690 ** Delete an IdList.
77691 */
77692 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
77693   int i;
77694   if( pList==0 ) return;
77695   for(i=0; i<pList->nId; i++){
77696     sqlite3DbFree(db, pList->a[i].zName);
77697   }
77698   sqlite3DbFree(db, pList->a);
77699   sqlite3DbFree(db, pList);
77700 }
77701
77702 /*
77703 ** Return the index in pList of the identifier named zId.  Return -1
77704 ** if not found.
77705 */
77706 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
77707   int i;
77708   if( pList==0 ) return -1;
77709   for(i=0; i<pList->nId; i++){
77710     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
77711   }
77712   return -1;
77713 }
77714
77715 /*
77716 ** Expand the space allocated for the given SrcList object by
77717 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
77718 ** New slots are zeroed.
77719 **
77720 ** For example, suppose a SrcList initially contains two entries: A,B.
77721 ** To append 3 new entries onto the end, do this:
77722 **
77723 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
77724 **
77725 ** After the call above it would contain:  A, B, nil, nil, nil.
77726 ** If the iStart argument had been 1 instead of 2, then the result
77727 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
77728 ** the iStart value would be 0.  The result then would
77729 ** be: nil, nil, nil, A, B.
77730 **
77731 ** If a memory allocation fails the SrcList is unchanged.  The
77732 ** db->mallocFailed flag will be set to true.
77733 */
77734 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
77735   sqlite3 *db,       /* Database connection to notify of OOM errors */
77736   SrcList *pSrc,     /* The SrcList to be enlarged */
77737   int nExtra,        /* Number of new slots to add to pSrc->a[] */
77738   int iStart         /* Index in pSrc->a[] of first new slot */
77739 ){
77740   int i;
77741
77742   /* Sanity checking on calling parameters */
77743   assert( iStart>=0 );
77744   assert( nExtra>=1 );
77745   assert( pSrc!=0 );
77746   assert( iStart<=pSrc->nSrc );
77747
77748   /* Allocate additional space if needed */
77749   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
77750     SrcList *pNew;
77751     int nAlloc = pSrc->nSrc+nExtra;
77752     int nGot;
77753     pNew = sqlite3DbRealloc(db, pSrc,
77754                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
77755     if( pNew==0 ){
77756       assert( db->mallocFailed );
77757       return pSrc;
77758     }
77759     pSrc = pNew;
77760     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
77761     pSrc->nAlloc = (u16)nGot;
77762   }
77763
77764   /* Move existing slots that come after the newly inserted slots
77765   ** out of the way */
77766   for(i=pSrc->nSrc-1; i>=iStart; i--){
77767     pSrc->a[i+nExtra] = pSrc->a[i];
77768   }
77769   pSrc->nSrc += (i16)nExtra;
77770
77771   /* Zero the newly allocated slots */
77772   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
77773   for(i=iStart; i<iStart+nExtra; i++){
77774     pSrc->a[i].iCursor = -1;
77775   }
77776
77777   /* Return a pointer to the enlarged SrcList */
77778   return pSrc;
77779 }
77780
77781
77782 /*
77783 ** Append a new table name to the given SrcList.  Create a new SrcList if
77784 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
77785 **
77786 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
77787 ** SrcList might be the same as the SrcList that was input or it might be
77788 ** a new one.  If an OOM error does occurs, then the prior value of pList
77789 ** that is input to this routine is automatically freed.
77790 **
77791 ** If pDatabase is not null, it means that the table has an optional
77792 ** database name prefix.  Like this:  "database.table".  The pDatabase
77793 ** points to the table name and the pTable points to the database name.
77794 ** The SrcList.a[].zName field is filled with the table name which might
77795 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
77796 ** SrcList.a[].zDatabase is filled with the database name from pTable,
77797 ** or with NULL if no database is specified.
77798 **
77799 ** In other words, if call like this:
77800 **
77801 **         sqlite3SrcListAppend(D,A,B,0);
77802 **
77803 ** Then B is a table name and the database name is unspecified.  If called
77804 ** like this:
77805 **
77806 **         sqlite3SrcListAppend(D,A,B,C);
77807 **
77808 ** Then C is the table name and B is the database name.  If C is defined
77809 ** then so is B.  In other words, we never have a case where:
77810 **
77811 **         sqlite3SrcListAppend(D,A,0,C);
77812 **
77813 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
77814 ** before being added to the SrcList.
77815 */
77816 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
77817   sqlite3 *db,        /* Connection to notify of malloc failures */
77818   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
77819   Token *pTable,      /* Table to append */
77820   Token *pDatabase    /* Database of the table */
77821 ){
77822   struct SrcList_item *pItem;
77823   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
77824   if( pList==0 ){
77825     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
77826     if( pList==0 ) return 0;
77827     pList->nAlloc = 1;
77828   }
77829   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
77830   if( db->mallocFailed ){
77831     sqlite3SrcListDelete(db, pList);
77832     return 0;
77833   }
77834   pItem = &pList->a[pList->nSrc-1];
77835   if( pDatabase && pDatabase->z==0 ){
77836     pDatabase = 0;
77837   }
77838   if( pDatabase ){
77839     Token *pTemp = pDatabase;
77840     pDatabase = pTable;
77841     pTable = pTemp;
77842   }
77843   pItem->zName = sqlite3NameFromToken(db, pTable);
77844   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
77845   return pList;
77846 }
77847
77848 /*
77849 ** Assign VdbeCursor index numbers to all tables in a SrcList
77850 */
77851 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
77852   int i;
77853   struct SrcList_item *pItem;
77854   assert(pList || pParse->db->mallocFailed );
77855   if( pList ){
77856     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
77857       if( pItem->iCursor>=0 ) break;
77858       pItem->iCursor = pParse->nTab++;
77859       if( pItem->pSelect ){
77860         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
77861       }
77862     }
77863   }
77864 }
77865
77866 /*
77867 ** Delete an entire SrcList including all its substructure.
77868 */
77869 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
77870   int i;
77871   struct SrcList_item *pItem;
77872   if( pList==0 ) return;
77873   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
77874     sqlite3DbFree(db, pItem->zDatabase);
77875     sqlite3DbFree(db, pItem->zName);
77876     sqlite3DbFree(db, pItem->zAlias);
77877     sqlite3DbFree(db, pItem->zIndex);
77878     sqlite3DeleteTable(db, pItem->pTab);
77879     sqlite3SelectDelete(db, pItem->pSelect);
77880     sqlite3ExprDelete(db, pItem->pOn);
77881     sqlite3IdListDelete(db, pItem->pUsing);
77882   }
77883   sqlite3DbFree(db, pList);
77884 }
77885
77886 /*
77887 ** This routine is called by the parser to add a new term to the
77888 ** end of a growing FROM clause.  The "p" parameter is the part of
77889 ** the FROM clause that has already been constructed.  "p" is NULL
77890 ** if this is the first term of the FROM clause.  pTable and pDatabase
77891 ** are the name of the table and database named in the FROM clause term.
77892 ** pDatabase is NULL if the database name qualifier is missing - the
77893 ** usual case.  If the term has a alias, then pAlias points to the
77894 ** alias token.  If the term is a subquery, then pSubquery is the
77895 ** SELECT statement that the subquery encodes.  The pTable and
77896 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
77897 ** parameters are the content of the ON and USING clauses.
77898 **
77899 ** Return a new SrcList which encodes is the FROM with the new
77900 ** term added.
77901 */
77902 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
77903   Parse *pParse,          /* Parsing context */
77904   SrcList *p,             /* The left part of the FROM clause already seen */
77905   Token *pTable,          /* Name of the table to add to the FROM clause */
77906   Token *pDatabase,       /* Name of the database containing pTable */
77907   Token *pAlias,          /* The right-hand side of the AS subexpression */
77908   Select *pSubquery,      /* A subquery used in place of a table name */
77909   Expr *pOn,              /* The ON clause of a join */
77910   IdList *pUsing          /* The USING clause of a join */
77911 ){
77912   struct SrcList_item *pItem;
77913   sqlite3 *db = pParse->db;
77914   if( !p && (pOn || pUsing) ){
77915     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
77916       (pOn ? "ON" : "USING")
77917     );
77918     goto append_from_error;
77919   }
77920   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
77921   if( p==0 || NEVER(p->nSrc==0) ){
77922     goto append_from_error;
77923   }
77924   pItem = &p->a[p->nSrc-1];
77925   assert( pAlias!=0 );
77926   if( pAlias->n ){
77927     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
77928   }
77929   pItem->pSelect = pSubquery;
77930   pItem->pOn = pOn;
77931   pItem->pUsing = pUsing;
77932   return p;
77933
77934  append_from_error:
77935   assert( p==0 );
77936   sqlite3ExprDelete(db, pOn);
77937   sqlite3IdListDelete(db, pUsing);
77938   sqlite3SelectDelete(db, pSubquery);
77939   return 0;
77940 }
77941
77942 /*
77943 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
77944 ** element of the source-list passed as the second argument.
77945 */
77946 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
77947   assert( pIndexedBy!=0 );
77948   if( p && ALWAYS(p->nSrc>0) ){
77949     struct SrcList_item *pItem = &p->a[p->nSrc-1];
77950     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
77951     if( pIndexedBy->n==1 && !pIndexedBy->z ){
77952       /* A "NOT INDEXED" clause was supplied. See parse.y 
77953       ** construct "indexed_opt" for details. */
77954       pItem->notIndexed = 1;
77955     }else{
77956       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
77957     }
77958   }
77959 }
77960
77961 /*
77962 ** When building up a FROM clause in the parser, the join operator
77963 ** is initially attached to the left operand.  But the code generator
77964 ** expects the join operator to be on the right operand.  This routine
77965 ** Shifts all join operators from left to right for an entire FROM
77966 ** clause.
77967 **
77968 ** Example: Suppose the join is like this:
77969 **
77970 **           A natural cross join B
77971 **
77972 ** The operator is "natural cross join".  The A and B operands are stored
77973 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
77974 ** operator with A.  This routine shifts that operator over to B.
77975 */
77976 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
77977   if( p && p->a ){
77978     int i;
77979     for(i=p->nSrc-1; i>0; i--){
77980       p->a[i].jointype = p->a[i-1].jointype;
77981     }
77982     p->a[0].jointype = 0;
77983   }
77984 }
77985
77986 /*
77987 ** Begin a transaction
77988 */
77989 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
77990   sqlite3 *db;
77991   Vdbe *v;
77992   int i;
77993
77994   assert( pParse!=0 );
77995   db = pParse->db;
77996   assert( db!=0 );
77997 /*  if( db->aDb[0].pBt==0 ) return; */
77998   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
77999     return;
78000   }
78001   v = sqlite3GetVdbe(pParse);
78002   if( !v ) return;
78003   if( type!=TK_DEFERRED ){
78004     for(i=0; i<db->nDb; i++){
78005       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
78006       sqlite3VdbeUsesBtree(v, i);
78007     }
78008   }
78009   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
78010 }
78011
78012 /*
78013 ** Commit a transaction
78014 */
78015 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
78016   sqlite3 *db;
78017   Vdbe *v;
78018
78019   assert( pParse!=0 );
78020   db = pParse->db;
78021   assert( db!=0 );
78022 /*  if( db->aDb[0].pBt==0 ) return; */
78023   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
78024     return;
78025   }
78026   v = sqlite3GetVdbe(pParse);
78027   if( v ){
78028     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
78029   }
78030 }
78031
78032 /*
78033 ** Rollback a transaction
78034 */
78035 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
78036   sqlite3 *db;
78037   Vdbe *v;
78038
78039   assert( pParse!=0 );
78040   db = pParse->db;
78041   assert( db!=0 );
78042 /*  if( db->aDb[0].pBt==0 ) return; */
78043   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
78044     return;
78045   }
78046   v = sqlite3GetVdbe(pParse);
78047   if( v ){
78048     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
78049   }
78050 }
78051
78052 /*
78053 ** This function is called by the parser when it parses a command to create,
78054 ** release or rollback an SQL savepoint. 
78055 */
78056 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
78057   char *zName = sqlite3NameFromToken(pParse->db, pName);
78058   if( zName ){
78059     Vdbe *v = sqlite3GetVdbe(pParse);
78060 #ifndef SQLITE_OMIT_AUTHORIZATION
78061     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
78062     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
78063 #endif
78064     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
78065       sqlite3DbFree(pParse->db, zName);
78066       return;
78067     }
78068     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
78069   }
78070 }
78071
78072 /*
78073 ** Make sure the TEMP database is open and available for use.  Return
78074 ** the number of errors.  Leave any error messages in the pParse structure.
78075 */
78076 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
78077   sqlite3 *db = pParse->db;
78078   if( db->aDb[1].pBt==0 && !pParse->explain ){
78079     int rc;
78080     Btree *pBt;
78081     static const int flags = 
78082           SQLITE_OPEN_READWRITE |
78083           SQLITE_OPEN_CREATE |
78084           SQLITE_OPEN_EXCLUSIVE |
78085           SQLITE_OPEN_DELETEONCLOSE |
78086           SQLITE_OPEN_TEMP_DB;
78087
78088     rc = sqlite3BtreeOpen(0, db, &pBt, 0, flags);
78089     if( rc!=SQLITE_OK ){
78090       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
78091         "file for storing temporary tables");
78092       pParse->rc = rc;
78093       return 1;
78094     }
78095     db->aDb[1].pBt = pBt;
78096     assert( db->aDb[1].pSchema );
78097     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
78098       db->mallocFailed = 1;
78099       return 1;
78100     }
78101   }
78102   return 0;
78103 }
78104
78105 /*
78106 ** Generate VDBE code that will verify the schema cookie and start
78107 ** a read-transaction for all named database files.
78108 **
78109 ** It is important that all schema cookies be verified and all
78110 ** read transactions be started before anything else happens in
78111 ** the VDBE program.  But this routine can be called after much other
78112 ** code has been generated.  So here is what we do:
78113 **
78114 ** The first time this routine is called, we code an OP_Goto that
78115 ** will jump to a subroutine at the end of the program.  Then we
78116 ** record every database that needs its schema verified in the
78117 ** pParse->cookieMask field.  Later, after all other code has been
78118 ** generated, the subroutine that does the cookie verifications and
78119 ** starts the transactions will be coded and the OP_Goto P2 value
78120 ** will be made to point to that subroutine.  The generation of the
78121 ** cookie verification subroutine code happens in sqlite3FinishCoding().
78122 **
78123 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
78124 ** schema on any databases.  This can be used to position the OP_Goto
78125 ** early in the code, before we know if any database tables will be used.
78126 */
78127 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
78128   Parse *pToplevel = sqlite3ParseToplevel(pParse);
78129
78130   if( pToplevel->cookieGoto==0 ){
78131     Vdbe *v = sqlite3GetVdbe(pToplevel);
78132     if( v==0 ) return;  /* This only happens if there was a prior error */
78133     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
78134   }
78135   if( iDb>=0 ){
78136     sqlite3 *db = pToplevel->db;
78137     int mask;
78138
78139     assert( iDb<db->nDb );
78140     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
78141     assert( iDb<SQLITE_MAX_ATTACHED+2 );
78142     mask = 1<<iDb;
78143     if( (pToplevel->cookieMask & mask)==0 ){
78144       pToplevel->cookieMask |= mask;
78145       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
78146       if( !OMIT_TEMPDB && iDb==1 ){
78147         sqlite3OpenTempDatabase(pToplevel);
78148       }
78149     }
78150   }
78151 }
78152
78153 /*
78154 ** Generate VDBE code that prepares for doing an operation that
78155 ** might change the database.
78156 **
78157 ** This routine starts a new transaction if we are not already within
78158 ** a transaction.  If we are already within a transaction, then a checkpoint
78159 ** is set if the setStatement parameter is true.  A checkpoint should
78160 ** be set for operations that might fail (due to a constraint) part of
78161 ** the way through and which will need to undo some writes without having to
78162 ** rollback the whole transaction.  For operations where all constraints
78163 ** can be checked before any changes are made to the database, it is never
78164 ** necessary to undo a write and the checkpoint should not be set.
78165 */
78166 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
78167   Parse *pToplevel = sqlite3ParseToplevel(pParse);
78168   sqlite3CodeVerifySchema(pParse, iDb);
78169   pToplevel->writeMask |= 1<<iDb;
78170   pToplevel->isMultiWrite |= setStatement;
78171 }
78172
78173 /*
78174 ** Indicate that the statement currently under construction might write
78175 ** more than one entry (example: deleting one row then inserting another,
78176 ** inserting multiple rows in a table, or inserting a row and index entries.)
78177 ** If an abort occurs after some of these writes have completed, then it will
78178 ** be necessary to undo the completed writes.
78179 */
78180 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
78181   Parse *pToplevel = sqlite3ParseToplevel(pParse);
78182   pToplevel->isMultiWrite = 1;
78183 }
78184
78185 /* 
78186 ** The code generator calls this routine if is discovers that it is
78187 ** possible to abort a statement prior to completion.  In order to 
78188 ** perform this abort without corrupting the database, we need to make
78189 ** sure that the statement is protected by a statement transaction.
78190 **
78191 ** Technically, we only need to set the mayAbort flag if the
78192 ** isMultiWrite flag was previously set.  There is a time dependency
78193 ** such that the abort must occur after the multiwrite.  This makes
78194 ** some statements involving the REPLACE conflict resolution algorithm
78195 ** go a little faster.  But taking advantage of this time dependency
78196 ** makes it more difficult to prove that the code is correct (in 
78197 ** particular, it prevents us from writing an effective
78198 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
78199 ** to take the safe route and skip the optimization.
78200 */
78201 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
78202   Parse *pToplevel = sqlite3ParseToplevel(pParse);
78203   pToplevel->mayAbort = 1;
78204 }
78205
78206 /*
78207 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
78208 ** error. The onError parameter determines which (if any) of the statement
78209 ** and/or current transaction is rolled back.
78210 */
78211 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
78212   Vdbe *v = sqlite3GetVdbe(pParse);
78213   if( onError==OE_Abort ){
78214     sqlite3MayAbort(pParse);
78215   }
78216   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
78217 }
78218
78219 /*
78220 ** Check to see if pIndex uses the collating sequence pColl.  Return
78221 ** true if it does and false if it does not.
78222 */
78223 #ifndef SQLITE_OMIT_REINDEX
78224 static int collationMatch(const char *zColl, Index *pIndex){
78225   int i;
78226   assert( zColl!=0 );
78227   for(i=0; i<pIndex->nColumn; i++){
78228     const char *z = pIndex->azColl[i];
78229     assert( z!=0 );
78230     if( 0==sqlite3StrICmp(z, zColl) ){
78231       return 1;
78232     }
78233   }
78234   return 0;
78235 }
78236 #endif
78237
78238 /*
78239 ** Recompute all indices of pTab that use the collating sequence pColl.
78240 ** If pColl==0 then recompute all indices of pTab.
78241 */
78242 #ifndef SQLITE_OMIT_REINDEX
78243 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
78244   Index *pIndex;              /* An index associated with pTab */
78245
78246   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
78247     if( zColl==0 || collationMatch(zColl, pIndex) ){
78248       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78249       sqlite3BeginWriteOperation(pParse, 0, iDb);
78250       sqlite3RefillIndex(pParse, pIndex, -1);
78251     }
78252   }
78253 }
78254 #endif
78255
78256 /*
78257 ** Recompute all indices of all tables in all databases where the
78258 ** indices use the collating sequence pColl.  If pColl==0 then recompute
78259 ** all indices everywhere.
78260 */
78261 #ifndef SQLITE_OMIT_REINDEX
78262 static void reindexDatabases(Parse *pParse, char const *zColl){
78263   Db *pDb;                    /* A single database */
78264   int iDb;                    /* The database index number */
78265   sqlite3 *db = pParse->db;   /* The database connection */
78266   HashElem *k;                /* For looping over tables in pDb */
78267   Table *pTab;                /* A table in the database */
78268
78269   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
78270     assert( pDb!=0 );
78271     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
78272       pTab = (Table*)sqliteHashData(k);
78273       reindexTable(pParse, pTab, zColl);
78274     }
78275   }
78276 }
78277 #endif
78278
78279 /*
78280 ** Generate code for the REINDEX command.
78281 **
78282 **        REINDEX                            -- 1
78283 **        REINDEX  <collation>               -- 2
78284 **        REINDEX  ?<database>.?<tablename>  -- 3
78285 **        REINDEX  ?<database>.?<indexname>  -- 4
78286 **
78287 ** Form 1 causes all indices in all attached databases to be rebuilt.
78288 ** Form 2 rebuilds all indices in all databases that use the named
78289 ** collating function.  Forms 3 and 4 rebuild the named index or all
78290 ** indices associated with the named table.
78291 */
78292 #ifndef SQLITE_OMIT_REINDEX
78293 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
78294   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
78295   char *z;                    /* Name of a table or index */
78296   const char *zDb;            /* Name of the database */
78297   Table *pTab;                /* A table in the database */
78298   Index *pIndex;              /* An index associated with pTab */
78299   int iDb;                    /* The database index number */
78300   sqlite3 *db = pParse->db;   /* The database connection */
78301   Token *pObjName;            /* Name of the table or index to be reindexed */
78302
78303   /* Read the database schema. If an error occurs, leave an error message
78304   ** and code in pParse and return NULL. */
78305   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
78306     return;
78307   }
78308
78309   if( pName1==0 ){
78310     reindexDatabases(pParse, 0);
78311     return;
78312   }else if( NEVER(pName2==0) || pName2->z==0 ){
78313     char *zColl;
78314     assert( pName1->z );
78315     zColl = sqlite3NameFromToken(pParse->db, pName1);
78316     if( !zColl ) return;
78317     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
78318     if( pColl ){
78319       reindexDatabases(pParse, zColl);
78320       sqlite3DbFree(db, zColl);
78321       return;
78322     }
78323     sqlite3DbFree(db, zColl);
78324   }
78325   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
78326   if( iDb<0 ) return;
78327   z = sqlite3NameFromToken(db, pObjName);
78328   if( z==0 ) return;
78329   zDb = db->aDb[iDb].zName;
78330   pTab = sqlite3FindTable(db, z, zDb);
78331   if( pTab ){
78332     reindexTable(pParse, pTab, 0);
78333     sqlite3DbFree(db, z);
78334     return;
78335   }
78336   pIndex = sqlite3FindIndex(db, z, zDb);
78337   sqlite3DbFree(db, z);
78338   if( pIndex ){
78339     sqlite3BeginWriteOperation(pParse, 0, iDb);
78340     sqlite3RefillIndex(pParse, pIndex, -1);
78341     return;
78342   }
78343   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
78344 }
78345 #endif
78346
78347 /*
78348 ** Return a dynamicly allocated KeyInfo structure that can be used
78349 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
78350 **
78351 ** If successful, a pointer to the new structure is returned. In this case
78352 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
78353 ** pointer. If an error occurs (out of memory or missing collation 
78354 ** sequence), NULL is returned and the state of pParse updated to reflect
78355 ** the error.
78356 */
78357 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
78358   int i;
78359   int nCol = pIdx->nColumn;
78360   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
78361   sqlite3 *db = pParse->db;
78362   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
78363
78364   if( pKey ){
78365     pKey->db = pParse->db;
78366     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
78367     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
78368     for(i=0; i<nCol; i++){
78369       char *zColl = pIdx->azColl[i];
78370       assert( zColl );
78371       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
78372       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
78373     }
78374     pKey->nField = (u16)nCol;
78375   }
78376
78377   if( pParse->nErr ){
78378     sqlite3DbFree(db, pKey);
78379     pKey = 0;
78380   }
78381   return pKey;
78382 }
78383
78384 /************** End of build.c ***********************************************/
78385 /************** Begin file callback.c ****************************************/
78386 /*
78387 ** 2005 May 23 
78388 **
78389 ** The author disclaims copyright to this source code.  In place of
78390 ** a legal notice, here is a blessing:
78391 **
78392 **    May you do good and not evil.
78393 **    May you find forgiveness for yourself and forgive others.
78394 **    May you share freely, never taking more than you give.
78395 **
78396 *************************************************************************
78397 **
78398 ** This file contains functions used to access the internal hash tables
78399 ** of user defined functions and collation sequences.
78400 */
78401
78402
78403 /*
78404 ** Invoke the 'collation needed' callback to request a collation sequence
78405 ** in the encoding enc of name zName, length nName.
78406 */
78407 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
78408   assert( !db->xCollNeeded || !db->xCollNeeded16 );
78409   if( db->xCollNeeded ){
78410     char *zExternal = sqlite3DbStrDup(db, zName);
78411     if( !zExternal ) return;
78412     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
78413     sqlite3DbFree(db, zExternal);
78414   }
78415 #ifndef SQLITE_OMIT_UTF16
78416   if( db->xCollNeeded16 ){
78417     char const *zExternal;
78418     sqlite3_value *pTmp = sqlite3ValueNew(db);
78419     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
78420     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
78421     if( zExternal ){
78422       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
78423     }
78424     sqlite3ValueFree(pTmp);
78425   }
78426 #endif
78427 }
78428
78429 /*
78430 ** This routine is called if the collation factory fails to deliver a
78431 ** collation function in the best encoding but there may be other versions
78432 ** of this collation function (for other text encodings) available. Use one
78433 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
78434 ** possible.
78435 */
78436 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
78437   CollSeq *pColl2;
78438   char *z = pColl->zName;
78439   int i;
78440   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
78441   for(i=0; i<3; i++){
78442     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
78443     if( pColl2->xCmp!=0 ){
78444       memcpy(pColl, pColl2, sizeof(CollSeq));
78445       pColl->xDel = 0;         /* Do not copy the destructor */
78446       return SQLITE_OK;
78447     }
78448   }
78449   return SQLITE_ERROR;
78450 }
78451
78452 /*
78453 ** This function is responsible for invoking the collation factory callback
78454 ** or substituting a collation sequence of a different encoding when the
78455 ** requested collation sequence is not available in the desired encoding.
78456 ** 
78457 ** If it is not NULL, then pColl must point to the database native encoding 
78458 ** collation sequence with name zName, length nName.
78459 **
78460 ** The return value is either the collation sequence to be used in database
78461 ** db for collation type name zName, length nName, or NULL, if no collation
78462 ** sequence can be found.
78463 **
78464 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
78465 */
78466 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
78467   sqlite3* db,          /* The database connection */
78468   u8 enc,               /* The desired encoding for the collating sequence */
78469   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
78470   const char *zName     /* Collating sequence name */
78471 ){
78472   CollSeq *p;
78473
78474   p = pColl;
78475   if( !p ){
78476     p = sqlite3FindCollSeq(db, enc, zName, 0);
78477   }
78478   if( !p || !p->xCmp ){
78479     /* No collation sequence of this type for this encoding is registered.
78480     ** Call the collation factory to see if it can supply us with one.
78481     */
78482     callCollNeeded(db, enc, zName);
78483     p = sqlite3FindCollSeq(db, enc, zName, 0);
78484   }
78485   if( p && !p->xCmp && synthCollSeq(db, p) ){
78486     p = 0;
78487   }
78488   assert( !p || p->xCmp );
78489   return p;
78490 }
78491
78492 /*
78493 ** This routine is called on a collation sequence before it is used to
78494 ** check that it is defined. An undefined collation sequence exists when
78495 ** a database is loaded that contains references to collation sequences
78496 ** that have not been defined by sqlite3_create_collation() etc.
78497 **
78498 ** If required, this routine calls the 'collation needed' callback to
78499 ** request a definition of the collating sequence. If this doesn't work, 
78500 ** an equivalent collating sequence that uses a text encoding different
78501 ** from the main database is substituted, if one is available.
78502 */
78503 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
78504   if( pColl ){
78505     const char *zName = pColl->zName;
78506     sqlite3 *db = pParse->db;
78507     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
78508     if( !p ){
78509       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
78510       pParse->nErr++;
78511       return SQLITE_ERROR;
78512     }
78513     assert( p==pColl );
78514   }
78515   return SQLITE_OK;
78516 }
78517
78518
78519
78520 /*
78521 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
78522 ** specified by zName and nName is not found and parameter 'create' is
78523 ** true, then create a new entry. Otherwise return NULL.
78524 **
78525 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
78526 ** array of three CollSeq structures. The first is the collation sequence
78527 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
78528 **
78529 ** Stored immediately after the three collation sequences is a copy of
78530 ** the collation sequence name. A pointer to this string is stored in
78531 ** each collation sequence structure.
78532 */
78533 static CollSeq *findCollSeqEntry(
78534   sqlite3 *db,          /* Database connection */
78535   const char *zName,    /* Name of the collating sequence */
78536   int create            /* Create a new entry if true */
78537 ){
78538   CollSeq *pColl;
78539   int nName = sqlite3Strlen30(zName);
78540   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
78541
78542   if( 0==pColl && create ){
78543     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
78544     if( pColl ){
78545       CollSeq *pDel = 0;
78546       pColl[0].zName = (char*)&pColl[3];
78547       pColl[0].enc = SQLITE_UTF8;
78548       pColl[1].zName = (char*)&pColl[3];
78549       pColl[1].enc = SQLITE_UTF16LE;
78550       pColl[2].zName = (char*)&pColl[3];
78551       pColl[2].enc = SQLITE_UTF16BE;
78552       memcpy(pColl[0].zName, zName, nName);
78553       pColl[0].zName[nName] = 0;
78554       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
78555
78556       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
78557       ** return the pColl pointer to be deleted (because it wasn't added
78558       ** to the hash table).
78559       */
78560       assert( pDel==0 || pDel==pColl );
78561       if( pDel!=0 ){
78562         db->mallocFailed = 1;
78563         sqlite3DbFree(db, pDel);
78564         pColl = 0;
78565       }
78566     }
78567   }
78568   return pColl;
78569 }
78570
78571 /*
78572 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
78573 ** Return the CollSeq* pointer for the collation sequence named zName
78574 ** for the encoding 'enc' from the database 'db'.
78575 **
78576 ** If the entry specified is not found and 'create' is true, then create a
78577 ** new entry.  Otherwise return NULL.
78578 **
78579 ** A separate function sqlite3LocateCollSeq() is a wrapper around
78580 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
78581 ** if necessary and generates an error message if the collating sequence
78582 ** cannot be found.
78583 **
78584 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
78585 */
78586 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
78587   sqlite3 *db,
78588   u8 enc,
78589   const char *zName,
78590   int create
78591 ){
78592   CollSeq *pColl;
78593   if( zName ){
78594     pColl = findCollSeqEntry(db, zName, create);
78595   }else{
78596     pColl = db->pDfltColl;
78597   }
78598   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
78599   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
78600   if( pColl ) pColl += enc-1;
78601   return pColl;
78602 }
78603
78604 /* During the search for the best function definition, this procedure
78605 ** is called to test how well the function passed as the first argument
78606 ** matches the request for a function with nArg arguments in a system
78607 ** that uses encoding enc. The value returned indicates how well the
78608 ** request is matched. A higher value indicates a better match.
78609 **
78610 ** The returned value is always between 0 and 6, as follows:
78611 **
78612 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
78613 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
78614 **    encoding is requested, or vice versa.
78615 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
78616 **    requested, or vice versa.
78617 ** 3: A variable arguments function using the same text encoding.
78618 ** 4: A function with the exact number of arguments requested that
78619 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
78620 ** 5: A function with the exact number of arguments requested that
78621 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
78622 ** 6: An exact match.
78623 **
78624 */
78625 static int matchQuality(FuncDef *p, int nArg, u8 enc){
78626   int match = 0;
78627   if( p->nArg==-1 || p->nArg==nArg 
78628    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
78629   ){
78630     match = 1;
78631     if( p->nArg==nArg || nArg==-1 ){
78632       match = 4;
78633     }
78634     if( enc==p->iPrefEnc ){
78635       match += 2;
78636     }
78637     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
78638              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
78639       match += 1;
78640     }
78641   }
78642   return match;
78643 }
78644
78645 /*
78646 ** Search a FuncDefHash for a function with the given name.  Return
78647 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
78648 */
78649 static FuncDef *functionSearch(
78650   FuncDefHash *pHash,  /* Hash table to search */
78651   int h,               /* Hash of the name */
78652   const char *zFunc,   /* Name of function */
78653   int nFunc            /* Number of bytes in zFunc */
78654 ){
78655   FuncDef *p;
78656   for(p=pHash->a[h]; p; p=p->pHash){
78657     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
78658       return p;
78659     }
78660   }
78661   return 0;
78662 }
78663
78664 /*
78665 ** Insert a new FuncDef into a FuncDefHash hash table.
78666 */
78667 SQLITE_PRIVATE void sqlite3FuncDefInsert(
78668   FuncDefHash *pHash,  /* The hash table into which to insert */
78669   FuncDef *pDef        /* The function definition to insert */
78670 ){
78671   FuncDef *pOther;
78672   int nName = sqlite3Strlen30(pDef->zName);
78673   u8 c1 = (u8)pDef->zName[0];
78674   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
78675   pOther = functionSearch(pHash, h, pDef->zName, nName);
78676   if( pOther ){
78677     assert( pOther!=pDef && pOther->pNext!=pDef );
78678     pDef->pNext = pOther->pNext;
78679     pOther->pNext = pDef;
78680   }else{
78681     pDef->pNext = 0;
78682     pDef->pHash = pHash->a[h];
78683     pHash->a[h] = pDef;
78684   }
78685 }
78686   
78687   
78688
78689 /*
78690 ** Locate a user function given a name, a number of arguments and a flag
78691 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
78692 ** pointer to the FuncDef structure that defines that function, or return
78693 ** NULL if the function does not exist.
78694 **
78695 ** If the createFlag argument is true, then a new (blank) FuncDef
78696 ** structure is created and liked into the "db" structure if a
78697 ** no matching function previously existed.  When createFlag is true
78698 ** and the nArg parameter is -1, then only a function that accepts
78699 ** any number of arguments will be returned.
78700 **
78701 ** If createFlag is false and nArg is -1, then the first valid
78702 ** function found is returned.  A function is valid if either xFunc
78703 ** or xStep is non-zero.
78704 **
78705 ** If createFlag is false, then a function with the required name and
78706 ** number of arguments may be returned even if the eTextRep flag does not
78707 ** match that requested.
78708 */
78709 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
78710   sqlite3 *db,       /* An open database */
78711   const char *zName, /* Name of the function.  Not null-terminated */
78712   int nName,         /* Number of characters in the name */
78713   int nArg,          /* Number of arguments.  -1 means any number */
78714   u8 enc,            /* Preferred text encoding */
78715   int createFlag     /* Create new entry if true and does not otherwise exist */
78716 ){
78717   FuncDef *p;         /* Iterator variable */
78718   FuncDef *pBest = 0; /* Best match found so far */
78719   int bestScore = 0;  /* Score of best match */
78720   int h;              /* Hash value */
78721
78722
78723   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
78724   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
78725
78726   /* First search for a match amongst the application-defined functions.
78727   */
78728   p = functionSearch(&db->aFunc, h, zName, nName);
78729   while( p ){
78730     int score = matchQuality(p, nArg, enc);
78731     if( score>bestScore ){
78732       pBest = p;
78733       bestScore = score;
78734     }
78735     p = p->pNext;
78736   }
78737
78738   /* If no match is found, search the built-in functions.
78739   **
78740   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
78741   ** functions even if a prior app-defined function was found.  And give
78742   ** priority to built-in functions.
78743   **
78744   ** Except, if createFlag is true, that means that we are trying to
78745   ** install a new function.  Whatever FuncDef structure is returned it will
78746   ** have fields overwritten with new information appropriate for the
78747   ** new function.  But the FuncDefs for built-in functions are read-only.
78748   ** So we must not search for built-ins when creating a new function.
78749   */ 
78750   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
78751     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
78752     bestScore = 0;
78753     p = functionSearch(pHash, h, zName, nName);
78754     while( p ){
78755       int score = matchQuality(p, nArg, enc);
78756       if( score>bestScore ){
78757         pBest = p;
78758         bestScore = score;
78759       }
78760       p = p->pNext;
78761     }
78762   }
78763
78764   /* If the createFlag parameter is true and the search did not reveal an
78765   ** exact match for the name, number of arguments and encoding, then add a
78766   ** new entry to the hash table and return it.
78767   */
78768   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
78769       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
78770     pBest->zName = (char *)&pBest[1];
78771     pBest->nArg = (u16)nArg;
78772     pBest->iPrefEnc = enc;
78773     memcpy(pBest->zName, zName, nName);
78774     pBest->zName[nName] = 0;
78775     sqlite3FuncDefInsert(&db->aFunc, pBest);
78776   }
78777
78778   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
78779     return pBest;
78780   }
78781   return 0;
78782 }
78783
78784 /*
78785 ** Free all resources held by the schema structure. The void* argument points
78786 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
78787 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
78788 ** of the schema hash tables).
78789 **
78790 ** The Schema.cache_size variable is not cleared.
78791 */
78792 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
78793   Hash temp1;
78794   Hash temp2;
78795   HashElem *pElem;
78796   Schema *pSchema = (Schema *)p;
78797
78798   temp1 = pSchema->tblHash;
78799   temp2 = pSchema->trigHash;
78800   sqlite3HashInit(&pSchema->trigHash);
78801   sqlite3HashClear(&pSchema->idxHash);
78802   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
78803     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
78804   }
78805   sqlite3HashClear(&temp2);
78806   sqlite3HashInit(&pSchema->tblHash);
78807   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
78808     Table *pTab = sqliteHashData(pElem);
78809     sqlite3DeleteTable(0, pTab);
78810   }
78811   sqlite3HashClear(&temp1);
78812   sqlite3HashClear(&pSchema->fkeyHash);
78813   pSchema->pSeqTab = 0;
78814   pSchema->flags &= ~DB_SchemaLoaded;
78815 }
78816
78817 /*
78818 ** Find and return the schema associated with a BTree.  Create
78819 ** a new one if necessary.
78820 */
78821 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
78822   Schema * p;
78823   if( pBt ){
78824     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
78825   }else{
78826     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
78827   }
78828   if( !p ){
78829     db->mallocFailed = 1;
78830   }else if ( 0==p->file_format ){
78831     sqlite3HashInit(&p->tblHash);
78832     sqlite3HashInit(&p->idxHash);
78833     sqlite3HashInit(&p->trigHash);
78834     sqlite3HashInit(&p->fkeyHash);
78835     p->enc = SQLITE_UTF8;
78836   }
78837   return p;
78838 }
78839
78840 /************** End of callback.c ********************************************/
78841 /************** Begin file delete.c ******************************************/
78842 /*
78843 ** 2001 September 15
78844 **
78845 ** The author disclaims copyright to this source code.  In place of
78846 ** a legal notice, here is a blessing:
78847 **
78848 **    May you do good and not evil.
78849 **    May you find forgiveness for yourself and forgive others.
78850 **    May you share freely, never taking more than you give.
78851 **
78852 *************************************************************************
78853 ** This file contains C code routines that are called by the parser
78854 ** in order to generate code for DELETE FROM statements.
78855 */
78856
78857 /*
78858 ** Look up every table that is named in pSrc.  If any table is not found,
78859 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
78860 ** are found, return a pointer to the last table.
78861 */
78862 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
78863   struct SrcList_item *pItem = pSrc->a;
78864   Table *pTab;
78865   assert( pItem && pSrc->nSrc==1 );
78866   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
78867   sqlite3DeleteTable(pParse->db, pItem->pTab);
78868   pItem->pTab = pTab;
78869   if( pTab ){
78870     pTab->nRef++;
78871   }
78872   if( sqlite3IndexedByLookup(pParse, pItem) ){
78873     pTab = 0;
78874   }
78875   return pTab;
78876 }
78877
78878 /*
78879 ** Check to make sure the given table is writable.  If it is not
78880 ** writable, generate an error message and return 1.  If it is
78881 ** writable return 0;
78882 */
78883 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
78884   /* A table is not writable under the following circumstances:
78885   **
78886   **   1) It is a virtual table and no implementation of the xUpdate method
78887   **      has been provided, or
78888   **   2) It is a system table (i.e. sqlite_master), this call is not
78889   **      part of a nested parse and writable_schema pragma has not 
78890   **      been specified.
78891   **
78892   ** In either case leave an error message in pParse and return non-zero.
78893   */
78894   if( ( IsVirtual(pTab) 
78895      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
78896    || ( (pTab->tabFlags & TF_Readonly)!=0
78897      && (pParse->db->flags & SQLITE_WriteSchema)==0
78898      && pParse->nested==0 )
78899   ){
78900     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
78901     return 1;
78902   }
78903
78904 #ifndef SQLITE_OMIT_VIEW
78905   if( !viewOk && pTab->pSelect ){
78906     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
78907     return 1;
78908   }
78909 #endif
78910   return 0;
78911 }
78912
78913
78914 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
78915 /*
78916 ** Evaluate a view and store its result in an ephemeral table.  The
78917 ** pWhere argument is an optional WHERE clause that restricts the
78918 ** set of rows in the view that are to be added to the ephemeral table.
78919 */
78920 SQLITE_PRIVATE void sqlite3MaterializeView(
78921   Parse *pParse,       /* Parsing context */
78922   Table *pView,        /* View definition */
78923   Expr *pWhere,        /* Optional WHERE clause to be added */
78924   int iCur             /* Cursor number for ephemerial table */
78925 ){
78926   SelectDest dest;
78927   Select *pDup;
78928   sqlite3 *db = pParse->db;
78929
78930   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
78931   if( pWhere ){
78932     SrcList *pFrom;
78933     
78934     pWhere = sqlite3ExprDup(db, pWhere, 0);
78935     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
78936     if( pFrom ){
78937       assert( pFrom->nSrc==1 );
78938       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
78939       pFrom->a[0].pSelect = pDup;
78940       assert( pFrom->a[0].pOn==0 );
78941       assert( pFrom->a[0].pUsing==0 );
78942     }else{
78943       sqlite3SelectDelete(db, pDup);
78944     }
78945     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
78946   }
78947   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
78948   sqlite3Select(pParse, pDup, &dest);
78949   sqlite3SelectDelete(db, pDup);
78950 }
78951 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
78952
78953 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
78954 /*
78955 ** Generate an expression tree to implement the WHERE, ORDER BY,
78956 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
78957 **
78958 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
78959 **                            \__________________________/
78960 **                               pLimitWhere (pInClause)
78961 */
78962 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
78963   Parse *pParse,               /* The parser context */
78964   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
78965   Expr *pWhere,                /* The WHERE clause.  May be null */
78966   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
78967   Expr *pLimit,                /* The LIMIT clause.  May be null */
78968   Expr *pOffset,               /* The OFFSET clause.  May be null */
78969   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
78970 ){
78971   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
78972   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
78973   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
78974   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
78975   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
78976   Select *pSelect = NULL;      /* Complete SELECT tree */
78977
78978   /* Check that there isn't an ORDER BY without a LIMIT clause.
78979   */
78980   if( pOrderBy && (pLimit == 0) ) {
78981     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
78982     pParse->parseError = 1;
78983     goto limit_where_cleanup_2;
78984   }
78985
78986   /* We only need to generate a select expression if there
78987   ** is a limit/offset term to enforce.
78988   */
78989   if( pLimit == 0 ) {
78990     /* if pLimit is null, pOffset will always be null as well. */
78991     assert( pOffset == 0 );
78992     return pWhere;
78993   }
78994
78995   /* Generate a select expression tree to enforce the limit/offset 
78996   ** term for the DELETE or UPDATE statement.  For example:
78997   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
78998   ** becomes:
78999   **   DELETE FROM table_a WHERE rowid IN ( 
79000   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
79001   **   );
79002   */
79003
79004   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
79005   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
79006   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
79007   if( pEList == 0 ) goto limit_where_cleanup_2;
79008
79009   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
79010   ** and the SELECT subtree. */
79011   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
79012   if( pSelectSrc == 0 ) {
79013     sqlite3ExprListDelete(pParse->db, pEList);
79014     goto limit_where_cleanup_2;
79015   }
79016
79017   /* generate the SELECT expression tree. */
79018   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
79019                              pOrderBy,0,pLimit,pOffset);
79020   if( pSelect == 0 ) return 0;
79021
79022   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
79023   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
79024   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
79025   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
79026   if( pInClause == 0 ) goto limit_where_cleanup_1;
79027
79028   pInClause->x.pSelect = pSelect;
79029   pInClause->flags |= EP_xIsSelect;
79030   sqlite3ExprSetHeight(pParse, pInClause);
79031   return pInClause;
79032
79033   /* something went wrong. clean up anything allocated. */
79034 limit_where_cleanup_1:
79035   sqlite3SelectDelete(pParse->db, pSelect);
79036   return 0;
79037
79038 limit_where_cleanup_2:
79039   sqlite3ExprDelete(pParse->db, pWhere);
79040   sqlite3ExprListDelete(pParse->db, pOrderBy);
79041   sqlite3ExprDelete(pParse->db, pLimit);
79042   sqlite3ExprDelete(pParse->db, pOffset);
79043   return 0;
79044 }
79045 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
79046
79047 /*
79048 ** Generate code for a DELETE FROM statement.
79049 **
79050 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
79051 **                 \________/       \________________/
79052 **                  pTabList              pWhere
79053 */
79054 SQLITE_PRIVATE void sqlite3DeleteFrom(
79055   Parse *pParse,         /* The parser context */
79056   SrcList *pTabList,     /* The table from which we should delete things */
79057   Expr *pWhere           /* The WHERE clause.  May be null */
79058 ){
79059   Vdbe *v;               /* The virtual database engine */
79060   Table *pTab;           /* The table from which records will be deleted */
79061   const char *zDb;       /* Name of database holding pTab */
79062   int end, addr = 0;     /* A couple addresses of generated code */
79063   int i;                 /* Loop counter */
79064   WhereInfo *pWInfo;     /* Information about the WHERE clause */
79065   Index *pIdx;           /* For looping over indices of the table */
79066   int iCur;              /* VDBE Cursor number for pTab */
79067   sqlite3 *db;           /* Main database structure */
79068   AuthContext sContext;  /* Authorization context */
79069   NameContext sNC;       /* Name context to resolve expressions in */
79070   int iDb;               /* Database number */
79071   int memCnt = -1;       /* Memory cell used for change counting */
79072   int rcauth;            /* Value returned by authorization callback */
79073
79074 #ifndef SQLITE_OMIT_TRIGGER
79075   int isView;                  /* True if attempting to delete from a view */
79076   Trigger *pTrigger;           /* List of table triggers, if required */
79077 #endif
79078
79079   memset(&sContext, 0, sizeof(sContext));
79080   db = pParse->db;
79081   if( pParse->nErr || db->mallocFailed ){
79082     goto delete_from_cleanup;
79083   }
79084   assert( pTabList->nSrc==1 );
79085
79086   /* Locate the table which we want to delete.  This table has to be
79087   ** put in an SrcList structure because some of the subroutines we
79088   ** will be calling are designed to work with multiple tables and expect
79089   ** an SrcList* parameter instead of just a Table* parameter.
79090   */
79091   pTab = sqlite3SrcListLookup(pParse, pTabList);
79092   if( pTab==0 )  goto delete_from_cleanup;
79093
79094   /* Figure out if we have any triggers and if the table being
79095   ** deleted from is a view
79096   */
79097 #ifndef SQLITE_OMIT_TRIGGER
79098   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
79099   isView = pTab->pSelect!=0;
79100 #else
79101 # define pTrigger 0
79102 # define isView 0
79103 #endif
79104 #ifdef SQLITE_OMIT_VIEW
79105 # undef isView
79106 # define isView 0
79107 #endif
79108
79109   /* If pTab is really a view, make sure it has been initialized.
79110   */
79111   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
79112     goto delete_from_cleanup;
79113   }
79114
79115   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
79116     goto delete_from_cleanup;
79117   }
79118   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79119   assert( iDb<db->nDb );
79120   zDb = db->aDb[iDb].zName;
79121   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
79122   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
79123   if( rcauth==SQLITE_DENY ){
79124     goto delete_from_cleanup;
79125   }
79126   assert(!isView || pTrigger);
79127
79128   /* Assign  cursor number to the table and all its indices.
79129   */
79130   assert( pTabList->nSrc==1 );
79131   iCur = pTabList->a[0].iCursor = pParse->nTab++;
79132   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79133     pParse->nTab++;
79134   }
79135
79136   /* Start the view context
79137   */
79138   if( isView ){
79139     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
79140   }
79141
79142   /* Begin generating code.
79143   */
79144   v = sqlite3GetVdbe(pParse);
79145   if( v==0 ){
79146     goto delete_from_cleanup;
79147   }
79148   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
79149   sqlite3BeginWriteOperation(pParse, 1, iDb);
79150
79151   /* If we are trying to delete from a view, realize that view into
79152   ** a ephemeral table.
79153   */
79154 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
79155   if( isView ){
79156     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
79157   }
79158 #endif
79159
79160   /* Resolve the column names in the WHERE clause.
79161   */
79162   memset(&sNC, 0, sizeof(sNC));
79163   sNC.pParse = pParse;
79164   sNC.pSrcList = pTabList;
79165   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
79166     goto delete_from_cleanup;
79167   }
79168
79169   /* Initialize the counter of the number of rows deleted, if
79170   ** we are counting rows.
79171   */
79172   if( db->flags & SQLITE_CountRows ){
79173     memCnt = ++pParse->nMem;
79174     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
79175   }
79176
79177 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
79178   /* Special case: A DELETE without a WHERE clause deletes everything.
79179   ** It is easier just to erase the whole table. Prior to version 3.6.5,
79180   ** this optimization caused the row change count (the value returned by 
79181   ** API function sqlite3_count_changes) to be set incorrectly.  */
79182   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
79183    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
79184   ){
79185     assert( !isView );
79186     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
79187                       pTab->zName, P4_STATIC);
79188     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79189       assert( pIdx->pSchema==pTab->pSchema );
79190       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
79191     }
79192   }else
79193 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
79194   /* The usual case: There is a WHERE clause so we have to scan through
79195   ** the table and pick which records to delete.
79196   */
79197   {
79198     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
79199     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
79200     int regRowid;                   /* Actual register containing rowids */
79201
79202     /* Collect rowids of every row to be deleted.
79203     */
79204     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
79205     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
79206     if( pWInfo==0 ) goto delete_from_cleanup;
79207     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
79208     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
79209     if( db->flags & SQLITE_CountRows ){
79210       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
79211     }
79212     sqlite3WhereEnd(pWInfo);
79213
79214     /* Delete every item whose key was written to the list during the
79215     ** database scan.  We have to delete items after the scan is complete
79216     ** because deleting an item can change the scan order.  */
79217     end = sqlite3VdbeMakeLabel(v);
79218
79219     /* Unless this is a view, open cursors for the table we are 
79220     ** deleting from and all its indices. If this is a view, then the
79221     ** only effect this statement has is to fire the INSTEAD OF 
79222     ** triggers.  */
79223     if( !isView ){
79224       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
79225     }
79226
79227     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
79228
79229     /* Delete the row */
79230 #ifndef SQLITE_OMIT_VIRTUALTABLE
79231     if( IsVirtual(pTab) ){
79232       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
79233       sqlite3VtabMakeWritable(pParse, pTab);
79234       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
79235       sqlite3MayAbort(pParse);
79236     }else
79237 #endif
79238     {
79239       int count = (pParse->nested==0);    /* True to count changes */
79240       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
79241     }
79242
79243     /* End of the delete loop */
79244     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
79245     sqlite3VdbeResolveLabel(v, end);
79246
79247     /* Close the cursors open on the table and its indexes. */
79248     if( !isView && !IsVirtual(pTab) ){
79249       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
79250         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
79251       }
79252       sqlite3VdbeAddOp1(v, OP_Close, iCur);
79253     }
79254   }
79255
79256   /* Update the sqlite_sequence table by storing the content of the
79257   ** maximum rowid counter values recorded while inserting into
79258   ** autoincrement tables.
79259   */
79260   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
79261     sqlite3AutoincrementEnd(pParse);
79262   }
79263
79264   /* Return the number of rows that were deleted. If this routine is 
79265   ** generating code because of a call to sqlite3NestedParse(), do not
79266   ** invoke the callback function.
79267   */
79268   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
79269     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
79270     sqlite3VdbeSetNumCols(v, 1);
79271     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
79272   }
79273
79274 delete_from_cleanup:
79275   sqlite3AuthContextPop(&sContext);
79276   sqlite3SrcListDelete(db, pTabList);
79277   sqlite3ExprDelete(db, pWhere);
79278   return;
79279 }
79280 /* Make sure "isView" and other macros defined above are undefined. Otherwise
79281 ** thely may interfere with compilation of other functions in this file
79282 ** (or in another file, if this file becomes part of the amalgamation).  */
79283 #ifdef isView
79284  #undef isView
79285 #endif
79286 #ifdef pTrigger
79287  #undef pTrigger
79288 #endif
79289
79290 /*
79291 ** This routine generates VDBE code that causes a single row of a
79292 ** single table to be deleted.
79293 **
79294 ** The VDBE must be in a particular state when this routine is called.
79295 ** These are the requirements:
79296 **
79297 **   1.  A read/write cursor pointing to pTab, the table containing the row
79298 **       to be deleted, must be opened as cursor number $iCur.
79299 **
79300 **   2.  Read/write cursors for all indices of pTab must be open as
79301 **       cursor number base+i for the i-th index.
79302 **
79303 **   3.  The record number of the row to be deleted must be stored in
79304 **       memory cell iRowid.
79305 **
79306 ** This routine generates code to remove both the table record and all 
79307 ** index entries that point to that record.
79308 */
79309 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
79310   Parse *pParse,     /* Parsing context */
79311   Table *pTab,       /* Table containing the row to be deleted */
79312   int iCur,          /* Cursor number for the table */
79313   int iRowid,        /* Memory cell that contains the rowid to delete */
79314   int count,         /* If non-zero, increment the row change counter */
79315   Trigger *pTrigger, /* List of triggers to (potentially) fire */
79316   int onconf         /* Default ON CONFLICT policy for triggers */
79317 ){
79318   Vdbe *v = pParse->pVdbe;        /* Vdbe */
79319   int iOld = 0;                   /* First register in OLD.* array */
79320   int iLabel;                     /* Label resolved to end of generated code */
79321
79322   /* Vdbe is guaranteed to have been allocated by this stage. */
79323   assert( v );
79324
79325   /* Seek cursor iCur to the row to delete. If this row no longer exists 
79326   ** (this can happen if a trigger program has already deleted it), do
79327   ** not attempt to delete it or fire any DELETE triggers.  */
79328   iLabel = sqlite3VdbeMakeLabel(v);
79329   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
79330  
79331   /* If there are any triggers to fire, allocate a range of registers to
79332   ** use for the old.* references in the triggers.  */
79333   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
79334     u32 mask;                     /* Mask of OLD.* columns in use */
79335     int iCol;                     /* Iterator used while populating OLD.* */
79336
79337     /* TODO: Could use temporary registers here. Also could attempt to
79338     ** avoid copying the contents of the rowid register.  */
79339     mask = sqlite3TriggerColmask(
79340         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
79341     );
79342     mask |= sqlite3FkOldmask(pParse, pTab);
79343     iOld = pParse->nMem+1;
79344     pParse->nMem += (1 + pTab->nCol);
79345
79346     /* Populate the OLD.* pseudo-table register array. These values will be 
79347     ** used by any BEFORE and AFTER triggers that exist.  */
79348     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
79349     for(iCol=0; iCol<pTab->nCol; iCol++){
79350       if( mask==0xffffffff || mask&(1<<iCol) ){
79351         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
79352       }
79353     }
79354
79355     /* Invoke BEFORE DELETE trigger programs. */
79356     sqlite3CodeRowTrigger(pParse, pTrigger, 
79357         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
79358     );
79359
79360     /* Seek the cursor to the row to be deleted again. It may be that
79361     ** the BEFORE triggers coded above have already removed the row
79362     ** being deleted. Do not attempt to delete the row a second time, and 
79363     ** do not fire AFTER triggers.  */
79364     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
79365
79366     /* Do FK processing. This call checks that any FK constraints that
79367     ** refer to this table (i.e. constraints attached to other tables) 
79368     ** are not violated by deleting this row.  */
79369     sqlite3FkCheck(pParse, pTab, iOld, 0);
79370   }
79371
79372   /* Delete the index and table entries. Skip this step if pTab is really
79373   ** a view (in which case the only effect of the DELETE statement is to
79374   ** fire the INSTEAD OF triggers).  */ 
79375   if( pTab->pSelect==0 ){
79376     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
79377     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
79378     if( count ){
79379       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
79380     }
79381   }
79382
79383   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
79384   ** handle rows (possibly in other tables) that refer via a foreign key
79385   ** to the row just deleted. */ 
79386   sqlite3FkActions(pParse, pTab, 0, iOld);
79387
79388   /* Invoke AFTER DELETE trigger programs. */
79389   sqlite3CodeRowTrigger(pParse, pTrigger, 
79390       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
79391   );
79392
79393   /* Jump here if the row had already been deleted before any BEFORE
79394   ** trigger programs were invoked. Or if a trigger program throws a 
79395   ** RAISE(IGNORE) exception.  */
79396   sqlite3VdbeResolveLabel(v, iLabel);
79397 }
79398
79399 /*
79400 ** This routine generates VDBE code that causes the deletion of all
79401 ** index entries associated with a single row of a single table.
79402 **
79403 ** The VDBE must be in a particular state when this routine is called.
79404 ** These are the requirements:
79405 **
79406 **   1.  A read/write cursor pointing to pTab, the table containing the row
79407 **       to be deleted, must be opened as cursor number "iCur".
79408 **
79409 **   2.  Read/write cursors for all indices of pTab must be open as
79410 **       cursor number iCur+i for the i-th index.
79411 **
79412 **   3.  The "iCur" cursor must be pointing to the row that is to be
79413 **       deleted.
79414 */
79415 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
79416   Parse *pParse,     /* Parsing and code generating context */
79417   Table *pTab,       /* Table containing the row to be deleted */
79418   int iCur,          /* Cursor number for the table */
79419   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
79420 ){
79421   int i;
79422   Index *pIdx;
79423   int r1;
79424
79425   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
79426     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
79427     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
79428     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
79429   }
79430 }
79431
79432 /*
79433 ** Generate code that will assemble an index key and put it in register
79434 ** regOut.  The key with be for index pIdx which is an index on pTab.
79435 ** iCur is the index of a cursor open on the pTab table and pointing to
79436 ** the entry that needs indexing.
79437 **
79438 ** Return a register number which is the first in a block of
79439 ** registers that holds the elements of the index key.  The
79440 ** block of registers has already been deallocated by the time
79441 ** this routine returns.
79442 */
79443 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
79444   Parse *pParse,     /* Parsing context */
79445   Index *pIdx,       /* The index for which to generate a key */
79446   int iCur,          /* Cursor number for the pIdx->pTable table */
79447   int regOut,        /* Write the new index key to this register */
79448   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
79449 ){
79450   Vdbe *v = pParse->pVdbe;
79451   int j;
79452   Table *pTab = pIdx->pTable;
79453   int regBase;
79454   int nCol;
79455
79456   nCol = pIdx->nColumn;
79457   regBase = sqlite3GetTempRange(pParse, nCol+1);
79458   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
79459   for(j=0; j<nCol; j++){
79460     int idx = pIdx->aiColumn[j];
79461     if( idx==pTab->iPKey ){
79462       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
79463     }else{
79464       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
79465       sqlite3ColumnDefault(v, pTab, idx, -1);
79466     }
79467   }
79468   if( doMakeRec ){
79469     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
79470     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
79471   }
79472   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
79473   return regBase;
79474 }
79475
79476 /************** End of delete.c **********************************************/
79477 /************** Begin file func.c ********************************************/
79478 /*
79479 ** 2002 February 23
79480 **
79481 ** The author disclaims copyright to this source code.  In place of
79482 ** a legal notice, here is a blessing:
79483 **
79484 **    May you do good and not evil.
79485 **    May you find forgiveness for yourself and forgive others.
79486 **    May you share freely, never taking more than you give.
79487 **
79488 *************************************************************************
79489 ** This file contains the C functions that implement various SQL
79490 ** functions of SQLite.  
79491 **
79492 ** There is only one exported symbol in this file - the function
79493 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
79494 ** All other code has file scope.
79495 */
79496
79497 /*
79498 ** Return the collating function associated with a function.
79499 */
79500 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
79501   return context->pColl;
79502 }
79503
79504 /*
79505 ** Implementation of the non-aggregate min() and max() functions
79506 */
79507 static void minmaxFunc(
79508   sqlite3_context *context,
79509   int argc,
79510   sqlite3_value **argv
79511 ){
79512   int i;
79513   int mask;    /* 0 for min() or 0xffffffff for max() */
79514   int iBest;
79515   CollSeq *pColl;
79516
79517   assert( argc>1 );
79518   mask = sqlite3_user_data(context)==0 ? 0 : -1;
79519   pColl = sqlite3GetFuncCollSeq(context);
79520   assert( pColl );
79521   assert( mask==-1 || mask==0 );
79522   iBest = 0;
79523   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
79524   for(i=1; i<argc; i++){
79525     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
79526     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
79527       testcase( mask==0 );
79528       iBest = i;
79529     }
79530   }
79531   sqlite3_result_value(context, argv[iBest]);
79532 }
79533
79534 /*
79535 ** Return the type of the argument.
79536 */
79537 static void typeofFunc(
79538   sqlite3_context *context,
79539   int NotUsed,
79540   sqlite3_value **argv
79541 ){
79542   const char *z = 0;
79543   UNUSED_PARAMETER(NotUsed);
79544   switch( sqlite3_value_type(argv[0]) ){
79545     case SQLITE_INTEGER: z = "integer"; break;
79546     case SQLITE_TEXT:    z = "text";    break;
79547     case SQLITE_FLOAT:   z = "real";    break;
79548     case SQLITE_BLOB:    z = "blob";    break;
79549     default:             z = "null";    break;
79550   }
79551   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
79552 }
79553
79554
79555 /*
79556 ** Implementation of the length() function
79557 */
79558 static void lengthFunc(
79559   sqlite3_context *context,
79560   int argc,
79561   sqlite3_value **argv
79562 ){
79563   int len;
79564
79565   assert( argc==1 );
79566   UNUSED_PARAMETER(argc);
79567   switch( sqlite3_value_type(argv[0]) ){
79568     case SQLITE_BLOB:
79569     case SQLITE_INTEGER:
79570     case SQLITE_FLOAT: {
79571       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
79572       break;
79573     }
79574     case SQLITE_TEXT: {
79575       const unsigned char *z = sqlite3_value_text(argv[0]);
79576       if( z==0 ) return;
79577       len = 0;
79578       while( *z ){
79579         len++;
79580         SQLITE_SKIP_UTF8(z);
79581       }
79582       sqlite3_result_int(context, len);
79583       break;
79584     }
79585     default: {
79586       sqlite3_result_null(context);
79587       break;
79588     }
79589   }
79590 }
79591
79592 /*
79593 ** Implementation of the abs() function.
79594 **
79595 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
79596 ** the numeric argument X. 
79597 */
79598 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79599   assert( argc==1 );
79600   UNUSED_PARAMETER(argc);
79601   switch( sqlite3_value_type(argv[0]) ){
79602     case SQLITE_INTEGER: {
79603       i64 iVal = sqlite3_value_int64(argv[0]);
79604       if( iVal<0 ){
79605         if( (iVal<<1)==0 ){
79606           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
79607           ** abs(X) throws an integer overflow error since there is no
79608           ** equivalent positive 64-bit two complement value. */
79609           sqlite3_result_error(context, "integer overflow", -1);
79610           return;
79611         }
79612         iVal = -iVal;
79613       } 
79614       sqlite3_result_int64(context, iVal);
79615       break;
79616     }
79617     case SQLITE_NULL: {
79618       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
79619       sqlite3_result_null(context);
79620       break;
79621     }
79622     default: {
79623       /* Because sqlite3_value_double() returns 0.0 if the argument is not
79624       ** something that can be converted into a number, we have:
79625       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
79626       ** cannot be converted to a numeric value. 
79627       */
79628       double rVal = sqlite3_value_double(argv[0]);
79629       if( rVal<0 ) rVal = -rVal;
79630       sqlite3_result_double(context, rVal);
79631       break;
79632     }
79633   }
79634 }
79635
79636 /*
79637 ** Implementation of the substr() function.
79638 **
79639 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
79640 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
79641 ** of x.  If x is text, then we actually count UTF-8 characters.
79642 ** If x is a blob, then we count bytes.
79643 **
79644 ** If p1 is negative, then we begin abs(p1) from the end of x[].
79645 **
79646 ** If p2 is negative, return the p2 characters preceeding p1.
79647 */
79648 static void substrFunc(
79649   sqlite3_context *context,
79650   int argc,
79651   sqlite3_value **argv
79652 ){
79653   const unsigned char *z;
79654   const unsigned char *z2;
79655   int len;
79656   int p0type;
79657   i64 p1, p2;
79658   int negP2 = 0;
79659
79660   assert( argc==3 || argc==2 );
79661   if( sqlite3_value_type(argv[1])==SQLITE_NULL
79662    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
79663   ){
79664     return;
79665   }
79666   p0type = sqlite3_value_type(argv[0]);
79667   p1 = sqlite3_value_int(argv[1]);
79668   if( p0type==SQLITE_BLOB ){
79669     len = sqlite3_value_bytes(argv[0]);
79670     z = sqlite3_value_blob(argv[0]);
79671     if( z==0 ) return;
79672     assert( len==sqlite3_value_bytes(argv[0]) );
79673   }else{
79674     z = sqlite3_value_text(argv[0]);
79675     if( z==0 ) return;
79676     len = 0;
79677     if( p1<0 ){
79678       for(z2=z; *z2; len++){
79679         SQLITE_SKIP_UTF8(z2);
79680       }
79681     }
79682   }
79683   if( argc==3 ){
79684     p2 = sqlite3_value_int(argv[2]);
79685     if( p2<0 ){
79686       p2 = -p2;
79687       negP2 = 1;
79688     }
79689   }else{
79690     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
79691   }
79692   if( p1<0 ){
79693     p1 += len;
79694     if( p1<0 ){
79695       p2 += p1;
79696       if( p2<0 ) p2 = 0;
79697       p1 = 0;
79698     }
79699   }else if( p1>0 ){
79700     p1--;
79701   }else if( p2>0 ){
79702     p2--;
79703   }
79704   if( negP2 ){
79705     p1 -= p2;
79706     if( p1<0 ){
79707       p2 += p1;
79708       p1 = 0;
79709     }
79710   }
79711   assert( p1>=0 && p2>=0 );
79712   if( p0type!=SQLITE_BLOB ){
79713     while( *z && p1 ){
79714       SQLITE_SKIP_UTF8(z);
79715       p1--;
79716     }
79717     for(z2=z; *z2 && p2; p2--){
79718       SQLITE_SKIP_UTF8(z2);
79719     }
79720     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
79721   }else{
79722     if( p1+p2>len ){
79723       p2 = len-p1;
79724       if( p2<0 ) p2 = 0;
79725     }
79726     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
79727   }
79728 }
79729
79730 /*
79731 ** Implementation of the round() function
79732 */
79733 #ifndef SQLITE_OMIT_FLOATING_POINT
79734 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79735   int n = 0;
79736   double r;
79737   char *zBuf;
79738   assert( argc==1 || argc==2 );
79739   if( argc==2 ){
79740     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
79741     n = sqlite3_value_int(argv[1]);
79742     if( n>30 ) n = 30;
79743     if( n<0 ) n = 0;
79744   }
79745   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
79746   r = sqlite3_value_double(argv[0]);
79747   /* If Y==0 and X will fit in a 64-bit int,
79748   ** handle the rounding directly,
79749   ** otherwise use printf.
79750   */
79751   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
79752     r = (double)((sqlite_int64)(r+0.5));
79753   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
79754     r = -(double)((sqlite_int64)((-r)+0.5));
79755   }else{
79756     zBuf = sqlite3_mprintf("%.*f",n,r);
79757     if( zBuf==0 ){
79758       sqlite3_result_error_nomem(context);
79759       return;
79760     }
79761     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
79762     sqlite3_free(zBuf);
79763   }
79764   sqlite3_result_double(context, r);
79765 }
79766 #endif
79767
79768 /*
79769 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
79770 ** allocation fails, call sqlite3_result_error_nomem() to notify
79771 ** the database handle that malloc() has failed and return NULL.
79772 ** If nByte is larger than the maximum string or blob length, then
79773 ** raise an SQLITE_TOOBIG exception and return NULL.
79774 */
79775 static void *contextMalloc(sqlite3_context *context, i64 nByte){
79776   char *z;
79777   sqlite3 *db = sqlite3_context_db_handle(context);
79778   assert( nByte>0 );
79779   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
79780   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
79781   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79782     sqlite3_result_error_toobig(context);
79783     z = 0;
79784   }else{
79785     z = sqlite3Malloc((int)nByte);
79786     if( !z ){
79787       sqlite3_result_error_nomem(context);
79788     }
79789   }
79790   return z;
79791 }
79792
79793 /*
79794 ** Implementation of the upper() and lower() SQL functions.
79795 */
79796 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79797   char *z1;
79798   const char *z2;
79799   int i, n;
79800   UNUSED_PARAMETER(argc);
79801   z2 = (char*)sqlite3_value_text(argv[0]);
79802   n = sqlite3_value_bytes(argv[0]);
79803   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
79804   assert( z2==(char*)sqlite3_value_text(argv[0]) );
79805   if( z2 ){
79806     z1 = contextMalloc(context, ((i64)n)+1);
79807     if( z1 ){
79808       memcpy(z1, z2, n+1);
79809       for(i=0; z1[i]; i++){
79810         z1[i] = (char)sqlite3Toupper(z1[i]);
79811       }
79812       sqlite3_result_text(context, z1, -1, sqlite3_free);
79813     }
79814   }
79815 }
79816 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
79817   u8 *z1;
79818   const char *z2;
79819   int i, n;
79820   UNUSED_PARAMETER(argc);
79821   z2 = (char*)sqlite3_value_text(argv[0]);
79822   n = sqlite3_value_bytes(argv[0]);
79823   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
79824   assert( z2==(char*)sqlite3_value_text(argv[0]) );
79825   if( z2 ){
79826     z1 = contextMalloc(context, ((i64)n)+1);
79827     if( z1 ){
79828       memcpy(z1, z2, n+1);
79829       for(i=0; z1[i]; i++){
79830         z1[i] = sqlite3Tolower(z1[i]);
79831       }
79832       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
79833     }
79834   }
79835 }
79836
79837
79838 #if 0  /* This function is never used. */
79839 /*
79840 ** The COALESCE() and IFNULL() functions used to be implemented as shown
79841 ** here.  But now they are implemented as VDBE code so that unused arguments
79842 ** do not have to be computed.  This legacy implementation is retained as
79843 ** comment.
79844 */
79845 /*
79846 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
79847 ** All three do the same thing.  They return the first non-NULL
79848 ** argument.
79849 */
79850 static void ifnullFunc(
79851   sqlite3_context *context,
79852   int argc,
79853   sqlite3_value **argv
79854 ){
79855   int i;
79856   for(i=0; i<argc; i++){
79857     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
79858       sqlite3_result_value(context, argv[i]);
79859       break;
79860     }
79861   }
79862 }
79863 #endif /* NOT USED */
79864 #define ifnullFunc versionFunc   /* Substitute function - never called */
79865
79866 /*
79867 ** Implementation of random().  Return a random integer.  
79868 */
79869 static void randomFunc(
79870   sqlite3_context *context,
79871   int NotUsed,
79872   sqlite3_value **NotUsed2
79873 ){
79874   sqlite_int64 r;
79875   UNUSED_PARAMETER2(NotUsed, NotUsed2);
79876   sqlite3_randomness(sizeof(r), &r);
79877   if( r<0 ){
79878     /* We need to prevent a random number of 0x8000000000000000 
79879     ** (or -9223372036854775808) since when you do abs() of that
79880     ** number of you get the same value back again.  To do this
79881     ** in a way that is testable, mask the sign bit off of negative
79882     ** values, resulting in a positive value.  Then take the 
79883     ** 2s complement of that positive value.  The end result can
79884     ** therefore be no less than -9223372036854775807.
79885     */
79886     r = -(r ^ (((sqlite3_int64)1)<<63));
79887   }
79888   sqlite3_result_int64(context, r);
79889 }
79890
79891 /*
79892 ** Implementation of randomblob(N).  Return a random blob
79893 ** that is N bytes long.
79894 */
79895 static void randomBlob(
79896   sqlite3_context *context,
79897   int argc,
79898   sqlite3_value **argv
79899 ){
79900   int n;
79901   unsigned char *p;
79902   assert( argc==1 );
79903   UNUSED_PARAMETER(argc);
79904   n = sqlite3_value_int(argv[0]);
79905   if( n<1 ){
79906     n = 1;
79907   }
79908   p = contextMalloc(context, n);
79909   if( p ){
79910     sqlite3_randomness(n, p);
79911     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
79912   }
79913 }
79914
79915 /*
79916 ** Implementation of the last_insert_rowid() SQL function.  The return
79917 ** value is the same as the sqlite3_last_insert_rowid() API function.
79918 */
79919 static void last_insert_rowid(
79920   sqlite3_context *context, 
79921   int NotUsed, 
79922   sqlite3_value **NotUsed2
79923 ){
79924   sqlite3 *db = sqlite3_context_db_handle(context);
79925   UNUSED_PARAMETER2(NotUsed, NotUsed2);
79926   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
79927   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
79928   ** function. */
79929   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
79930 }
79931
79932 /*
79933 ** Implementation of the changes() SQL function.
79934 **
79935 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
79936 ** around the sqlite3_changes() C/C++ function and hence follows the same
79937 ** rules for counting changes.
79938 */
79939 static void changes(
79940   sqlite3_context *context,
79941   int NotUsed,
79942   sqlite3_value **NotUsed2
79943 ){
79944   sqlite3 *db = sqlite3_context_db_handle(context);
79945   UNUSED_PARAMETER2(NotUsed, NotUsed2);
79946   sqlite3_result_int(context, sqlite3_changes(db));
79947 }
79948
79949 /*
79950 ** Implementation of the total_changes() SQL function.  The return value is
79951 ** the same as the sqlite3_total_changes() API function.
79952 */
79953 static void total_changes(
79954   sqlite3_context *context,
79955   int NotUsed,
79956   sqlite3_value **NotUsed2
79957 ){
79958   sqlite3 *db = sqlite3_context_db_handle(context);
79959   UNUSED_PARAMETER2(NotUsed, NotUsed2);
79960   /* IMP: R-52756-41993 This function is a wrapper around the
79961   ** sqlite3_total_changes() C/C++ interface. */
79962   sqlite3_result_int(context, sqlite3_total_changes(db));
79963 }
79964
79965 /*
79966 ** A structure defining how to do GLOB-style comparisons.
79967 */
79968 struct compareInfo {
79969   u8 matchAll;
79970   u8 matchOne;
79971   u8 matchSet;
79972   u8 noCase;
79973 };
79974
79975 /*
79976 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
79977 ** character is exactly one byte in size.  Also, all characters are
79978 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
79979 ** whereas only characters less than 0x80 do in ASCII.
79980 */
79981 #if defined(SQLITE_EBCDIC)
79982 # define sqlite3Utf8Read(A,C)    (*(A++))
79983 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
79984 #else
79985 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
79986 #endif
79987
79988 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
79989 /* The correct SQL-92 behavior is for the LIKE operator to ignore
79990 ** case.  Thus  'a' LIKE 'A' would be true. */
79991 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
79992 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
79993 ** is case sensitive causing 'a' LIKE 'A' to be false */
79994 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
79995
79996 /*
79997 ** Compare two UTF-8 strings for equality where the first string can
79998 ** potentially be a "glob" expression.  Return true (1) if they
79999 ** are the same and false (0) if they are different.
80000 **
80001 ** Globbing rules:
80002 **
80003 **      '*'       Matches any sequence of zero or more characters.
80004 **
80005 **      '?'       Matches exactly one character.
80006 **
80007 **     [...]      Matches one character from the enclosed list of
80008 **                characters.
80009 **
80010 **     [^...]     Matches one character not in the enclosed list.
80011 **
80012 ** With the [...] and [^...] matching, a ']' character can be included
80013 ** in the list by making it the first character after '[' or '^'.  A
80014 ** range of characters can be specified using '-'.  Example:
80015 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
80016 ** it the last character in the list.
80017 **
80018 ** This routine is usually quick, but can be N**2 in the worst case.
80019 **
80020 ** Hints: to match '*' or '?', put them in "[]".  Like this:
80021 **
80022 **         abc[*]xyz        Matches "abc*xyz" only
80023 */
80024 static int patternCompare(
80025   const u8 *zPattern,              /* The glob pattern */
80026   const u8 *zString,               /* The string to compare against the glob */
80027   const struct compareInfo *pInfo, /* Information about how to do the compare */
80028   const int esc                    /* The escape character */
80029 ){
80030   int c, c2;
80031   int invert;
80032   int seen;
80033   u8 matchOne = pInfo->matchOne;
80034   u8 matchAll = pInfo->matchAll;
80035   u8 matchSet = pInfo->matchSet;
80036   u8 noCase = pInfo->noCase; 
80037   int prevEscape = 0;     /* True if the previous character was 'escape' */
80038
80039   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
80040     if( !prevEscape && c==matchAll ){
80041       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
80042                || c == matchOne ){
80043         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
80044           return 0;
80045         }
80046       }
80047       if( c==0 ){
80048         return 1;
80049       }else if( c==esc ){
80050         c = sqlite3Utf8Read(zPattern, &zPattern);
80051         if( c==0 ){
80052           return 0;
80053         }
80054       }else if( c==matchSet ){
80055         assert( esc==0 );         /* This is GLOB, not LIKE */
80056         assert( matchSet<0x80 );  /* '[' is a single-byte character */
80057         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
80058           SQLITE_SKIP_UTF8(zString);
80059         }
80060         return *zString!=0;
80061       }
80062       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
80063         if( noCase ){
80064           GlogUpperToLower(c2);
80065           GlogUpperToLower(c);
80066           while( c2 != 0 && c2 != c ){
80067             c2 = sqlite3Utf8Read(zString, &zString);
80068             GlogUpperToLower(c2);
80069           }
80070         }else{
80071           while( c2 != 0 && c2 != c ){
80072             c2 = sqlite3Utf8Read(zString, &zString);
80073           }
80074         }
80075         if( c2==0 ) return 0;
80076         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
80077       }
80078       return 0;
80079     }else if( !prevEscape && c==matchOne ){
80080       if( sqlite3Utf8Read(zString, &zString)==0 ){
80081         return 0;
80082       }
80083     }else if( c==matchSet ){
80084       int prior_c = 0;
80085       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
80086       seen = 0;
80087       invert = 0;
80088       c = sqlite3Utf8Read(zString, &zString);
80089       if( c==0 ) return 0;
80090       c2 = sqlite3Utf8Read(zPattern, &zPattern);
80091       if( c2=='^' ){
80092         invert = 1;
80093         c2 = sqlite3Utf8Read(zPattern, &zPattern);
80094       }
80095       if( c2==']' ){
80096         if( c==']' ) seen = 1;
80097         c2 = sqlite3Utf8Read(zPattern, &zPattern);
80098       }
80099       while( c2 && c2!=']' ){
80100         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
80101           c2 = sqlite3Utf8Read(zPattern, &zPattern);
80102           if( c>=prior_c && c<=c2 ) seen = 1;
80103           prior_c = 0;
80104         }else{
80105           if( c==c2 ){
80106             seen = 1;
80107           }
80108           prior_c = c2;
80109         }
80110         c2 = sqlite3Utf8Read(zPattern, &zPattern);
80111       }
80112       if( c2==0 || (seen ^ invert)==0 ){
80113         return 0;
80114       }
80115     }else if( esc==c && !prevEscape ){
80116       prevEscape = 1;
80117     }else{
80118       c2 = sqlite3Utf8Read(zString, &zString);
80119       if( noCase ){
80120         GlogUpperToLower(c);
80121         GlogUpperToLower(c2);
80122       }
80123       if( c!=c2 ){
80124         return 0;
80125       }
80126       prevEscape = 0;
80127     }
80128   }
80129   return *zString==0;
80130 }
80131
80132 /*
80133 ** Count the number of times that the LIKE operator (or GLOB which is
80134 ** just a variation of LIKE) gets called.  This is used for testing
80135 ** only.
80136 */
80137 #ifdef SQLITE_TEST
80138 SQLITE_API int sqlite3_like_count = 0;
80139 #endif
80140
80141
80142 /*
80143 ** Implementation of the like() SQL function.  This function implements
80144 ** the build-in LIKE operator.  The first argument to the function is the
80145 ** pattern and the second argument is the string.  So, the SQL statements:
80146 **
80147 **       A LIKE B
80148 **
80149 ** is implemented as like(B,A).
80150 **
80151 ** This same function (with a different compareInfo structure) computes
80152 ** the GLOB operator.
80153 */
80154 static void likeFunc(
80155   sqlite3_context *context, 
80156   int argc, 
80157   sqlite3_value **argv
80158 ){
80159   const unsigned char *zA, *zB;
80160   int escape = 0;
80161   int nPat;
80162   sqlite3 *db = sqlite3_context_db_handle(context);
80163
80164   zB = sqlite3_value_text(argv[0]);
80165   zA = sqlite3_value_text(argv[1]);
80166
80167   /* Limit the length of the LIKE or GLOB pattern to avoid problems
80168   ** of deep recursion and N*N behavior in patternCompare().
80169   */
80170   nPat = sqlite3_value_bytes(argv[0]);
80171   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
80172   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
80173   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
80174     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
80175     return;
80176   }
80177   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
80178
80179   if( argc==3 ){
80180     /* The escape character string must consist of a single UTF-8 character.
80181     ** Otherwise, return an error.
80182     */
80183     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
80184     if( zEsc==0 ) return;
80185     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
80186       sqlite3_result_error(context, 
80187           "ESCAPE expression must be a single character", -1);
80188       return;
80189     }
80190     escape = sqlite3Utf8Read(zEsc, &zEsc);
80191   }
80192   if( zA && zB ){
80193     struct compareInfo *pInfo = sqlite3_user_data(context);
80194 #ifdef SQLITE_TEST
80195     sqlite3_like_count++;
80196 #endif
80197     
80198     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
80199   }
80200 }
80201
80202 /*
80203 ** Implementation of the NULLIF(x,y) function.  The result is the first
80204 ** argument if the arguments are different.  The result is NULL if the
80205 ** arguments are equal to each other.
80206 */
80207 static void nullifFunc(
80208   sqlite3_context *context,
80209   int NotUsed,
80210   sqlite3_value **argv
80211 ){
80212   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
80213   UNUSED_PARAMETER(NotUsed);
80214   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
80215     sqlite3_result_value(context, argv[0]);
80216   }
80217 }
80218
80219 /*
80220 ** Implementation of the sqlite_version() function.  The result is the version
80221 ** of the SQLite library that is running.
80222 */
80223 static void versionFunc(
80224   sqlite3_context *context,
80225   int NotUsed,
80226   sqlite3_value **NotUsed2
80227 ){
80228   UNUSED_PARAMETER2(NotUsed, NotUsed2);
80229   /* IMP: R-48699-48617 This function is an SQL wrapper around the
80230   ** sqlite3_libversion() C-interface. */
80231   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
80232 }
80233
80234 /*
80235 ** Implementation of the sqlite_source_id() function. The result is a string
80236 ** that identifies the particular version of the source code used to build
80237 ** SQLite.
80238 */
80239 static void sourceidFunc(
80240   sqlite3_context *context,
80241   int NotUsed,
80242   sqlite3_value **NotUsed2
80243 ){
80244   UNUSED_PARAMETER2(NotUsed, NotUsed2);
80245   /* IMP: R-24470-31136 This function is an SQL wrapper around the
80246   ** sqlite3_sourceid() C interface. */
80247   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
80248 }
80249
80250 /*
80251 ** Implementation of the sqlite_compileoption_used() function.
80252 ** The result is an integer that identifies if the compiler option
80253 ** was used to build SQLite.
80254 */
80255 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
80256 static void compileoptionusedFunc(
80257   sqlite3_context *context,
80258   int argc,
80259   sqlite3_value **argv
80260 ){
80261   const char *zOptName;
80262   assert( argc==1 );
80263   UNUSED_PARAMETER(argc);
80264   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
80265   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
80266   ** function.
80267   */
80268   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
80269     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
80270   }
80271 }
80272 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
80273
80274 /*
80275 ** Implementation of the sqlite_compileoption_get() function. 
80276 ** The result is a string that identifies the compiler options 
80277 ** used to build SQLite.
80278 */
80279 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
80280 static void compileoptiongetFunc(
80281   sqlite3_context *context,
80282   int argc,
80283   sqlite3_value **argv
80284 ){
80285   int n;
80286   assert( argc==1 );
80287   UNUSED_PARAMETER(argc);
80288   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
80289   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
80290   */
80291   n = sqlite3_value_int(argv[0]);
80292   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
80293 }
80294 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
80295
80296 /* Array for converting from half-bytes (nybbles) into ASCII hex
80297 ** digits. */
80298 static const char hexdigits[] = {
80299   '0', '1', '2', '3', '4', '5', '6', '7',
80300   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
80301 };
80302
80303 /*
80304 ** EXPERIMENTAL - This is not an official function.  The interface may
80305 ** change.  This function may disappear.  Do not write code that depends
80306 ** on this function.
80307 **
80308 ** Implementation of the QUOTE() function.  This function takes a single
80309 ** argument.  If the argument is numeric, the return value is the same as
80310 ** the argument.  If the argument is NULL, the return value is the string
80311 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
80312 ** single-quote escapes.
80313 */
80314 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
80315   assert( argc==1 );
80316   UNUSED_PARAMETER(argc);
80317   switch( sqlite3_value_type(argv[0]) ){
80318     case SQLITE_INTEGER:
80319     case SQLITE_FLOAT: {
80320       sqlite3_result_value(context, argv[0]);
80321       break;
80322     }
80323     case SQLITE_BLOB: {
80324       char *zText = 0;
80325       char const *zBlob = sqlite3_value_blob(argv[0]);
80326       int nBlob = sqlite3_value_bytes(argv[0]);
80327       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
80328       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
80329       if( zText ){
80330         int i;
80331         for(i=0; i<nBlob; i++){
80332           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
80333           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
80334         }
80335         zText[(nBlob*2)+2] = '\'';
80336         zText[(nBlob*2)+3] = '\0';
80337         zText[0] = 'X';
80338         zText[1] = '\'';
80339         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
80340         sqlite3_free(zText);
80341       }
80342       break;
80343     }
80344     case SQLITE_TEXT: {
80345       int i,j;
80346       u64 n;
80347       const unsigned char *zArg = sqlite3_value_text(argv[0]);
80348       char *z;
80349
80350       if( zArg==0 ) return;
80351       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
80352       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
80353       if( z ){
80354         z[0] = '\'';
80355         for(i=0, j=1; zArg[i]; i++){
80356           z[j++] = zArg[i];
80357           if( zArg[i]=='\'' ){
80358             z[j++] = '\'';
80359           }
80360         }
80361         z[j++] = '\'';
80362         z[j] = 0;
80363         sqlite3_result_text(context, z, j, sqlite3_free);
80364       }
80365       break;
80366     }
80367     default: {
80368       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
80369       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
80370       break;
80371     }
80372   }
80373 }
80374
80375 /*
80376 ** The hex() function.  Interpret the argument as a blob.  Return
80377 ** a hexadecimal rendering as text.
80378 */
80379 static void hexFunc(
80380   sqlite3_context *context,
80381   int argc,
80382   sqlite3_value **argv
80383 ){
80384   int i, n;
80385   const unsigned char *pBlob;
80386   char *zHex, *z;
80387   assert( argc==1 );
80388   UNUSED_PARAMETER(argc);
80389   pBlob = sqlite3_value_blob(argv[0]);
80390   n = sqlite3_value_bytes(argv[0]);
80391   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
80392   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
80393   if( zHex ){
80394     for(i=0; i<n; i++, pBlob++){
80395       unsigned char c = *pBlob;
80396       *(z++) = hexdigits[(c>>4)&0xf];
80397       *(z++) = hexdigits[c&0xf];
80398     }
80399     *z = 0;
80400     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
80401   }
80402 }
80403
80404 /*
80405 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
80406 */
80407 static void zeroblobFunc(
80408   sqlite3_context *context,
80409   int argc,
80410   sqlite3_value **argv
80411 ){
80412   i64 n;
80413   sqlite3 *db = sqlite3_context_db_handle(context);
80414   assert( argc==1 );
80415   UNUSED_PARAMETER(argc);
80416   n = sqlite3_value_int64(argv[0]);
80417   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
80418   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
80419   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80420     sqlite3_result_error_toobig(context);
80421   }else{
80422     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
80423   }
80424 }
80425
80426 /*
80427 ** The replace() function.  Three arguments are all strings: call
80428 ** them A, B, and C. The result is also a string which is derived
80429 ** from A by replacing every occurance of B with C.  The match
80430 ** must be exact.  Collating sequences are not used.
80431 */
80432 static void replaceFunc(
80433   sqlite3_context *context,
80434   int argc,
80435   sqlite3_value **argv
80436 ){
80437   const unsigned char *zStr;        /* The input string A */
80438   const unsigned char *zPattern;    /* The pattern string B */
80439   const unsigned char *zRep;        /* The replacement string C */
80440   unsigned char *zOut;              /* The output */
80441   int nStr;                /* Size of zStr */
80442   int nPattern;            /* Size of zPattern */
80443   int nRep;                /* Size of zRep */
80444   i64 nOut;                /* Maximum size of zOut */
80445   int loopLimit;           /* Last zStr[] that might match zPattern[] */
80446   int i, j;                /* Loop counters */
80447
80448   assert( argc==3 );
80449   UNUSED_PARAMETER(argc);
80450   zStr = sqlite3_value_text(argv[0]);
80451   if( zStr==0 ) return;
80452   nStr = sqlite3_value_bytes(argv[0]);
80453   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
80454   zPattern = sqlite3_value_text(argv[1]);
80455   if( zPattern==0 ){
80456     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
80457             || sqlite3_context_db_handle(context)->mallocFailed );
80458     return;
80459   }
80460   if( zPattern[0]==0 ){
80461     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
80462     sqlite3_result_value(context, argv[0]);
80463     return;
80464   }
80465   nPattern = sqlite3_value_bytes(argv[1]);
80466   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
80467   zRep = sqlite3_value_text(argv[2]);
80468   if( zRep==0 ) return;
80469   nRep = sqlite3_value_bytes(argv[2]);
80470   assert( zRep==sqlite3_value_text(argv[2]) );
80471   nOut = nStr + 1;
80472   assert( nOut<SQLITE_MAX_LENGTH );
80473   zOut = contextMalloc(context, (i64)nOut);
80474   if( zOut==0 ){
80475     return;
80476   }
80477   loopLimit = nStr - nPattern;  
80478   for(i=j=0; i<=loopLimit; i++){
80479     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
80480       zOut[j++] = zStr[i];
80481     }else{
80482       u8 *zOld;
80483       sqlite3 *db = sqlite3_context_db_handle(context);
80484       nOut += nRep - nPattern;
80485       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
80486       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
80487       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
80488         sqlite3_result_error_toobig(context);
80489         sqlite3_free(zOut);
80490         return;
80491       }
80492       zOld = zOut;
80493       zOut = sqlite3_realloc(zOut, (int)nOut);
80494       if( zOut==0 ){
80495         sqlite3_result_error_nomem(context);
80496         sqlite3_free(zOld);
80497         return;
80498       }
80499       memcpy(&zOut[j], zRep, nRep);
80500       j += nRep;
80501       i += nPattern-1;
80502     }
80503   }
80504   assert( j+nStr-i+1==nOut );
80505   memcpy(&zOut[j], &zStr[i], nStr-i);
80506   j += nStr - i;
80507   assert( j<=nOut );
80508   zOut[j] = 0;
80509   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
80510 }
80511
80512 /*
80513 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
80514 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
80515 */
80516 static void trimFunc(
80517   sqlite3_context *context,
80518   int argc,
80519   sqlite3_value **argv
80520 ){
80521   const unsigned char *zIn;         /* Input string */
80522   const unsigned char *zCharSet;    /* Set of characters to trim */
80523   int nIn;                          /* Number of bytes in input */
80524   int flags;                        /* 1: trimleft  2: trimright  3: trim */
80525   int i;                            /* Loop counter */
80526   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
80527   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
80528   int nChar;                        /* Number of characters in zCharSet */
80529
80530   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
80531     return;
80532   }
80533   zIn = sqlite3_value_text(argv[0]);
80534   if( zIn==0 ) return;
80535   nIn = sqlite3_value_bytes(argv[0]);
80536   assert( zIn==sqlite3_value_text(argv[0]) );
80537   if( argc==1 ){
80538     static const unsigned char lenOne[] = { 1 };
80539     static unsigned char * const azOne[] = { (u8*)" " };
80540     nChar = 1;
80541     aLen = (u8*)lenOne;
80542     azChar = (unsigned char **)azOne;
80543     zCharSet = 0;
80544   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
80545     return;
80546   }else{
80547     const unsigned char *z;
80548     for(z=zCharSet, nChar=0; *z; nChar++){
80549       SQLITE_SKIP_UTF8(z);
80550     }
80551     if( nChar>0 ){
80552       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
80553       if( azChar==0 ){
80554         return;
80555       }
80556       aLen = (unsigned char*)&azChar[nChar];
80557       for(z=zCharSet, nChar=0; *z; nChar++){
80558         azChar[nChar] = (unsigned char *)z;
80559         SQLITE_SKIP_UTF8(z);
80560         aLen[nChar] = (u8)(z - azChar[nChar]);
80561       }
80562     }
80563   }
80564   if( nChar>0 ){
80565     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
80566     if( flags & 1 ){
80567       while( nIn>0 ){
80568         int len = 0;
80569         for(i=0; i<nChar; i++){
80570           len = aLen[i];
80571           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
80572         }
80573         if( i>=nChar ) break;
80574         zIn += len;
80575         nIn -= len;
80576       }
80577     }
80578     if( flags & 2 ){
80579       while( nIn>0 ){
80580         int len = 0;
80581         for(i=0; i<nChar; i++){
80582           len = aLen[i];
80583           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
80584         }
80585         if( i>=nChar ) break;
80586         nIn -= len;
80587       }
80588     }
80589     if( zCharSet ){
80590       sqlite3_free(azChar);
80591     }
80592   }
80593   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
80594 }
80595
80596
80597 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
80598 ** is only available if the SQLITE_SOUNDEX compile-time option is used
80599 ** when SQLite is built.
80600 */
80601 #ifdef SQLITE_SOUNDEX
80602 /*
80603 ** Compute the soundex encoding of a word.
80604 **
80605 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
80606 ** soundex encoding of the string X. 
80607 */
80608 static void soundexFunc(
80609   sqlite3_context *context,
80610   int argc,
80611   sqlite3_value **argv
80612 ){
80613   char zResult[8];
80614   const u8 *zIn;
80615   int i, j;
80616   static const unsigned char iCode[] = {
80617     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80618     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80619     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80620     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80621     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
80622     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
80623     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
80624     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
80625   };
80626   assert( argc==1 );
80627   zIn = (u8*)sqlite3_value_text(argv[0]);
80628   if( zIn==0 ) zIn = (u8*)"";
80629   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
80630   if( zIn[i] ){
80631     u8 prevcode = iCode[zIn[i]&0x7f];
80632     zResult[0] = sqlite3Toupper(zIn[i]);
80633     for(j=1; j<4 && zIn[i]; i++){
80634       int code = iCode[zIn[i]&0x7f];
80635       if( code>0 ){
80636         if( code!=prevcode ){
80637           prevcode = code;
80638           zResult[j++] = code + '0';
80639         }
80640       }else{
80641         prevcode = 0;
80642       }
80643     }
80644     while( j<4 ){
80645       zResult[j++] = '0';
80646     }
80647     zResult[j] = 0;
80648     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
80649   }else{
80650     /* IMP: R-64894-50321 The string "?000" is returned if the argument
80651     ** is NULL or contains no ASCII alphabetic characters. */
80652     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
80653   }
80654 }
80655 #endif /* SQLITE_SOUNDEX */
80656
80657 #ifndef SQLITE_OMIT_LOAD_EXTENSION
80658 /*
80659 ** A function that loads a shared-library extension then returns NULL.
80660 */
80661 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
80662   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
80663   const char *zProc;
80664   sqlite3 *db = sqlite3_context_db_handle(context);
80665   char *zErrMsg = 0;
80666
80667   if( argc==2 ){
80668     zProc = (const char *)sqlite3_value_text(argv[1]);
80669   }else{
80670     zProc = 0;
80671   }
80672   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
80673     sqlite3_result_error(context, zErrMsg, -1);
80674     sqlite3_free(zErrMsg);
80675   }
80676 }
80677 #endif
80678
80679
80680 /*
80681 ** An instance of the following structure holds the context of a
80682 ** sum() or avg() aggregate computation.
80683 */
80684 typedef struct SumCtx SumCtx;
80685 struct SumCtx {
80686   double rSum;      /* Floating point sum */
80687   i64 iSum;         /* Integer sum */   
80688   i64 cnt;          /* Number of elements summed */
80689   u8 overflow;      /* True if integer overflow seen */
80690   u8 approx;        /* True if non-integer value was input to the sum */
80691 };
80692
80693 /*
80694 ** Routines used to compute the sum, average, and total.
80695 **
80696 ** The SUM() function follows the (broken) SQL standard which means
80697 ** that it returns NULL if it sums over no inputs.  TOTAL returns
80698 ** 0.0 in that case.  In addition, TOTAL always returns a float where
80699 ** SUM might return an integer if it never encounters a floating point
80700 ** value.  TOTAL never fails, but SUM might through an exception if
80701 ** it overflows an integer.
80702 */
80703 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
80704   SumCtx *p;
80705   int type;
80706   assert( argc==1 );
80707   UNUSED_PARAMETER(argc);
80708   p = sqlite3_aggregate_context(context, sizeof(*p));
80709   type = sqlite3_value_numeric_type(argv[0]);
80710   if( p && type!=SQLITE_NULL ){
80711     p->cnt++;
80712     if( type==SQLITE_INTEGER ){
80713       i64 v = sqlite3_value_int64(argv[0]);
80714       p->rSum += v;
80715       if( (p->approx|p->overflow)==0 ){
80716         i64 iNewSum = p->iSum + v;
80717         int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
80718         int s2 = (int)(v       >> (sizeof(i64)*8-1));
80719         int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
80720         p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
80721         p->iSum = iNewSum;
80722       }
80723     }else{
80724       p->rSum += sqlite3_value_double(argv[0]);
80725       p->approx = 1;
80726     }
80727   }
80728 }
80729 static void sumFinalize(sqlite3_context *context){
80730   SumCtx *p;
80731   p = sqlite3_aggregate_context(context, 0);
80732   if( p && p->cnt>0 ){
80733     if( p->overflow ){
80734       sqlite3_result_error(context,"integer overflow",-1);
80735     }else if( p->approx ){
80736       sqlite3_result_double(context, p->rSum);
80737     }else{
80738       sqlite3_result_int64(context, p->iSum);
80739     }
80740   }
80741 }
80742 static void avgFinalize(sqlite3_context *context){
80743   SumCtx *p;
80744   p = sqlite3_aggregate_context(context, 0);
80745   if( p && p->cnt>0 ){
80746     sqlite3_result_double(context, p->rSum/(double)p->cnt);
80747   }
80748 }
80749 static void totalFinalize(sqlite3_context *context){
80750   SumCtx *p;
80751   p = sqlite3_aggregate_context(context, 0);
80752   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
80753   sqlite3_result_double(context, p ? p->rSum : (double)0);
80754 }
80755
80756 /*
80757 ** The following structure keeps track of state information for the
80758 ** count() aggregate function.
80759 */
80760 typedef struct CountCtx CountCtx;
80761 struct CountCtx {
80762   i64 n;
80763 };
80764
80765 /*
80766 ** Routines to implement the count() aggregate function.
80767 */
80768 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
80769   CountCtx *p;
80770   p = sqlite3_aggregate_context(context, sizeof(*p));
80771   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
80772     p->n++;
80773   }
80774
80775 #ifndef SQLITE_OMIT_DEPRECATED
80776   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
80777   ** sure it still operates correctly, verify that its count agrees with our 
80778   ** internal count when using count(*) and when the total count can be
80779   ** expressed as a 32-bit integer. */
80780   assert( argc==1 || p==0 || p->n>0x7fffffff
80781           || p->n==sqlite3_aggregate_count(context) );
80782 #endif
80783 }   
80784 static void countFinalize(sqlite3_context *context){
80785   CountCtx *p;
80786   p = sqlite3_aggregate_context(context, 0);
80787   sqlite3_result_int64(context, p ? p->n : 0);
80788 }
80789
80790 /*
80791 ** Routines to implement min() and max() aggregate functions.
80792 */
80793 static void minmaxStep(
80794   sqlite3_context *context, 
80795   int NotUsed, 
80796   sqlite3_value **argv
80797 ){
80798   Mem *pArg  = (Mem *)argv[0];
80799   Mem *pBest;
80800   UNUSED_PARAMETER(NotUsed);
80801
80802   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
80803   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
80804   if( !pBest ) return;
80805
80806   if( pBest->flags ){
80807     int max;
80808     int cmp;
80809     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
80810     /* This step function is used for both the min() and max() aggregates,
80811     ** the only difference between the two being that the sense of the
80812     ** comparison is inverted. For the max() aggregate, the
80813     ** sqlite3_user_data() function returns (void *)-1. For min() it
80814     ** returns (void *)db, where db is the sqlite3* database pointer.
80815     ** Therefore the next statement sets variable 'max' to 1 for the max()
80816     ** aggregate, or 0 for min().
80817     */
80818     max = sqlite3_user_data(context)!=0;
80819     cmp = sqlite3MemCompare(pBest, pArg, pColl);
80820     if( (max && cmp<0) || (!max && cmp>0) ){
80821       sqlite3VdbeMemCopy(pBest, pArg);
80822     }
80823   }else{
80824     sqlite3VdbeMemCopy(pBest, pArg);
80825   }
80826 }
80827 static void minMaxFinalize(sqlite3_context *context){
80828   sqlite3_value *pRes;
80829   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
80830   if( pRes ){
80831     if( ALWAYS(pRes->flags) ){
80832       sqlite3_result_value(context, pRes);
80833     }
80834     sqlite3VdbeMemRelease(pRes);
80835   }
80836 }
80837
80838 /*
80839 ** group_concat(EXPR, ?SEPARATOR?)
80840 */
80841 static void groupConcatStep(
80842   sqlite3_context *context,
80843   int argc,
80844   sqlite3_value **argv
80845 ){
80846   const char *zVal;
80847   StrAccum *pAccum;
80848   const char *zSep;
80849   int nVal, nSep;
80850   assert( argc==1 || argc==2 );
80851   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
80852   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
80853
80854   if( pAccum ){
80855     sqlite3 *db = sqlite3_context_db_handle(context);
80856     int firstTerm = pAccum->useMalloc==0;
80857     pAccum->useMalloc = 2;
80858     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
80859     if( !firstTerm ){
80860       if( argc==2 ){
80861         zSep = (char*)sqlite3_value_text(argv[1]);
80862         nSep = sqlite3_value_bytes(argv[1]);
80863       }else{
80864         zSep = ",";
80865         nSep = 1;
80866       }
80867       sqlite3StrAccumAppend(pAccum, zSep, nSep);
80868     }
80869     zVal = (char*)sqlite3_value_text(argv[0]);
80870     nVal = sqlite3_value_bytes(argv[0]);
80871     sqlite3StrAccumAppend(pAccum, zVal, nVal);
80872   }
80873 }
80874 static void groupConcatFinalize(sqlite3_context *context){
80875   StrAccum *pAccum;
80876   pAccum = sqlite3_aggregate_context(context, 0);
80877   if( pAccum ){
80878     if( pAccum->tooBig ){
80879       sqlite3_result_error_toobig(context);
80880     }else if( pAccum->mallocFailed ){
80881       sqlite3_result_error_nomem(context);
80882     }else{    
80883       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
80884                           sqlite3_free);
80885     }
80886   }
80887 }
80888
80889 /*
80890 ** This routine does per-connection function registration.  Most
80891 ** of the built-in functions above are part of the global function set.
80892 ** This routine only deals with those that are not global.
80893 */
80894 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
80895   int rc = sqlite3_overload_function(db, "MATCH", 2);
80896   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
80897   if( rc==SQLITE_NOMEM ){
80898     db->mallocFailed = 1;
80899   }
80900 }
80901
80902 /*
80903 ** Set the LIKEOPT flag on the 2-argument function with the given name.
80904 */
80905 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
80906   FuncDef *pDef;
80907   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
80908                              2, SQLITE_UTF8, 0);
80909   if( ALWAYS(pDef) ){
80910     pDef->flags = flagVal;
80911   }
80912 }
80913
80914 /*
80915 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
80916 ** parameter determines whether or not the LIKE operator is case
80917 ** sensitive.  GLOB is always case sensitive.
80918 */
80919 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
80920   struct compareInfo *pInfo;
80921   if( caseSensitive ){
80922     pInfo = (struct compareInfo*)&likeInfoAlt;
80923   }else{
80924     pInfo = (struct compareInfo*)&likeInfoNorm;
80925   }
80926   sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0, 0);
80927   sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0, 0);
80928   sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY, 
80929       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
80930   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
80931   setLikeOptFlag(db, "like", 
80932       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
80933 }
80934
80935 /*
80936 ** pExpr points to an expression which implements a function.  If
80937 ** it is appropriate to apply the LIKE optimization to that function
80938 ** then set aWc[0] through aWc[2] to the wildcard characters and
80939 ** return TRUE.  If the function is not a LIKE-style function then
80940 ** return FALSE.
80941 */
80942 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
80943   FuncDef *pDef;
80944   if( pExpr->op!=TK_FUNCTION 
80945    || !pExpr->x.pList 
80946    || pExpr->x.pList->nExpr!=2
80947   ){
80948     return 0;
80949   }
80950   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
80951   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
80952                              sqlite3Strlen30(pExpr->u.zToken),
80953                              2, SQLITE_UTF8, 0);
80954   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
80955     return 0;
80956   }
80957
80958   /* The memcpy() statement assumes that the wildcard characters are
80959   ** the first three statements in the compareInfo structure.  The
80960   ** asserts() that follow verify that assumption
80961   */
80962   memcpy(aWc, pDef->pUserData, 3);
80963   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
80964   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
80965   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
80966   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
80967   return 1;
80968 }
80969
80970 /*
80971 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
80972 ** to the global function hash table.  This occurs at start-time (as
80973 ** a consequence of calling sqlite3_initialize()).
80974 **
80975 ** After this routine runs
80976 */
80977 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
80978   /*
80979   ** The following array holds FuncDef structures for all of the functions
80980   ** defined in this file.
80981   **
80982   ** The array cannot be constant since changes are made to the
80983   ** FuncDef.pHash elements at start-time.  The elements of this array
80984   ** are read-only after initialization is complete.
80985   */
80986   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
80987     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
80988     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
80989     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
80990     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
80991     FUNCTION(trim,               1, 3, 0, trimFunc         ),
80992     FUNCTION(trim,               2, 3, 0, trimFunc         ),
80993     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
80994     FUNCTION(min,                0, 0, 1, 0                ),
80995     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
80996     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
80997     FUNCTION(max,                0, 1, 1, 0                ),
80998     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
80999     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
81000     FUNCTION(length,             1, 0, 0, lengthFunc       ),
81001     FUNCTION(substr,             2, 0, 0, substrFunc       ),
81002     FUNCTION(substr,             3, 0, 0, substrFunc       ),
81003     FUNCTION(abs,                1, 0, 0, absFunc          ),
81004 #ifndef SQLITE_OMIT_FLOATING_POINT
81005     FUNCTION(round,              1, 0, 0, roundFunc        ),
81006     FUNCTION(round,              2, 0, 0, roundFunc        ),
81007 #endif
81008     FUNCTION(upper,              1, 0, 0, upperFunc        ),
81009     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
81010     FUNCTION(coalesce,           1, 0, 0, 0                ),
81011     FUNCTION(coalesce,           0, 0, 0, 0                ),
81012 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
81013     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
81014     FUNCTION(hex,                1, 0, 0, hexFunc          ),
81015 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
81016     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
81017     FUNCTION(random,             0, 0, 0, randomFunc       ),
81018     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
81019     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
81020     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
81021     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
81022 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
81023     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
81024     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
81025 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
81026     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
81027     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
81028     FUNCTION(changes,            0, 0, 0, changes          ),
81029     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
81030     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
81031     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
81032   #ifdef SQLITE_SOUNDEX
81033     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
81034   #endif
81035   #ifndef SQLITE_OMIT_LOAD_EXTENSION
81036     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
81037     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
81038   #endif
81039     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
81040     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
81041     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
81042  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
81043     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
81044     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
81045     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
81046     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
81047   
81048     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
81049   #ifdef SQLITE_CASE_SENSITIVE_LIKE
81050     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
81051     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
81052   #else
81053     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
81054     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
81055   #endif
81056   };
81057
81058   int i;
81059   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
81060   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
81061
81062   for(i=0; i<ArraySize(aBuiltinFunc); i++){
81063     sqlite3FuncDefInsert(pHash, &aFunc[i]);
81064   }
81065   sqlite3RegisterDateTimeFunctions();
81066 #ifndef SQLITE_OMIT_ALTERTABLE
81067   sqlite3AlterFunctions();
81068 #endif
81069 }
81070
81071 /************** End of func.c ************************************************/
81072 /************** Begin file fkey.c ********************************************/
81073 /*
81074 **
81075 ** The author disclaims copyright to this source code.  In place of
81076 ** a legal notice, here is a blessing:
81077 **
81078 **    May you do good and not evil.
81079 **    May you find forgiveness for yourself and forgive others.
81080 **    May you share freely, never taking more than you give.
81081 **
81082 *************************************************************************
81083 ** This file contains code used by the compiler to add foreign key
81084 ** support to compiled SQL statements.
81085 */
81086
81087 #ifndef SQLITE_OMIT_FOREIGN_KEY
81088 #ifndef SQLITE_OMIT_TRIGGER
81089
81090 /*
81091 ** Deferred and Immediate FKs
81092 ** --------------------------
81093 **
81094 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
81095 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
81096 ** is returned and the current statement transaction rolled back. If a 
81097 ** deferred foreign key constraint is violated, no action is taken 
81098 ** immediately. However if the application attempts to commit the 
81099 ** transaction before fixing the constraint violation, the attempt fails.
81100 **
81101 ** Deferred constraints are implemented using a simple counter associated
81102 ** with the database handle. The counter is set to zero each time a 
81103 ** database transaction is opened. Each time a statement is executed 
81104 ** that causes a foreign key violation, the counter is incremented. Each
81105 ** time a statement is executed that removes an existing violation from
81106 ** the database, the counter is decremented. When the transaction is
81107 ** committed, the commit fails if the current value of the counter is
81108 ** greater than zero. This scheme has two big drawbacks:
81109 **
81110 **   * When a commit fails due to a deferred foreign key constraint, 
81111 **     there is no way to tell which foreign constraint is not satisfied,
81112 **     or which row it is not satisfied for.
81113 **
81114 **   * If the database contains foreign key violations when the 
81115 **     transaction is opened, this may cause the mechanism to malfunction.
81116 **
81117 ** Despite these problems, this approach is adopted as it seems simpler
81118 ** than the alternatives.
81119 **
81120 ** INSERT operations:
81121 **
81122 **   I.1) For each FK for which the table is the child table, search
81123 **        the parent table for a match. If none is found increment the
81124 **        constraint counter.
81125 **
81126 **   I.2) For each FK for which the table is the parent table, 
81127 **        search the child table for rows that correspond to the new
81128 **        row in the parent table. Decrement the counter for each row
81129 **        found (as the constraint is now satisfied).
81130 **
81131 ** DELETE operations:
81132 **
81133 **   D.1) For each FK for which the table is the child table, 
81134 **        search the parent table for a row that corresponds to the 
81135 **        deleted row in the child table. If such a row is not found, 
81136 **        decrement the counter.
81137 **
81138 **   D.2) For each FK for which the table is the parent table, search 
81139 **        the child table for rows that correspond to the deleted row 
81140 **        in the parent table. For each found increment the counter.
81141 **
81142 ** UPDATE operations:
81143 **
81144 **   An UPDATE command requires that all 4 steps above are taken, but only
81145 **   for FK constraints for which the affected columns are actually 
81146 **   modified (values must be compared at runtime).
81147 **
81148 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
81149 ** This simplifies the implementation a bit.
81150 **
81151 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
81152 ** resolution is considered to delete rows before the new row is inserted.
81153 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
81154 ** is thrown, even if the FK constraint would be satisfied after the new 
81155 ** row is inserted.
81156 **
81157 ** Immediate constraints are usually handled similarly. The only difference 
81158 ** is that the counter used is stored as part of each individual statement
81159 ** object (struct Vdbe). If, after the statement has run, its immediate
81160 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
81161 ** and the statement transaction is rolled back. An exception is an INSERT
81162 ** statement that inserts a single row only (no triggers). In this case,
81163 ** instead of using a counter, an exception is thrown immediately if the
81164 ** INSERT violates a foreign key constraint. This is necessary as such
81165 ** an INSERT does not open a statement transaction.
81166 **
81167 ** TODO: How should dropping a table be handled? How should renaming a 
81168 ** table be handled?
81169 **
81170 **
81171 ** Query API Notes
81172 ** ---------------
81173 **
81174 ** Before coding an UPDATE or DELETE row operation, the code-generator
81175 ** for those two operations needs to know whether or not the operation
81176 ** requires any FK processing and, if so, which columns of the original
81177 ** row are required by the FK processing VDBE code (i.e. if FKs were
81178 ** implemented using triggers, which of the old.* columns would be 
81179 ** accessed). No information is required by the code-generator before
81180 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
81181 ** generation code to query for this information are:
81182 **
81183 **   sqlite3FkRequired() - Test to see if FK processing is required.
81184 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
81185 **
81186 **
81187 ** Externally accessible module functions
81188 ** --------------------------------------
81189 **
81190 **   sqlite3FkCheck()    - Check for foreign key violations.
81191 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
81192 **   sqlite3FkDelete()   - Delete an FKey structure.
81193 */
81194
81195 /*
81196 ** VDBE Calling Convention
81197 ** -----------------------
81198 **
81199 ** Example:
81200 **
81201 **   For the following INSERT statement:
81202 **
81203 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
81204 **     INSERT INTO t1 VALUES(1, 2, 3.1);
81205 **
81206 **   Register (x):        2    (type integer)
81207 **   Register (x+1):      1    (type integer)
81208 **   Register (x+2):      NULL (type NULL)
81209 **   Register (x+3):      3.1  (type real)
81210 */
81211
81212 /*
81213 ** A foreign key constraint requires that the key columns in the parent
81214 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
81215 ** Given that pParent is the parent table for foreign key constraint pFKey, 
81216 ** search the schema a unique index on the parent key columns. 
81217 **
81218 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
81219 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
81220 ** is set to point to the unique index. 
81221 ** 
81222 ** If the parent key consists of a single column (the foreign key constraint
81223 ** is not a composite foreign key), output variable *paiCol is set to NULL.
81224 ** Otherwise, it is set to point to an allocated array of size N, where
81225 ** N is the number of columns in the parent key. The first element of the
81226 ** array is the index of the child table column that is mapped by the FK
81227 ** constraint to the parent table column stored in the left-most column
81228 ** of index *ppIdx. The second element of the array is the index of the
81229 ** child table column that corresponds to the second left-most column of
81230 ** *ppIdx, and so on.
81231 **
81232 ** If the required index cannot be found, either because:
81233 **
81234 **   1) The named parent key columns do not exist, or
81235 **
81236 **   2) The named parent key columns do exist, but are not subject to a
81237 **      UNIQUE or PRIMARY KEY constraint, or
81238 **
81239 **   3) No parent key columns were provided explicitly as part of the
81240 **      foreign key definition, and the parent table does not have a
81241 **      PRIMARY KEY, or
81242 **
81243 **   4) No parent key columns were provided explicitly as part of the
81244 **      foreign key definition, and the PRIMARY KEY of the parent table 
81245 **      consists of a a different number of columns to the child key in 
81246 **      the child table.
81247 **
81248 ** then non-zero is returned, and a "foreign key mismatch" error loaded
81249 ** into pParse. If an OOM error occurs, non-zero is returned and the
81250 ** pParse->db->mallocFailed flag is set.
81251 */
81252 static int locateFkeyIndex(
81253   Parse *pParse,                  /* Parse context to store any error in */
81254   Table *pParent,                 /* Parent table of FK constraint pFKey */
81255   FKey *pFKey,                    /* Foreign key to find index for */
81256   Index **ppIdx,                  /* OUT: Unique index on parent table */
81257   int **paiCol                    /* OUT: Map of index columns in pFKey */
81258 ){
81259   Index *pIdx = 0;                    /* Value to return via *ppIdx */
81260   int *aiCol = 0;                     /* Value to return via *paiCol */
81261   int nCol = pFKey->nCol;             /* Number of columns in parent key */
81262   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
81263
81264   /* The caller is responsible for zeroing output parameters. */
81265   assert( ppIdx && *ppIdx==0 );
81266   assert( !paiCol || *paiCol==0 );
81267   assert( pParse );
81268
81269   /* If this is a non-composite (single column) foreign key, check if it 
81270   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
81271   ** and *paiCol set to zero and return early. 
81272   **
81273   ** Otherwise, for a composite foreign key (more than one column), allocate
81274   ** space for the aiCol array (returned via output parameter *paiCol).
81275   ** Non-composite foreign keys do not require the aiCol array.
81276   */
81277   if( nCol==1 ){
81278     /* The FK maps to the IPK if any of the following are true:
81279     **
81280     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
81281     **      mapped to the primary key of table pParent, or
81282     **   2) The FK is explicitly mapped to a column declared as INTEGER
81283     **      PRIMARY KEY.
81284     */
81285     if( pParent->iPKey>=0 ){
81286       if( !zKey ) return 0;
81287       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
81288     }
81289   }else if( paiCol ){
81290     assert( nCol>1 );
81291     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
81292     if( !aiCol ) return 1;
81293     *paiCol = aiCol;
81294   }
81295
81296   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
81297     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
81298       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
81299       ** of columns. If each indexed column corresponds to a foreign key
81300       ** column of pFKey, then this index is a winner.  */
81301
81302       if( zKey==0 ){
81303         /* If zKey is NULL, then this foreign key is implicitly mapped to 
81304         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
81305         ** identified by the test (Index.autoIndex==2).  */
81306         if( pIdx->autoIndex==2 ){
81307           if( aiCol ){
81308             int i;
81309             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
81310           }
81311           break;
81312         }
81313       }else{
81314         /* If zKey is non-NULL, then this foreign key was declared to
81315         ** map to an explicit list of columns in table pParent. Check if this
81316         ** index matches those columns. Also, check that the index uses
81317         ** the default collation sequences for each column. */
81318         int i, j;
81319         for(i=0; i<nCol; i++){
81320           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
81321           char *zDfltColl;                  /* Def. collation for column */
81322           char *zIdxCol;                    /* Name of indexed column */
81323
81324           /* If the index uses a collation sequence that is different from
81325           ** the default collation sequence for the column, this index is
81326           ** unusable. Bail out early in this case.  */
81327           zDfltColl = pParent->aCol[iCol].zColl;
81328           if( !zDfltColl ){
81329             zDfltColl = "BINARY";
81330           }
81331           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
81332
81333           zIdxCol = pParent->aCol[iCol].zName;
81334           for(j=0; j<nCol; j++){
81335             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
81336               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
81337               break;
81338             }
81339           }
81340           if( j==nCol ) break;
81341         }
81342         if( i==nCol ) break;      /* pIdx is usable */
81343       }
81344     }
81345   }
81346
81347   if( !pIdx ){
81348     if( !pParse->disableTriggers ){
81349       sqlite3ErrorMsg(pParse, "foreign key mismatch");
81350     }
81351     sqlite3DbFree(pParse->db, aiCol);
81352     return 1;
81353   }
81354
81355   *ppIdx = pIdx;
81356   return 0;
81357 }
81358
81359 /*
81360 ** This function is called when a row is inserted into or deleted from the 
81361 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
81362 ** on the child table of pFKey, this function is invoked twice for each row
81363 ** affected - once to "delete" the old row, and then again to "insert" the
81364 ** new row.
81365 **
81366 ** Each time it is called, this function generates VDBE code to locate the
81367 ** row in the parent table that corresponds to the row being inserted into 
81368 ** or deleted from the child table. If the parent row can be found, no 
81369 ** special action is taken. Otherwise, if the parent row can *not* be
81370 ** found in the parent table:
81371 **
81372 **   Operation | FK type   | Action taken
81373 **   --------------------------------------------------------------------------
81374 **   INSERT      immediate   Increment the "immediate constraint counter".
81375 **
81376 **   DELETE      immediate   Decrement the "immediate constraint counter".
81377 **
81378 **   INSERT      deferred    Increment the "deferred constraint counter".
81379 **
81380 **   DELETE      deferred    Decrement the "deferred constraint counter".
81381 **
81382 ** These operations are identified in the comment at the top of this file 
81383 ** (fkey.c) as "I.1" and "D.1".
81384 */
81385 static void fkLookupParent(
81386   Parse *pParse,        /* Parse context */
81387   int iDb,              /* Index of database housing pTab */
81388   Table *pTab,          /* Parent table of FK pFKey */
81389   Index *pIdx,          /* Unique index on parent key columns in pTab */
81390   FKey *pFKey,          /* Foreign key constraint */
81391   int *aiCol,           /* Map from parent key columns to child table columns */
81392   int regData,          /* Address of array containing child table row */
81393   int nIncr,            /* Increment constraint counter by this */
81394   int isIgnore          /* If true, pretend pTab contains all NULL values */
81395 ){
81396   int i;                                    /* Iterator variable */
81397   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
81398   int iCur = pParse->nTab - 1;              /* Cursor number to use */
81399   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
81400
81401   /* If nIncr is less than zero, then check at runtime if there are any
81402   ** outstanding constraints to resolve. If there are not, there is no need
81403   ** to check if deleting this row resolves any outstanding violations.
81404   **
81405   ** Check if any of the key columns in the child table row are NULL. If 
81406   ** any are, then the constraint is considered satisfied. No need to 
81407   ** search for a matching row in the parent table.  */
81408   if( nIncr<0 ){
81409     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
81410   }
81411   for(i=0; i<pFKey->nCol; i++){
81412     int iReg = aiCol[i] + regData + 1;
81413     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
81414   }
81415
81416   if( isIgnore==0 ){
81417     if( pIdx==0 ){
81418       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
81419       ** column of the parent table (table pTab).  */
81420       int iMustBeInt;               /* Address of MustBeInt instruction */
81421       int regTemp = sqlite3GetTempReg(pParse);
81422   
81423       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
81424       ** apply the affinity of the parent key). If this fails, then there
81425       ** is no matching parent key. Before using MustBeInt, make a copy of
81426       ** the value. Otherwise, the value inserted into the child key column
81427       ** will have INTEGER affinity applied to it, which may not be correct.  */
81428       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
81429       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
81430   
81431       /* If the parent table is the same as the child table, and we are about
81432       ** to increment the constraint-counter (i.e. this is an INSERT operation),
81433       ** then check if the row being inserted matches itself. If so, do not
81434       ** increment the constraint-counter.  */
81435       if( pTab==pFKey->pFrom && nIncr==1 ){
81436         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
81437       }
81438   
81439       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
81440       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
81441       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
81442       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
81443       sqlite3VdbeJumpHere(v, iMustBeInt);
81444       sqlite3ReleaseTempReg(pParse, regTemp);
81445     }else{
81446       int nCol = pFKey->nCol;
81447       int regTemp = sqlite3GetTempRange(pParse, nCol);
81448       int regRec = sqlite3GetTempReg(pParse);
81449       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
81450   
81451       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
81452       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
81453       for(i=0; i<nCol; i++){
81454         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
81455       }
81456   
81457       /* If the parent table is the same as the child table, and we are about
81458       ** to increment the constraint-counter (i.e. this is an INSERT operation),
81459       ** then check if the row being inserted matches itself. If so, do not
81460       ** increment the constraint-counter.  */
81461       if( pTab==pFKey->pFrom && nIncr==1 ){
81462         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
81463         for(i=0; i<nCol; i++){
81464           int iChild = aiCol[i]+1+regData;
81465           int iParent = pIdx->aiColumn[i]+1+regData;
81466           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
81467         }
81468         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
81469       }
81470   
81471       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
81472       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
81473       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
81474   
81475       sqlite3ReleaseTempReg(pParse, regRec);
81476       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
81477     }
81478   }
81479
81480   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
81481     /* Special case: If this is an INSERT statement that will insert exactly
81482     ** one row into the table, raise a constraint immediately instead of
81483     ** incrementing a counter. This is necessary as the VM code is being
81484     ** generated for will not open a statement transaction.  */
81485     assert( nIncr==1 );
81486     sqlite3HaltConstraint(
81487         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
81488     );
81489   }else{
81490     if( nIncr>0 && pFKey->isDeferred==0 ){
81491       sqlite3ParseToplevel(pParse)->mayAbort = 1;
81492     }
81493     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
81494   }
81495
81496   sqlite3VdbeResolveLabel(v, iOk);
81497   sqlite3VdbeAddOp1(v, OP_Close, iCur);
81498 }
81499
81500 /*
81501 ** This function is called to generate code executed when a row is deleted
81502 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
81503 ** deferred, when a row is inserted into the same table. When generating
81504 ** code for an SQL UPDATE operation, this function may be called twice -
81505 ** once to "delete" the old row and once to "insert" the new row.
81506 **
81507 ** The code generated by this function scans through the rows in the child
81508 ** table that correspond to the parent table row being deleted or inserted.
81509 ** For each child row found, one of the following actions is taken:
81510 **
81511 **   Operation | FK type   | Action taken
81512 **   --------------------------------------------------------------------------
81513 **   DELETE      immediate   Increment the "immediate constraint counter".
81514 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
81515 **                           throw a "foreign key constraint failed" exception.
81516 **
81517 **   INSERT      immediate   Decrement the "immediate constraint counter".
81518 **
81519 **   DELETE      deferred    Increment the "deferred constraint counter".
81520 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
81521 **                           throw a "foreign key constraint failed" exception.
81522 **
81523 **   INSERT      deferred    Decrement the "deferred constraint counter".
81524 **
81525 ** These operations are identified in the comment at the top of this file 
81526 ** (fkey.c) as "I.2" and "D.2".
81527 */
81528 static void fkScanChildren(
81529   Parse *pParse,                  /* Parse context */
81530   SrcList *pSrc,                  /* SrcList containing the table to scan */
81531   Table *pTab,
81532   Index *pIdx,                    /* Foreign key index */
81533   FKey *pFKey,                    /* Foreign key relationship */
81534   int *aiCol,                     /* Map from pIdx cols to child table cols */
81535   int regData,                    /* Referenced table data starts here */
81536   int nIncr                       /* Amount to increment deferred counter by */
81537 ){
81538   sqlite3 *db = pParse->db;       /* Database handle */
81539   int i;                          /* Iterator variable */
81540   Expr *pWhere = 0;               /* WHERE clause to scan with */
81541   NameContext sNameContext;       /* Context used to resolve WHERE clause */
81542   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
81543   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
81544   Vdbe *v = sqlite3GetVdbe(pParse);
81545
81546   assert( !pIdx || pIdx->pTable==pTab );
81547
81548   if( nIncr<0 ){
81549     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
81550   }
81551
81552   /* Create an Expr object representing an SQL expression like:
81553   **
81554   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
81555   **
81556   ** The collation sequence used for the comparison should be that of
81557   ** the parent key columns. The affinity of the parent key column should
81558   ** be applied to each child key value before the comparison takes place.
81559   */
81560   for(i=0; i<pFKey->nCol; i++){
81561     Expr *pLeft;                  /* Value from parent table row */
81562     Expr *pRight;                 /* Column ref to child table */
81563     Expr *pEq;                    /* Expression (pLeft = pRight) */
81564     int iCol;                     /* Index of column in child table */ 
81565     const char *zCol;             /* Name of column in child table */
81566
81567     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
81568     if( pLeft ){
81569       /* Set the collation sequence and affinity of the LHS of each TK_EQ
81570       ** expression to the parent key column defaults.  */
81571       if( pIdx ){
81572         Column *pCol;
81573         iCol = pIdx->aiColumn[i];
81574         pCol = &pTab->aCol[iCol];
81575         if( pTab->iPKey==iCol ) iCol = -1;
81576         pLeft->iTable = regData+iCol+1;
81577         pLeft->affinity = pCol->affinity;
81578         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
81579       }else{
81580         pLeft->iTable = regData;
81581         pLeft->affinity = SQLITE_AFF_INTEGER;
81582       }
81583     }
81584     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
81585     assert( iCol>=0 );
81586     zCol = pFKey->pFrom->aCol[iCol].zName;
81587     pRight = sqlite3Expr(db, TK_ID, zCol);
81588     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
81589     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
81590   }
81591
81592   /* If the child table is the same as the parent table, and this scan
81593   ** is taking place as part of a DELETE operation (operation D.2), omit the
81594   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
81595   ** clause, where $rowid is the rowid of the row being deleted.  */
81596   if( pTab==pFKey->pFrom && nIncr>0 ){
81597     Expr *pEq;                    /* Expression (pLeft = pRight) */
81598     Expr *pLeft;                  /* Value from parent table row */
81599     Expr *pRight;                 /* Column ref to child table */
81600     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
81601     pRight = sqlite3Expr(db, TK_COLUMN, 0);
81602     if( pLeft && pRight ){
81603       pLeft->iTable = regData;
81604       pLeft->affinity = SQLITE_AFF_INTEGER;
81605       pRight->iTable = pSrc->a[0].iCursor;
81606       pRight->iColumn = -1;
81607     }
81608     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
81609     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
81610   }
81611
81612   /* Resolve the references in the WHERE clause. */
81613   memset(&sNameContext, 0, sizeof(NameContext));
81614   sNameContext.pSrcList = pSrc;
81615   sNameContext.pParse = pParse;
81616   sqlite3ResolveExprNames(&sNameContext, pWhere);
81617
81618   /* Create VDBE to loop through the entries in pSrc that match the WHERE
81619   ** clause. If the constraint is not deferred, throw an exception for
81620   ** each row found. Otherwise, for deferred constraints, increment the
81621   ** deferred constraint counter by nIncr for each row selected.  */
81622   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
81623   if( nIncr>0 && pFKey->isDeferred==0 ){
81624     sqlite3ParseToplevel(pParse)->mayAbort = 1;
81625   }
81626   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
81627   if( pWInfo ){
81628     sqlite3WhereEnd(pWInfo);
81629   }
81630
81631   /* Clean up the WHERE clause constructed above. */
81632   sqlite3ExprDelete(db, pWhere);
81633   if( iFkIfZero ){
81634     sqlite3VdbeJumpHere(v, iFkIfZero);
81635   }
81636 }
81637
81638 /*
81639 ** This function returns a pointer to the head of a linked list of FK
81640 ** constraints for which table pTab is the parent table. For example,
81641 ** given the following schema:
81642 **
81643 **   CREATE TABLE t1(a PRIMARY KEY);
81644 **   CREATE TABLE t2(b REFERENCES t1(a);
81645 **
81646 ** Calling this function with table "t1" as an argument returns a pointer
81647 ** to the FKey structure representing the foreign key constraint on table
81648 ** "t2". Calling this function with "t2" as the argument would return a
81649 ** NULL pointer (as there are no FK constraints for which t2 is the parent
81650 ** table).
81651 */
81652 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
81653   int nName = sqlite3Strlen30(pTab->zName);
81654   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
81655 }
81656
81657 /*
81658 ** The second argument is a Trigger structure allocated by the 
81659 ** fkActionTrigger() routine. This function deletes the Trigger structure
81660 ** and all of its sub-components.
81661 **
81662 ** The Trigger structure or any of its sub-components may be allocated from
81663 ** the lookaside buffer belonging to database handle dbMem.
81664 */
81665 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
81666   if( p ){
81667     TriggerStep *pStep = p->step_list;
81668     sqlite3ExprDelete(dbMem, pStep->pWhere);
81669     sqlite3ExprListDelete(dbMem, pStep->pExprList);
81670     sqlite3SelectDelete(dbMem, pStep->pSelect);
81671     sqlite3ExprDelete(dbMem, p->pWhen);
81672     sqlite3DbFree(dbMem, p);
81673   }
81674 }
81675
81676 /*
81677 ** This function is called to generate code that runs when table pTab is
81678 ** being dropped from the database. The SrcList passed as the second argument
81679 ** to this function contains a single entry guaranteed to resolve to
81680 ** table pTab.
81681 **
81682 ** Normally, no code is required. However, if either
81683 **
81684 **   (a) The table is the parent table of a FK constraint, or
81685 **   (b) The table is the child table of a deferred FK constraint and it is
81686 **       determined at runtime that there are outstanding deferred FK 
81687 **       constraint violations in the database,
81688 **
81689 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
81690 ** the table from the database. Triggers are disabled while running this
81691 ** DELETE, but foreign key actions are not.
81692 */
81693 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
81694   sqlite3 *db = pParse->db;
81695   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
81696     int iSkip = 0;
81697     Vdbe *v = sqlite3GetVdbe(pParse);
81698
81699     assert( v );                  /* VDBE has already been allocated */
81700     if( sqlite3FkReferences(pTab)==0 ){
81701       /* Search for a deferred foreign key constraint for which this table
81702       ** is the child table. If one cannot be found, return without 
81703       ** generating any VDBE code. If one can be found, then jump over
81704       ** the entire DELETE if there are no outstanding deferred constraints
81705       ** when this statement is run.  */
81706       FKey *p;
81707       for(p=pTab->pFKey; p; p=p->pNextFrom){
81708         if( p->isDeferred ) break;
81709       }
81710       if( !p ) return;
81711       iSkip = sqlite3VdbeMakeLabel(v);
81712       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
81713     }
81714
81715     pParse->disableTriggers = 1;
81716     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
81717     pParse->disableTriggers = 0;
81718
81719     /* If the DELETE has generated immediate foreign key constraint 
81720     ** violations, halt the VDBE and return an error at this point, before
81721     ** any modifications to the schema are made. This is because statement
81722     ** transactions are not able to rollback schema changes.  */
81723     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
81724     sqlite3HaltConstraint(
81725         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
81726     );
81727
81728     if( iSkip ){
81729       sqlite3VdbeResolveLabel(v, iSkip);
81730     }
81731   }
81732 }
81733
81734 /*
81735 ** This function is called when inserting, deleting or updating a row of
81736 ** table pTab to generate VDBE code to perform foreign key constraint 
81737 ** processing for the operation.
81738 **
81739 ** For a DELETE operation, parameter regOld is passed the index of the
81740 ** first register in an array of (pTab->nCol+1) registers containing the
81741 ** rowid of the row being deleted, followed by each of the column values
81742 ** of the row being deleted, from left to right. Parameter regNew is passed
81743 ** zero in this case.
81744 **
81745 ** For an INSERT operation, regOld is passed zero and regNew is passed the
81746 ** first register of an array of (pTab->nCol+1) registers containing the new
81747 ** row data.
81748 **
81749 ** For an UPDATE operation, this function is called twice. Once before
81750 ** the original record is deleted from the table using the calling convention
81751 ** described for DELETE. Then again after the original record is deleted
81752 ** but before the new record is inserted using the INSERT convention. 
81753 */
81754 SQLITE_PRIVATE void sqlite3FkCheck(
81755   Parse *pParse,                  /* Parse context */
81756   Table *pTab,                    /* Row is being deleted from this table */ 
81757   int regOld,                     /* Previous row data is stored here */
81758   int regNew                      /* New row data is stored here */
81759 ){
81760   sqlite3 *db = pParse->db;       /* Database handle */
81761   Vdbe *v;                        /* VM to write code to */
81762   FKey *pFKey;                    /* Used to iterate through FKs */
81763   int iDb;                        /* Index of database containing pTab */
81764   const char *zDb;                /* Name of database containing pTab */
81765   int isIgnoreErrors = pParse->disableTriggers;
81766
81767   /* Exactly one of regOld and regNew should be non-zero. */
81768   assert( (regOld==0)!=(regNew==0) );
81769
81770   /* If foreign-keys are disabled, this function is a no-op. */
81771   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
81772
81773   v = sqlite3GetVdbe(pParse);
81774   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81775   zDb = db->aDb[iDb].zName;
81776
81777   /* Loop through all the foreign key constraints for which pTab is the
81778   ** child table (the table that the foreign key definition is part of).  */
81779   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
81780     Table *pTo;                   /* Parent table of foreign key pFKey */
81781     Index *pIdx = 0;              /* Index on key columns in pTo */
81782     int *aiFree = 0;
81783     int *aiCol;
81784     int iCol;
81785     int i;
81786     int isIgnore = 0;
81787
81788     /* Find the parent table of this foreign key. Also find a unique index 
81789     ** on the parent key columns in the parent table. If either of these 
81790     ** schema items cannot be located, set an error in pParse and return 
81791     ** early.  */
81792     if( pParse->disableTriggers ){
81793       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
81794     }else{
81795       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
81796     }
81797     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
81798       if( !isIgnoreErrors || db->mallocFailed ) return;
81799       continue;
81800     }
81801     assert( pFKey->nCol==1 || (aiFree && pIdx) );
81802
81803     if( aiFree ){
81804       aiCol = aiFree;
81805     }else{
81806       iCol = pFKey->aCol[0].iFrom;
81807       aiCol = &iCol;
81808     }
81809     for(i=0; i<pFKey->nCol; i++){
81810       if( aiCol[i]==pTab->iPKey ){
81811         aiCol[i] = -1;
81812       }
81813 #ifndef SQLITE_OMIT_AUTHORIZATION
81814       /* Request permission to read the parent key columns. If the 
81815       ** authorization callback returns SQLITE_IGNORE, behave as if any
81816       ** values read from the parent table are NULL. */
81817       if( db->xAuth ){
81818         int rcauth;
81819         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
81820         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
81821         isIgnore = (rcauth==SQLITE_IGNORE);
81822       }
81823 #endif
81824     }
81825
81826     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
81827     ** a cursor to use to search the unique index on the parent key columns 
81828     ** in the parent table.  */
81829     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
81830     pParse->nTab++;
81831
81832     if( regOld!=0 ){
81833       /* A row is being removed from the child table. Search for the parent.
81834       ** If the parent does not exist, removing the child row resolves an 
81835       ** outstanding foreign key constraint violation. */
81836       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
81837     }
81838     if( regNew!=0 ){
81839       /* A row is being added to the child table. If a parent row cannot
81840       ** be found, adding the child row has violated the FK constraint. */ 
81841       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
81842     }
81843
81844     sqlite3DbFree(db, aiFree);
81845   }
81846
81847   /* Loop through all the foreign key constraints that refer to this table */
81848   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
81849     Index *pIdx = 0;              /* Foreign key index for pFKey */
81850     SrcList *pSrc;
81851     int *aiCol = 0;
81852
81853     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
81854       assert( regOld==0 && regNew!=0 );
81855       /* Inserting a single row into a parent table cannot cause an immediate
81856       ** foreign key violation. So do nothing in this case.  */
81857       continue;
81858     }
81859
81860     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
81861       if( !isIgnoreErrors || db->mallocFailed ) return;
81862       continue;
81863     }
81864     assert( aiCol || pFKey->nCol==1 );
81865
81866     /* Create a SrcList structure containing a single table (the table 
81867     ** the foreign key that refers to this table is attached to). This
81868     ** is required for the sqlite3WhereXXX() interface.  */
81869     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
81870     if( pSrc ){
81871       struct SrcList_item *pItem = pSrc->a;
81872       pItem->pTab = pFKey->pFrom;
81873       pItem->zName = pFKey->pFrom->zName;
81874       pItem->pTab->nRef++;
81875       pItem->iCursor = pParse->nTab++;
81876   
81877       if( regNew!=0 ){
81878         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
81879       }
81880       if( regOld!=0 ){
81881         /* If there is a RESTRICT action configured for the current operation
81882         ** on the parent table of this FK, then throw an exception 
81883         ** immediately if the FK constraint is violated, even if this is a
81884         ** deferred trigger. That's what RESTRICT means. To defer checking
81885         ** the constraint, the FK should specify NO ACTION (represented
81886         ** using OE_None). NO ACTION is the default.  */
81887         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
81888       }
81889       pItem->zName = 0;
81890       sqlite3SrcListDelete(db, pSrc);
81891     }
81892     sqlite3DbFree(db, aiCol);
81893   }
81894 }
81895
81896 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
81897
81898 /*
81899 ** This function is called before generating code to update or delete a 
81900 ** row contained in table pTab.
81901 */
81902 SQLITE_PRIVATE u32 sqlite3FkOldmask(
81903   Parse *pParse,                  /* Parse context */
81904   Table *pTab                     /* Table being modified */
81905 ){
81906   u32 mask = 0;
81907   if( pParse->db->flags&SQLITE_ForeignKeys ){
81908     FKey *p;
81909     int i;
81910     for(p=pTab->pFKey; p; p=p->pNextFrom){
81911       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
81912     }
81913     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
81914       Index *pIdx = 0;
81915       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
81916       if( pIdx ){
81917         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
81918       }
81919     }
81920   }
81921   return mask;
81922 }
81923
81924 /*
81925 ** This function is called before generating code to update or delete a 
81926 ** row contained in table pTab. If the operation is a DELETE, then
81927 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
81928 ** to an array of size N, where N is the number of columns in table pTab.
81929 ** If the i'th column is not modified by the UPDATE, then the corresponding 
81930 ** entry in the aChange[] array is set to -1. If the column is modified,
81931 ** the value is 0 or greater. Parameter chngRowid is set to true if the
81932 ** UPDATE statement modifies the rowid fields of the table.
81933 **
81934 ** If any foreign key processing will be required, this function returns
81935 ** true. If there is no foreign key related processing, this function 
81936 ** returns false.
81937 */
81938 SQLITE_PRIVATE int sqlite3FkRequired(
81939   Parse *pParse,                  /* Parse context */
81940   Table *pTab,                    /* Table being modified */
81941   int *aChange,                   /* Non-NULL for UPDATE operations */
81942   int chngRowid                   /* True for UPDATE that affects rowid */
81943 ){
81944   if( pParse->db->flags&SQLITE_ForeignKeys ){
81945     if( !aChange ){
81946       /* A DELETE operation. Foreign key processing is required if the 
81947       ** table in question is either the child or parent table for any 
81948       ** foreign key constraint.  */
81949       return (sqlite3FkReferences(pTab) || pTab->pFKey);
81950     }else{
81951       /* This is an UPDATE. Foreign key processing is only required if the
81952       ** operation modifies one or more child or parent key columns. */
81953       int i;
81954       FKey *p;
81955
81956       /* Check if any child key columns are being modified. */
81957       for(p=pTab->pFKey; p; p=p->pNextFrom){
81958         for(i=0; i<p->nCol; i++){
81959           int iChildKey = p->aCol[i].iFrom;
81960           if( aChange[iChildKey]>=0 ) return 1;
81961           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
81962         }
81963       }
81964
81965       /* Check if any parent key columns are being modified. */
81966       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
81967         for(i=0; i<p->nCol; i++){
81968           char *zKey = p->aCol[i].zCol;
81969           int iKey;
81970           for(iKey=0; iKey<pTab->nCol; iKey++){
81971             Column *pCol = &pTab->aCol[iKey];
81972             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
81973               if( aChange[iKey]>=0 ) return 1;
81974               if( iKey==pTab->iPKey && chngRowid ) return 1;
81975             }
81976           }
81977         }
81978       }
81979     }
81980   }
81981   return 0;
81982 }
81983
81984 /*
81985 ** This function is called when an UPDATE or DELETE operation is being 
81986 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
81987 ** If the current operation is an UPDATE, then the pChanges parameter is
81988 ** passed a pointer to the list of columns being modified. If it is a
81989 ** DELETE, pChanges is passed a NULL pointer.
81990 **
81991 ** It returns a pointer to a Trigger structure containing a trigger
81992 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
81993 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
81994 ** returned (these actions require no special handling by the triggers
81995 ** sub-system, code for them is created by fkScanChildren()).
81996 **
81997 ** For example, if pFKey is the foreign key and pTab is table "p" in 
81998 ** the following schema:
81999 **
82000 **   CREATE TABLE p(pk PRIMARY KEY);
82001 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
82002 **
82003 ** then the returned trigger structure is equivalent to:
82004 **
82005 **   CREATE TRIGGER ... DELETE ON p BEGIN
82006 **     DELETE FROM c WHERE ck = old.pk;
82007 **   END;
82008 **
82009 ** The returned pointer is cached as part of the foreign key object. It
82010 ** is eventually freed along with the rest of the foreign key object by 
82011 ** sqlite3FkDelete().
82012 */
82013 static Trigger *fkActionTrigger(
82014   Parse *pParse,                  /* Parse context */
82015   Table *pTab,                    /* Table being updated or deleted from */
82016   FKey *pFKey,                    /* Foreign key to get action for */
82017   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
82018 ){
82019   sqlite3 *db = pParse->db;       /* Database handle */
82020   int action;                     /* One of OE_None, OE_Cascade etc. */
82021   Trigger *pTrigger;              /* Trigger definition to return */
82022   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
82023
82024   action = pFKey->aAction[iAction];
82025   pTrigger = pFKey->apTrigger[iAction];
82026
82027   if( action!=OE_None && !pTrigger ){
82028     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
82029     char const *zFrom;            /* Name of child table */
82030     int nFrom;                    /* Length in bytes of zFrom */
82031     Index *pIdx = 0;              /* Parent key index for this FK */
82032     int *aiCol = 0;               /* child table cols -> parent key cols */
82033     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
82034     Expr *pWhere = 0;             /* WHERE clause of trigger step */
82035     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
82036     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
82037     int i;                        /* Iterator variable */
82038     Expr *pWhen = 0;              /* WHEN clause for the trigger */
82039
82040     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
82041     assert( aiCol || pFKey->nCol==1 );
82042
82043     for(i=0; i<pFKey->nCol; i++){
82044       Token tOld = { "old", 3 };  /* Literal "old" token */
82045       Token tNew = { "new", 3 };  /* Literal "new" token */
82046       Token tFromCol;             /* Name of column in child table */
82047       Token tToCol;               /* Name of column in parent table */
82048       int iFromCol;               /* Idx of column in child table */
82049       Expr *pEq;                  /* tFromCol = OLD.tToCol */
82050
82051       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
82052       assert( iFromCol>=0 );
82053       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
82054       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
82055
82056       tToCol.n = sqlite3Strlen30(tToCol.z);
82057       tFromCol.n = sqlite3Strlen30(tFromCol.z);
82058
82059       /* Create the expression "OLD.zToCol = zFromCol". It is important
82060       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
82061       ** that the affinity and collation sequence associated with the
82062       ** parent table are used for the comparison. */
82063       pEq = sqlite3PExpr(pParse, TK_EQ,
82064           sqlite3PExpr(pParse, TK_DOT, 
82065             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
82066             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
82067           , 0),
82068           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
82069       , 0);
82070       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
82071
82072       /* For ON UPDATE, construct the next term of the WHEN clause.
82073       ** The final WHEN clause will be like this:
82074       **
82075       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
82076       */
82077       if( pChanges ){
82078         pEq = sqlite3PExpr(pParse, TK_IS,
82079             sqlite3PExpr(pParse, TK_DOT, 
82080               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
82081               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
82082               0),
82083             sqlite3PExpr(pParse, TK_DOT, 
82084               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
82085               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
82086               0),
82087             0);
82088         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
82089       }
82090   
82091       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
82092         Expr *pNew;
82093         if( action==OE_Cascade ){
82094           pNew = sqlite3PExpr(pParse, TK_DOT, 
82095             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
82096             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
82097           , 0);
82098         }else if( action==OE_SetDflt ){
82099           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
82100           if( pDflt ){
82101             pNew = sqlite3ExprDup(db, pDflt, 0);
82102           }else{
82103             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
82104           }
82105         }else{
82106           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
82107         }
82108         pList = sqlite3ExprListAppend(pParse, pList, pNew);
82109         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
82110       }
82111     }
82112     sqlite3DbFree(db, aiCol);
82113
82114     zFrom = pFKey->pFrom->zName;
82115     nFrom = sqlite3Strlen30(zFrom);
82116
82117     if( action==OE_Restrict ){
82118       Token tFrom;
82119       Expr *pRaise; 
82120
82121       tFrom.z = zFrom;
82122       tFrom.n = nFrom;
82123       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
82124       if( pRaise ){
82125         pRaise->affinity = OE_Abort;
82126       }
82127       pSelect = sqlite3SelectNew(pParse, 
82128           sqlite3ExprListAppend(pParse, 0, pRaise),
82129           sqlite3SrcListAppend(db, 0, &tFrom, 0),
82130           pWhere,
82131           0, 0, 0, 0, 0, 0
82132       );
82133       pWhere = 0;
82134     }
82135
82136     /* Disable lookaside memory allocation */
82137     enableLookaside = db->lookaside.bEnabled;
82138     db->lookaside.bEnabled = 0;
82139
82140     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
82141         sizeof(Trigger) +         /* struct Trigger */
82142         sizeof(TriggerStep) +     /* Single step in trigger program */
82143         nFrom + 1                 /* Space for pStep->target.z */
82144     );
82145     if( pTrigger ){
82146       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
82147       pStep->target.z = (char *)&pStep[1];
82148       pStep->target.n = nFrom;
82149       memcpy((char *)pStep->target.z, zFrom, nFrom);
82150   
82151       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
82152       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
82153       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
82154       if( pWhen ){
82155         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
82156         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
82157       }
82158     }
82159
82160     /* Re-enable the lookaside buffer, if it was disabled earlier. */
82161     db->lookaside.bEnabled = enableLookaside;
82162
82163     sqlite3ExprDelete(db, pWhere);
82164     sqlite3ExprDelete(db, pWhen);
82165     sqlite3ExprListDelete(db, pList);
82166     sqlite3SelectDelete(db, pSelect);
82167     if( db->mallocFailed==1 ){
82168       fkTriggerDelete(db, pTrigger);
82169       return 0;
82170     }
82171
82172     switch( action ){
82173       case OE_Restrict:
82174         pStep->op = TK_SELECT; 
82175         break;
82176       case OE_Cascade: 
82177         if( !pChanges ){ 
82178           pStep->op = TK_DELETE; 
82179           break; 
82180         }
82181       default:
82182         pStep->op = TK_UPDATE;
82183     }
82184     pStep->pTrig = pTrigger;
82185     pTrigger->pSchema = pTab->pSchema;
82186     pTrigger->pTabSchema = pTab->pSchema;
82187     pFKey->apTrigger[iAction] = pTrigger;
82188     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
82189   }
82190
82191   return pTrigger;
82192 }
82193
82194 /*
82195 ** This function is called when deleting or updating a row to implement
82196 ** any required CASCADE, SET NULL or SET DEFAULT actions.
82197 */
82198 SQLITE_PRIVATE void sqlite3FkActions(
82199   Parse *pParse,                  /* Parse context */
82200   Table *pTab,                    /* Table being updated or deleted from */
82201   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
82202   int regOld                      /* Address of array containing old row */
82203 ){
82204   /* If foreign-key support is enabled, iterate through all FKs that 
82205   ** refer to table pTab. If there is an action associated with the FK 
82206   ** for this operation (either update or delete), invoke the associated 
82207   ** trigger sub-program.  */
82208   if( pParse->db->flags&SQLITE_ForeignKeys ){
82209     FKey *pFKey;                  /* Iterator variable */
82210     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
82211       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
82212       if( pAction ){
82213         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
82214       }
82215     }
82216   }
82217 }
82218
82219 #endif /* ifndef SQLITE_OMIT_TRIGGER */
82220
82221 /*
82222 ** Free all memory associated with foreign key definitions attached to
82223 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
82224 ** hash table.
82225 */
82226 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
82227   FKey *pFKey;                    /* Iterator variable */
82228   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
82229
82230   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
82231
82232     /* Remove the FK from the fkeyHash hash table. */
82233     if( !db || db->pnBytesFreed==0 ){
82234       if( pFKey->pPrevTo ){
82235         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
82236       }else{
82237         void *p = (void *)pFKey->pNextTo;
82238         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
82239         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
82240       }
82241       if( pFKey->pNextTo ){
82242         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
82243       }
82244     }
82245
82246     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
82247     ** classified as either immediate or deferred.
82248     */
82249     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
82250
82251     /* Delete any triggers created to implement actions for this FK. */
82252 #ifndef SQLITE_OMIT_TRIGGER
82253     fkTriggerDelete(db, pFKey->apTrigger[0]);
82254     fkTriggerDelete(db, pFKey->apTrigger[1]);
82255 #endif
82256
82257     pNext = pFKey->pNextFrom;
82258     sqlite3DbFree(db, pFKey);
82259   }
82260 }
82261 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
82262
82263 /************** End of fkey.c ************************************************/
82264 /************** Begin file insert.c ******************************************/
82265 /*
82266 ** 2001 September 15
82267 **
82268 ** The author disclaims copyright to this source code.  In place of
82269 ** a legal notice, here is a blessing:
82270 **
82271 **    May you do good and not evil.
82272 **    May you find forgiveness for yourself and forgive others.
82273 **    May you share freely, never taking more than you give.
82274 **
82275 *************************************************************************
82276 ** This file contains C code routines that are called by the parser
82277 ** to handle INSERT statements in SQLite.
82278 */
82279
82280 /*
82281 ** Generate code that will open a table for reading.
82282 */
82283 SQLITE_PRIVATE void sqlite3OpenTable(
82284   Parse *p,       /* Generate code into this VDBE */
82285   int iCur,       /* The cursor number of the table */
82286   int iDb,        /* The database index in sqlite3.aDb[] */
82287   Table *pTab,    /* The table to be opened */
82288   int opcode      /* OP_OpenRead or OP_OpenWrite */
82289 ){
82290   Vdbe *v;
82291   if( IsVirtual(pTab) ) return;
82292   v = sqlite3GetVdbe(p);
82293   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
82294   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
82295   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
82296   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
82297   VdbeComment((v, "%s", pTab->zName));
82298 }
82299
82300 /*
82301 ** Return a pointer to the column affinity string associated with index
82302 ** pIdx. A column affinity string has one character for each column in 
82303 ** the table, according to the affinity of the column:
82304 **
82305 **  Character      Column affinity
82306 **  ------------------------------
82307 **  'a'            TEXT
82308 **  'b'            NONE
82309 **  'c'            NUMERIC
82310 **  'd'            INTEGER
82311 **  'e'            REAL
82312 **
82313 ** An extra 'b' is appended to the end of the string to cover the
82314 ** rowid that appears as the last column in every index.
82315 **
82316 ** Memory for the buffer containing the column index affinity string
82317 ** is managed along with the rest of the Index structure. It will be
82318 ** released when sqlite3DeleteIndex() is called.
82319 */
82320 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
82321   if( !pIdx->zColAff ){
82322     /* The first time a column affinity string for a particular index is
82323     ** required, it is allocated and populated here. It is then stored as
82324     ** a member of the Index structure for subsequent use.
82325     **
82326     ** The column affinity string will eventually be deleted by
82327     ** sqliteDeleteIndex() when the Index structure itself is cleaned
82328     ** up.
82329     */
82330     int n;
82331     Table *pTab = pIdx->pTable;
82332     sqlite3 *db = sqlite3VdbeDb(v);
82333     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
82334     if( !pIdx->zColAff ){
82335       db->mallocFailed = 1;
82336       return 0;
82337     }
82338     for(n=0; n<pIdx->nColumn; n++){
82339       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
82340     }
82341     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
82342     pIdx->zColAff[n] = 0;
82343   }
82344  
82345   return pIdx->zColAff;
82346 }
82347
82348 /*
82349 ** Set P4 of the most recently inserted opcode to a column affinity
82350 ** string for table pTab. A column affinity string has one character
82351 ** for each column indexed by the index, according to the affinity of the
82352 ** column:
82353 **
82354 **  Character      Column affinity
82355 **  ------------------------------
82356 **  'a'            TEXT
82357 **  'b'            NONE
82358 **  'c'            NUMERIC
82359 **  'd'            INTEGER
82360 **  'e'            REAL
82361 */
82362 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
82363   /* The first time a column affinity string for a particular table
82364   ** is required, it is allocated and populated here. It is then 
82365   ** stored as a member of the Table structure for subsequent use.
82366   **
82367   ** The column affinity string will eventually be deleted by
82368   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
82369   */
82370   if( !pTab->zColAff ){
82371     char *zColAff;
82372     int i;
82373     sqlite3 *db = sqlite3VdbeDb(v);
82374
82375     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
82376     if( !zColAff ){
82377       db->mallocFailed = 1;
82378       return;
82379     }
82380
82381     for(i=0; i<pTab->nCol; i++){
82382       zColAff[i] = pTab->aCol[i].affinity;
82383     }
82384     zColAff[pTab->nCol] = '\0';
82385
82386     pTab->zColAff = zColAff;
82387   }
82388
82389   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
82390 }
82391
82392 /*
82393 ** Return non-zero if the table pTab in database iDb or any of its indices
82394 ** have been opened at any point in the VDBE program beginning at location
82395 ** iStartAddr throught the end of the program.  This is used to see if 
82396 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
82397 ** run without using temporary table for the results of the SELECT. 
82398 */
82399 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
82400   Vdbe *v = sqlite3GetVdbe(p);
82401   int i;
82402   int iEnd = sqlite3VdbeCurrentAddr(v);
82403 #ifndef SQLITE_OMIT_VIRTUALTABLE
82404   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
82405 #endif
82406
82407   for(i=iStartAddr; i<iEnd; i++){
82408     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
82409     assert( pOp!=0 );
82410     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
82411       Index *pIndex;
82412       int tnum = pOp->p2;
82413       if( tnum==pTab->tnum ){
82414         return 1;
82415       }
82416       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
82417         if( tnum==pIndex->tnum ){
82418           return 1;
82419         }
82420       }
82421     }
82422 #ifndef SQLITE_OMIT_VIRTUALTABLE
82423     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
82424       assert( pOp->p4.pVtab!=0 );
82425       assert( pOp->p4type==P4_VTAB );
82426       return 1;
82427     }
82428 #endif
82429   }
82430   return 0;
82431 }
82432
82433 #ifndef SQLITE_OMIT_AUTOINCREMENT
82434 /*
82435 ** Locate or create an AutoincInfo structure associated with table pTab
82436 ** which is in database iDb.  Return the register number for the register
82437 ** that holds the maximum rowid.
82438 **
82439 ** There is at most one AutoincInfo structure per table even if the
82440 ** same table is autoincremented multiple times due to inserts within
82441 ** triggers.  A new AutoincInfo structure is created if this is the
82442 ** first use of table pTab.  On 2nd and subsequent uses, the original
82443 ** AutoincInfo structure is used.
82444 **
82445 ** Three memory locations are allocated:
82446 **
82447 **   (1)  Register to hold the name of the pTab table.
82448 **   (2)  Register to hold the maximum ROWID of pTab.
82449 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
82450 **
82451 ** The 2nd register is the one that is returned.  That is all the
82452 ** insert routine needs to know about.
82453 */
82454 static int autoIncBegin(
82455   Parse *pParse,      /* Parsing context */
82456   int iDb,            /* Index of the database holding pTab */
82457   Table *pTab         /* The table we are writing to */
82458 ){
82459   int memId = 0;      /* Register holding maximum rowid */
82460   if( pTab->tabFlags & TF_Autoincrement ){
82461     Parse *pToplevel = sqlite3ParseToplevel(pParse);
82462     AutoincInfo *pInfo;
82463
82464     pInfo = pToplevel->pAinc;
82465     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
82466     if( pInfo==0 ){
82467       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
82468       if( pInfo==0 ) return 0;
82469       pInfo->pNext = pToplevel->pAinc;
82470       pToplevel->pAinc = pInfo;
82471       pInfo->pTab = pTab;
82472       pInfo->iDb = iDb;
82473       pToplevel->nMem++;                  /* Register to hold name of table */
82474       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
82475       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
82476     }
82477     memId = pInfo->regCtr;
82478   }
82479   return memId;
82480 }
82481
82482 /*
82483 ** This routine generates code that will initialize all of the
82484 ** register used by the autoincrement tracker.  
82485 */
82486 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
82487   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
82488   sqlite3 *db = pParse->db;  /* The database connection */
82489   Db *pDb;                   /* Database only autoinc table */
82490   int memId;                 /* Register holding max rowid */
82491   int addr;                  /* A VDBE address */
82492   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
82493
82494   /* This routine is never called during trigger-generation.  It is
82495   ** only called from the top-level */
82496   assert( pParse->pTriggerTab==0 );
82497   assert( pParse==sqlite3ParseToplevel(pParse) );
82498
82499   assert( v );   /* We failed long ago if this is not so */
82500   for(p = pParse->pAinc; p; p = p->pNext){
82501     pDb = &db->aDb[p->iDb];
82502     memId = p->regCtr;
82503     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
82504     addr = sqlite3VdbeCurrentAddr(v);
82505     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
82506     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
82507     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
82508     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
82509     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
82510     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
82511     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
82512     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
82513     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
82514     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
82515     sqlite3VdbeAddOp0(v, OP_Close);
82516   }
82517 }
82518
82519 /*
82520 ** Update the maximum rowid for an autoincrement calculation.
82521 **
82522 ** This routine should be called when the top of the stack holds a
82523 ** new rowid that is about to be inserted.  If that new rowid is
82524 ** larger than the maximum rowid in the memId memory cell, then the
82525 ** memory cell is updated.  The stack is unchanged.
82526 */
82527 static void autoIncStep(Parse *pParse, int memId, int regRowid){
82528   if( memId>0 ){
82529     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
82530   }
82531 }
82532
82533 /*
82534 ** This routine generates the code needed to write autoincrement
82535 ** maximum rowid values back into the sqlite_sequence register.
82536 ** Every statement that might do an INSERT into an autoincrement
82537 ** table (either directly or through triggers) needs to call this
82538 ** routine just before the "exit" code.
82539 */
82540 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
82541   AutoincInfo *p;
82542   Vdbe *v = pParse->pVdbe;
82543   sqlite3 *db = pParse->db;
82544
82545   assert( v );
82546   for(p = pParse->pAinc; p; p = p->pNext){
82547     Db *pDb = &db->aDb[p->iDb];
82548     int j1, j2, j3, j4, j5;
82549     int iRec;
82550     int memId = p->regCtr;
82551
82552     iRec = sqlite3GetTempReg(pParse);
82553     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
82554     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
82555     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
82556     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
82557     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
82558     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
82559     sqlite3VdbeJumpHere(v, j2);
82560     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
82561     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
82562     sqlite3VdbeJumpHere(v, j4);
82563     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
82564     sqlite3VdbeJumpHere(v, j1);
82565     sqlite3VdbeJumpHere(v, j5);
82566     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
82567     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
82568     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
82569     sqlite3VdbeAddOp0(v, OP_Close);
82570     sqlite3ReleaseTempReg(pParse, iRec);
82571   }
82572 }
82573 #else
82574 /*
82575 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
82576 ** above are all no-ops
82577 */
82578 # define autoIncBegin(A,B,C) (0)
82579 # define autoIncStep(A,B,C)
82580 #endif /* SQLITE_OMIT_AUTOINCREMENT */
82581
82582
82583 /* Forward declaration */
82584 static int xferOptimization(
82585   Parse *pParse,        /* Parser context */
82586   Table *pDest,         /* The table we are inserting into */
82587   Select *pSelect,      /* A SELECT statement to use as the data source */
82588   int onError,          /* How to handle constraint errors */
82589   int iDbDest           /* The database of pDest */
82590 );
82591
82592 /*
82593 ** This routine is call to handle SQL of the following forms:
82594 **
82595 **    insert into TABLE (IDLIST) values(EXPRLIST)
82596 **    insert into TABLE (IDLIST) select
82597 **
82598 ** The IDLIST following the table name is always optional.  If omitted,
82599 ** then a list of all columns for the table is substituted.  The IDLIST
82600 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
82601 **
82602 ** The pList parameter holds EXPRLIST in the first form of the INSERT
82603 ** statement above, and pSelect is NULL.  For the second form, pList is
82604 ** NULL and pSelect is a pointer to the select statement used to generate
82605 ** data for the insert.
82606 **
82607 ** The code generated follows one of four templates.  For a simple
82608 ** select with data coming from a VALUES clause, the code executes
82609 ** once straight down through.  Pseudo-code follows (we call this
82610 ** the "1st template"):
82611 **
82612 **         open write cursor to <table> and its indices
82613 **         puts VALUES clause expressions onto the stack
82614 **         write the resulting record into <table>
82615 **         cleanup
82616 **
82617 ** The three remaining templates assume the statement is of the form
82618 **
82619 **   INSERT INTO <table> SELECT ...
82620 **
82621 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
82622 ** in other words if the SELECT pulls all columns from a single table
82623 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
82624 ** if <table2> and <table1> are distinct tables but have identical
82625 ** schemas, including all the same indices, then a special optimization
82626 ** is invoked that copies raw records from <table2> over to <table1>.
82627 ** See the xferOptimization() function for the implementation of this
82628 ** template.  This is the 2nd template.
82629 **
82630 **         open a write cursor to <table>
82631 **         open read cursor on <table2>
82632 **         transfer all records in <table2> over to <table>
82633 **         close cursors
82634 **         foreach index on <table>
82635 **           open a write cursor on the <table> index
82636 **           open a read cursor on the corresponding <table2> index
82637 **           transfer all records from the read to the write cursors
82638 **           close cursors
82639 **         end foreach
82640 **
82641 ** The 3rd template is for when the second template does not apply
82642 ** and the SELECT clause does not read from <table> at any time.
82643 ** The generated code follows this template:
82644 **
82645 **         EOF <- 0
82646 **         X <- A
82647 **         goto B
82648 **      A: setup for the SELECT
82649 **         loop over the rows in the SELECT
82650 **           load values into registers R..R+n
82651 **           yield X
82652 **         end loop
82653 **         cleanup after the SELECT
82654 **         EOF <- 1
82655 **         yield X
82656 **         goto A
82657 **      B: open write cursor to <table> and its indices
82658 **      C: yield X
82659 **         if EOF goto D
82660 **         insert the select result into <table> from R..R+n
82661 **         goto C
82662 **      D: cleanup
82663 **
82664 ** The 4th template is used if the insert statement takes its
82665 ** values from a SELECT but the data is being inserted into a table
82666 ** that is also read as part of the SELECT.  In the third form,
82667 ** we have to use a intermediate table to store the results of
82668 ** the select.  The template is like this:
82669 **
82670 **         EOF <- 0
82671 **         X <- A
82672 **         goto B
82673 **      A: setup for the SELECT
82674 **         loop over the tables in the SELECT
82675 **           load value into register R..R+n
82676 **           yield X
82677 **         end loop
82678 **         cleanup after the SELECT
82679 **         EOF <- 1
82680 **         yield X
82681 **         halt-error
82682 **      B: open temp table
82683 **      L: yield X
82684 **         if EOF goto M
82685 **         insert row from R..R+n into temp table
82686 **         goto L
82687 **      M: open write cursor to <table> and its indices
82688 **         rewind temp table
82689 **      C: loop over rows of intermediate table
82690 **           transfer values form intermediate table into <table>
82691 **         end loop
82692 **      D: cleanup
82693 */
82694 SQLITE_PRIVATE void sqlite3Insert(
82695   Parse *pParse,        /* Parser context */
82696   SrcList *pTabList,    /* Name of table into which we are inserting */
82697   ExprList *pList,      /* List of values to be inserted */
82698   Select *pSelect,      /* A SELECT statement to use as the data source */
82699   IdList *pColumn,      /* Column names corresponding to IDLIST. */
82700   int onError           /* How to handle constraint errors */
82701 ){
82702   sqlite3 *db;          /* The main database structure */
82703   Table *pTab;          /* The table to insert into.  aka TABLE */
82704   char *zTab;           /* Name of the table into which we are inserting */
82705   const char *zDb;      /* Name of the database holding this table */
82706   int i, j, idx;        /* Loop counters */
82707   Vdbe *v;              /* Generate code into this virtual machine */
82708   Index *pIdx;          /* For looping over indices of the table */
82709   int nColumn;          /* Number of columns in the data */
82710   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
82711   int baseCur = 0;      /* VDBE Cursor number for pTab */
82712   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
82713   int endOfLoop;        /* Label for the end of the insertion loop */
82714   int useTempTable = 0; /* Store SELECT results in intermediate table */
82715   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
82716   int addrInsTop = 0;   /* Jump to label "D" */
82717   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
82718   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
82719   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
82720   int iDb;              /* Index of database holding TABLE */
82721   Db *pDb;              /* The database containing table being inserted into */
82722   int appendFlag = 0;   /* True if the insert is likely to be an append */
82723
82724   /* Register allocations */
82725   int regFromSelect = 0;/* Base register for data coming from SELECT */
82726   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
82727   int regRowCount = 0;  /* Memory cell used for the row counter */
82728   int regIns;           /* Block of regs holding rowid+data being inserted */
82729   int regRowid;         /* registers holding insert rowid */
82730   int regData;          /* register holding first column to insert */
82731   int regRecord;        /* Holds the assemblied row record */
82732   int regEof = 0;       /* Register recording end of SELECT data */
82733   int *aRegIdx = 0;     /* One register allocated to each index */
82734
82735 #ifndef SQLITE_OMIT_TRIGGER
82736   int isView;                 /* True if attempting to insert into a view */
82737   Trigger *pTrigger;          /* List of triggers on pTab, if required */
82738   int tmask;                  /* Mask of trigger times */
82739 #endif
82740
82741   db = pParse->db;
82742   memset(&dest, 0, sizeof(dest));
82743   if( pParse->nErr || db->mallocFailed ){
82744     goto insert_cleanup;
82745   }
82746
82747   /* Locate the table into which we will be inserting new information.
82748   */
82749   assert( pTabList->nSrc==1 );
82750   zTab = pTabList->a[0].zName;
82751   if( NEVER(zTab==0) ) goto insert_cleanup;
82752   pTab = sqlite3SrcListLookup(pParse, pTabList);
82753   if( pTab==0 ){
82754     goto insert_cleanup;
82755   }
82756   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82757   assert( iDb<db->nDb );
82758   pDb = &db->aDb[iDb];
82759   zDb = pDb->zName;
82760   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
82761     goto insert_cleanup;
82762   }
82763
82764   /* Figure out if we have any triggers and if the table being
82765   ** inserted into is a view
82766   */
82767 #ifndef SQLITE_OMIT_TRIGGER
82768   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
82769   isView = pTab->pSelect!=0;
82770 #else
82771 # define pTrigger 0
82772 # define tmask 0
82773 # define isView 0
82774 #endif
82775 #ifdef SQLITE_OMIT_VIEW
82776 # undef isView
82777 # define isView 0
82778 #endif
82779   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
82780
82781   /* If pTab is really a view, make sure it has been initialized.
82782   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
82783   ** module table).
82784   */
82785   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
82786     goto insert_cleanup;
82787   }
82788
82789   /* Ensure that:
82790   *  (a) the table is not read-only, 
82791   *  (b) that if it is a view then ON INSERT triggers exist
82792   */
82793   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
82794     goto insert_cleanup;
82795   }
82796
82797   /* Allocate a VDBE
82798   */
82799   v = sqlite3GetVdbe(pParse);
82800   if( v==0 ) goto insert_cleanup;
82801   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
82802   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
82803
82804 #ifndef SQLITE_OMIT_XFER_OPT
82805   /* If the statement is of the form
82806   **
82807   **       INSERT INTO <table1> SELECT * FROM <table2>;
82808   **
82809   ** Then special optimizations can be applied that make the transfer
82810   ** very fast and which reduce fragmentation of indices.
82811   **
82812   ** This is the 2nd template.
82813   */
82814   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
82815     assert( !pTrigger );
82816     assert( pList==0 );
82817     goto insert_end;
82818   }
82819 #endif /* SQLITE_OMIT_XFER_OPT */
82820
82821   /* If this is an AUTOINCREMENT table, look up the sequence number in the
82822   ** sqlite_sequence table and store it in memory cell regAutoinc.
82823   */
82824   regAutoinc = autoIncBegin(pParse, iDb, pTab);
82825
82826   /* Figure out how many columns of data are supplied.  If the data
82827   ** is coming from a SELECT statement, then generate a co-routine that
82828   ** produces a single row of the SELECT on each invocation.  The
82829   ** co-routine is the common header to the 3rd and 4th templates.
82830   */
82831   if( pSelect ){
82832     /* Data is coming from a SELECT.  Generate code to implement that SELECT
82833     ** as a co-routine.  The code is common to both the 3rd and 4th
82834     ** templates:
82835     **
82836     **         EOF <- 0
82837     **         X <- A
82838     **         goto B
82839     **      A: setup for the SELECT
82840     **         loop over the tables in the SELECT
82841     **           load value into register R..R+n
82842     **           yield X
82843     **         end loop
82844     **         cleanup after the SELECT
82845     **         EOF <- 1
82846     **         yield X
82847     **         halt-error
82848     **
82849     ** On each invocation of the co-routine, it puts a single row of the
82850     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
82851     ** (These output registers are allocated by sqlite3Select().)  When
82852     ** the SELECT completes, it sets the EOF flag stored in regEof.
82853     */
82854     int rc, j1;
82855
82856     regEof = ++pParse->nMem;
82857     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
82858     VdbeComment((v, "SELECT eof flag"));
82859     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
82860     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
82861     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
82862     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
82863     VdbeComment((v, "Jump over SELECT coroutine"));
82864
82865     /* Resolve the expressions in the SELECT statement and execute it. */
82866     rc = sqlite3Select(pParse, pSelect, &dest);
82867     assert( pParse->nErr==0 || rc );
82868     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
82869       goto insert_cleanup;
82870     }
82871     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
82872     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
82873     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
82874     VdbeComment((v, "End of SELECT coroutine"));
82875     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
82876
82877     regFromSelect = dest.iMem;
82878     assert( pSelect->pEList );
82879     nColumn = pSelect->pEList->nExpr;
82880     assert( dest.nMem==nColumn );
82881
82882     /* Set useTempTable to TRUE if the result of the SELECT statement
82883     ** should be written into a temporary table (template 4).  Set to
82884     ** FALSE if each* row of the SELECT can be written directly into
82885     ** the destination table (template 3).
82886     **
82887     ** A temp table must be used if the table being updated is also one
82888     ** of the tables being read by the SELECT statement.  Also use a 
82889     ** temp table in the case of row triggers.
82890     */
82891     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
82892       useTempTable = 1;
82893     }
82894
82895     if( useTempTable ){
82896       /* Invoke the coroutine to extract information from the SELECT
82897       ** and add it to a transient table srcTab.  The code generated
82898       ** here is from the 4th template:
82899       **
82900       **      B: open temp table
82901       **      L: yield X
82902       **         if EOF goto M
82903       **         insert row from R..R+n into temp table
82904       **         goto L
82905       **      M: ...
82906       */
82907       int regRec;          /* Register to hold packed record */
82908       int regTempRowid;    /* Register to hold temp table ROWID */
82909       int addrTop;         /* Label "L" */
82910       int addrIf;          /* Address of jump to M */
82911
82912       srcTab = pParse->nTab++;
82913       regRec = sqlite3GetTempReg(pParse);
82914       regTempRowid = sqlite3GetTempReg(pParse);
82915       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
82916       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
82917       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
82918       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
82919       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
82920       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
82921       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
82922       sqlite3VdbeJumpHere(v, addrIf);
82923       sqlite3ReleaseTempReg(pParse, regRec);
82924       sqlite3ReleaseTempReg(pParse, regTempRowid);
82925     }
82926   }else{
82927     /* This is the case if the data for the INSERT is coming from a VALUES
82928     ** clause
82929     */
82930     NameContext sNC;
82931     memset(&sNC, 0, sizeof(sNC));
82932     sNC.pParse = pParse;
82933     srcTab = -1;
82934     assert( useTempTable==0 );
82935     nColumn = pList ? pList->nExpr : 0;
82936     for(i=0; i<nColumn; i++){
82937       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
82938         goto insert_cleanup;
82939       }
82940     }
82941   }
82942
82943   /* Make sure the number of columns in the source data matches the number
82944   ** of columns to be inserted into the table.
82945   */
82946   if( IsVirtual(pTab) ){
82947     for(i=0; i<pTab->nCol; i++){
82948       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
82949     }
82950   }
82951   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
82952     sqlite3ErrorMsg(pParse, 
82953        "table %S has %d columns but %d values were supplied",
82954        pTabList, 0, pTab->nCol-nHidden, nColumn);
82955     goto insert_cleanup;
82956   }
82957   if( pColumn!=0 && nColumn!=pColumn->nId ){
82958     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
82959     goto insert_cleanup;
82960   }
82961
82962   /* If the INSERT statement included an IDLIST term, then make sure
82963   ** all elements of the IDLIST really are columns of the table and 
82964   ** remember the column indices.
82965   **
82966   ** If the table has an INTEGER PRIMARY KEY column and that column
82967   ** is named in the IDLIST, then record in the keyColumn variable
82968   ** the index into IDLIST of the primary key column.  keyColumn is
82969   ** the index of the primary key as it appears in IDLIST, not as
82970   ** is appears in the original table.  (The index of the primary
82971   ** key in the original table is pTab->iPKey.)
82972   */
82973   if( pColumn ){
82974     for(i=0; i<pColumn->nId; i++){
82975       pColumn->a[i].idx = -1;
82976     }
82977     for(i=0; i<pColumn->nId; i++){
82978       for(j=0; j<pTab->nCol; j++){
82979         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
82980           pColumn->a[i].idx = j;
82981           if( j==pTab->iPKey ){
82982             keyColumn = i;
82983           }
82984           break;
82985         }
82986       }
82987       if( j>=pTab->nCol ){
82988         if( sqlite3IsRowid(pColumn->a[i].zName) ){
82989           keyColumn = i;
82990         }else{
82991           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
82992               pTabList, 0, pColumn->a[i].zName);
82993           pParse->checkSchema = 1;
82994           goto insert_cleanup;
82995         }
82996       }
82997     }
82998   }
82999
83000   /* If there is no IDLIST term but the table has an integer primary
83001   ** key, the set the keyColumn variable to the primary key column index
83002   ** in the original table definition.
83003   */
83004   if( pColumn==0 && nColumn>0 ){
83005     keyColumn = pTab->iPKey;
83006   }
83007     
83008   /* Initialize the count of rows to be inserted
83009   */
83010   if( db->flags & SQLITE_CountRows ){
83011     regRowCount = ++pParse->nMem;
83012     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
83013   }
83014
83015   /* If this is not a view, open the table and and all indices */
83016   if( !isView ){
83017     int nIdx;
83018
83019     baseCur = pParse->nTab;
83020     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
83021     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
83022     if( aRegIdx==0 ){
83023       goto insert_cleanup;
83024     }
83025     for(i=0; i<nIdx; i++){
83026       aRegIdx[i] = ++pParse->nMem;
83027     }
83028   }
83029
83030   /* This is the top of the main insertion loop */
83031   if( useTempTable ){
83032     /* This block codes the top of loop only.  The complete loop is the
83033     ** following pseudocode (template 4):
83034     **
83035     **         rewind temp table
83036     **      C: loop over rows of intermediate table
83037     **           transfer values form intermediate table into <table>
83038     **         end loop
83039     **      D: ...
83040     */
83041     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
83042     addrCont = sqlite3VdbeCurrentAddr(v);
83043   }else if( pSelect ){
83044     /* This block codes the top of loop only.  The complete loop is the
83045     ** following pseudocode (template 3):
83046     **
83047     **      C: yield X
83048     **         if EOF goto D
83049     **         insert the select result into <table> from R..R+n
83050     **         goto C
83051     **      D: ...
83052     */
83053     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
83054     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
83055   }
83056
83057   /* Allocate registers for holding the rowid of the new row,
83058   ** the content of the new row, and the assemblied row record.
83059   */
83060   regRecord = ++pParse->nMem;
83061   regRowid = regIns = pParse->nMem+1;
83062   pParse->nMem += pTab->nCol + 1;
83063   if( IsVirtual(pTab) ){
83064     regRowid++;
83065     pParse->nMem++;
83066   }
83067   regData = regRowid+1;
83068
83069   /* Run the BEFORE and INSTEAD OF triggers, if there are any
83070   */
83071   endOfLoop = sqlite3VdbeMakeLabel(v);
83072   if( tmask & TRIGGER_BEFORE ){
83073     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
83074
83075     /* build the NEW.* reference row.  Note that if there is an INTEGER
83076     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
83077     ** translated into a unique ID for the row.  But on a BEFORE trigger,
83078     ** we do not know what the unique ID will be (because the insert has
83079     ** not happened yet) so we substitute a rowid of -1
83080     */
83081     if( keyColumn<0 ){
83082       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
83083     }else{
83084       int j1;
83085       if( useTempTable ){
83086         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
83087       }else{
83088         assert( pSelect==0 );  /* Otherwise useTempTable is true */
83089         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
83090       }
83091       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
83092       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
83093       sqlite3VdbeJumpHere(v, j1);
83094       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
83095     }
83096
83097     /* Cannot have triggers on a virtual table. If it were possible,
83098     ** this block would have to account for hidden column.
83099     */
83100     assert( !IsVirtual(pTab) );
83101
83102     /* Create the new column data
83103     */
83104     for(i=0; i<pTab->nCol; i++){
83105       if( pColumn==0 ){
83106         j = i;
83107       }else{
83108         for(j=0; j<pColumn->nId; j++){
83109           if( pColumn->a[j].idx==i ) break;
83110         }
83111       }
83112       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
83113         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
83114       }else if( useTempTable ){
83115         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
83116       }else{
83117         assert( pSelect==0 ); /* Otherwise useTempTable is true */
83118         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
83119       }
83120     }
83121
83122     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
83123     ** do not attempt any conversions before assembling the record.
83124     ** If this is a real table, attempt conversions as required by the
83125     ** table column affinities.
83126     */
83127     if( !isView ){
83128       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
83129       sqlite3TableAffinityStr(v, pTab);
83130     }
83131
83132     /* Fire BEFORE or INSTEAD OF triggers */
83133     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
83134         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
83135
83136     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
83137   }
83138
83139   /* Push the record number for the new entry onto the stack.  The
83140   ** record number is a randomly generate integer created by NewRowid
83141   ** except when the table has an INTEGER PRIMARY KEY column, in which
83142   ** case the record number is the same as that column. 
83143   */
83144   if( !isView ){
83145     if( IsVirtual(pTab) ){
83146       /* The row that the VUpdate opcode will delete: none */
83147       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
83148     }
83149     if( keyColumn>=0 ){
83150       if( useTempTable ){
83151         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
83152       }else if( pSelect ){
83153         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
83154       }else{
83155         VdbeOp *pOp;
83156         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
83157         pOp = sqlite3VdbeGetOp(v, -1);
83158         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
83159           appendFlag = 1;
83160           pOp->opcode = OP_NewRowid;
83161           pOp->p1 = baseCur;
83162           pOp->p2 = regRowid;
83163           pOp->p3 = regAutoinc;
83164         }
83165       }
83166       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
83167       ** to generate a unique primary key value.
83168       */
83169       if( !appendFlag ){
83170         int j1;
83171         if( !IsVirtual(pTab) ){
83172           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
83173           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
83174           sqlite3VdbeJumpHere(v, j1);
83175         }else{
83176           j1 = sqlite3VdbeCurrentAddr(v);
83177           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
83178         }
83179         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
83180       }
83181     }else if( IsVirtual(pTab) ){
83182       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
83183     }else{
83184       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
83185       appendFlag = 1;
83186     }
83187     autoIncStep(pParse, regAutoinc, regRowid);
83188
83189     /* Push onto the stack, data for all columns of the new entry, beginning
83190     ** with the first column.
83191     */
83192     nHidden = 0;
83193     for(i=0; i<pTab->nCol; i++){
83194       int iRegStore = regRowid+1+i;
83195       if( i==pTab->iPKey ){
83196         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
83197         ** Whenever this column is read, the record number will be substituted
83198         ** in its place.  So will fill this column with a NULL to avoid
83199         ** taking up data space with information that will never be used. */
83200         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
83201         continue;
83202       }
83203       if( pColumn==0 ){
83204         if( IsHiddenColumn(&pTab->aCol[i]) ){
83205           assert( IsVirtual(pTab) );
83206           j = -1;
83207           nHidden++;
83208         }else{
83209           j = i - nHidden;
83210         }
83211       }else{
83212         for(j=0; j<pColumn->nId; j++){
83213           if( pColumn->a[j].idx==i ) break;
83214         }
83215       }
83216       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
83217         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
83218       }else if( useTempTable ){
83219         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
83220       }else if( pSelect ){
83221         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
83222       }else{
83223         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
83224       }
83225     }
83226
83227     /* Generate code to check constraints and generate index keys and
83228     ** do the insertion.
83229     */
83230 #ifndef SQLITE_OMIT_VIRTUALTABLE
83231     if( IsVirtual(pTab) ){
83232       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
83233       sqlite3VtabMakeWritable(pParse, pTab);
83234       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
83235       sqlite3MayAbort(pParse);
83236     }else
83237 #endif
83238     {
83239       int isReplace;    /* Set to true if constraints may cause a replace */
83240       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
83241           keyColumn>=0, 0, onError, endOfLoop, &isReplace
83242       );
83243       sqlite3FkCheck(pParse, pTab, 0, regIns);
83244       sqlite3CompleteInsertion(
83245           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
83246       );
83247     }
83248   }
83249
83250   /* Update the count of rows that are inserted
83251   */
83252   if( (db->flags & SQLITE_CountRows)!=0 ){
83253     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
83254   }
83255
83256   if( pTrigger ){
83257     /* Code AFTER triggers */
83258     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
83259         pTab, regData-2-pTab->nCol, onError, endOfLoop);
83260   }
83261
83262   /* The bottom of the main insertion loop, if the data source
83263   ** is a SELECT statement.
83264   */
83265   sqlite3VdbeResolveLabel(v, endOfLoop);
83266   if( useTempTable ){
83267     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
83268     sqlite3VdbeJumpHere(v, addrInsTop);
83269     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
83270   }else if( pSelect ){
83271     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
83272     sqlite3VdbeJumpHere(v, addrInsTop);
83273   }
83274
83275   if( !IsVirtual(pTab) && !isView ){
83276     /* Close all tables opened */
83277     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
83278     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
83279       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
83280     }
83281   }
83282
83283 insert_end:
83284   /* Update the sqlite_sequence table by storing the content of the
83285   ** maximum rowid counter values recorded while inserting into
83286   ** autoincrement tables.
83287   */
83288   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
83289     sqlite3AutoincrementEnd(pParse);
83290   }
83291
83292   /*
83293   ** Return the number of rows inserted. If this routine is 
83294   ** generating code because of a call to sqlite3NestedParse(), do not
83295   ** invoke the callback function.
83296   */
83297   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
83298     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
83299     sqlite3VdbeSetNumCols(v, 1);
83300     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
83301   }
83302
83303 insert_cleanup:
83304   sqlite3SrcListDelete(db, pTabList);
83305   sqlite3ExprListDelete(db, pList);
83306   sqlite3SelectDelete(db, pSelect);
83307   sqlite3IdListDelete(db, pColumn);
83308   sqlite3DbFree(db, aRegIdx);
83309 }
83310
83311 /* Make sure "isView" and other macros defined above are undefined. Otherwise
83312 ** thely may interfere with compilation of other functions in this file
83313 ** (or in another file, if this file becomes part of the amalgamation).  */
83314 #ifdef isView
83315  #undef isView
83316 #endif
83317 #ifdef pTrigger
83318  #undef pTrigger
83319 #endif
83320 #ifdef tmask
83321  #undef tmask
83322 #endif
83323
83324
83325 /*
83326 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
83327 **
83328 ** The input is a range of consecutive registers as follows:
83329 **
83330 **    1.  The rowid of the row after the update.
83331 **
83332 **    2.  The data in the first column of the entry after the update.
83333 **
83334 **    i.  Data from middle columns...
83335 **
83336 **    N.  The data in the last column of the entry after the update.
83337 **
83338 ** The regRowid parameter is the index of the register containing (1).
83339 **
83340 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
83341 ** the address of a register containing the rowid before the update takes
83342 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
83343 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
83344 ** indicates that the rowid was explicitly specified as part of the
83345 ** INSERT statement. If rowidChng is false, it means that  the rowid is
83346 ** computed automatically in an insert or that the rowid value is not 
83347 ** modified by an update.
83348 **
83349 ** The code generated by this routine store new index entries into
83350 ** registers identified by aRegIdx[].  No index entry is created for
83351 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
83352 ** the same as the order of indices on the linked list of indices
83353 ** attached to the table.
83354 **
83355 ** This routine also generates code to check constraints.  NOT NULL,
83356 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
83357 ** then the appropriate action is performed.  There are five possible
83358 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
83359 **
83360 **  Constraint type  Action       What Happens
83361 **  ---------------  ----------   ----------------------------------------
83362 **  any              ROLLBACK     The current transaction is rolled back and
83363 **                                sqlite3_exec() returns immediately with a
83364 **                                return code of SQLITE_CONSTRAINT.
83365 **
83366 **  any              ABORT        Back out changes from the current command
83367 **                                only (do not do a complete rollback) then
83368 **                                cause sqlite3_exec() to return immediately
83369 **                                with SQLITE_CONSTRAINT.
83370 **
83371 **  any              FAIL         Sqlite_exec() returns immediately with a
83372 **                                return code of SQLITE_CONSTRAINT.  The
83373 **                                transaction is not rolled back and any
83374 **                                prior changes are retained.
83375 **
83376 **  any              IGNORE       The record number and data is popped from
83377 **                                the stack and there is an immediate jump
83378 **                                to label ignoreDest.
83379 **
83380 **  NOT NULL         REPLACE      The NULL value is replace by the default
83381 **                                value for that column.  If the default value
83382 **                                is NULL, the action is the same as ABORT.
83383 **
83384 **  UNIQUE           REPLACE      The other row that conflicts with the row
83385 **                                being inserted is removed.
83386 **
83387 **  CHECK            REPLACE      Illegal.  The results in an exception.
83388 **
83389 ** Which action to take is determined by the overrideError parameter.
83390 ** Or if overrideError==OE_Default, then the pParse->onError parameter
83391 ** is used.  Or if pParse->onError==OE_Default then the onError value
83392 ** for the constraint is used.
83393 **
83394 ** The calling routine must open a read/write cursor for pTab with
83395 ** cursor number "baseCur".  All indices of pTab must also have open
83396 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
83397 ** Except, if there is no possibility of a REPLACE action then
83398 ** cursors do not need to be open for indices where aRegIdx[i]==0.
83399 */
83400 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
83401   Parse *pParse,      /* The parser context */
83402   Table *pTab,        /* the table into which we are inserting */
83403   int baseCur,        /* Index of a read/write cursor pointing at pTab */
83404   int regRowid,       /* Index of the range of input registers */
83405   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
83406   int rowidChng,      /* True if the rowid might collide with existing entry */
83407   int isUpdate,       /* True for UPDATE, False for INSERT */
83408   int overrideError,  /* Override onError to this if not OE_Default */
83409   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
83410   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
83411 ){
83412   int i;              /* loop counter */
83413   Vdbe *v;            /* VDBE under constrution */
83414   int nCol;           /* Number of columns */
83415   int onError;        /* Conflict resolution strategy */
83416   int j1;             /* Addresss of jump instruction */
83417   int j2 = 0, j3;     /* Addresses of jump instructions */
83418   int regData;        /* Register containing first data column */
83419   int iCur;           /* Table cursor number */
83420   Index *pIdx;         /* Pointer to one of the indices */
83421   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
83422   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
83423
83424   v = sqlite3GetVdbe(pParse);
83425   assert( v!=0 );
83426   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
83427   nCol = pTab->nCol;
83428   regData = regRowid + 1;
83429
83430   /* Test all NOT NULL constraints.
83431   */
83432   for(i=0; i<nCol; i++){
83433     if( i==pTab->iPKey ){
83434       continue;
83435     }
83436     onError = pTab->aCol[i].notNull;
83437     if( onError==OE_None ) continue;
83438     if( overrideError!=OE_Default ){
83439       onError = overrideError;
83440     }else if( onError==OE_Default ){
83441       onError = OE_Abort;
83442     }
83443     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
83444       onError = OE_Abort;
83445     }
83446     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
83447         || onError==OE_Ignore || onError==OE_Replace );
83448     switch( onError ){
83449       case OE_Abort:
83450         sqlite3MayAbort(pParse);
83451       case OE_Rollback:
83452       case OE_Fail: {
83453         char *zMsg;
83454         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
83455                                   SQLITE_CONSTRAINT, onError, regData+i);
83456         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
83457                               pTab->zName, pTab->aCol[i].zName);
83458         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
83459         break;
83460       }
83461       case OE_Ignore: {
83462         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
83463         break;
83464       }
83465       default: {
83466         assert( onError==OE_Replace );
83467         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
83468         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
83469         sqlite3VdbeJumpHere(v, j1);
83470         break;
83471       }
83472     }
83473   }
83474
83475   /* Test all CHECK constraints
83476   */
83477 #ifndef SQLITE_OMIT_CHECK
83478   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
83479     int allOk = sqlite3VdbeMakeLabel(v);
83480     pParse->ckBase = regData;
83481     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
83482     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
83483     if( onError==OE_Ignore ){
83484       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
83485     }else{
83486       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
83487       sqlite3HaltConstraint(pParse, onError, 0, 0);
83488     }
83489     sqlite3VdbeResolveLabel(v, allOk);
83490   }
83491 #endif /* !defined(SQLITE_OMIT_CHECK) */
83492
83493   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
83494   ** of the new record does not previously exist.  Except, if this
83495   ** is an UPDATE and the primary key is not changing, that is OK.
83496   */
83497   if( rowidChng ){
83498     onError = pTab->keyConf;
83499     if( overrideError!=OE_Default ){
83500       onError = overrideError;
83501     }else if( onError==OE_Default ){
83502       onError = OE_Abort;
83503     }
83504     
83505     if( isUpdate ){
83506       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
83507     }
83508     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
83509     switch( onError ){
83510       default: {
83511         onError = OE_Abort;
83512         /* Fall thru into the next case */
83513       }
83514       case OE_Rollback:
83515       case OE_Abort:
83516       case OE_Fail: {
83517         sqlite3HaltConstraint(
83518           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
83519         break;
83520       }
83521       case OE_Replace: {
83522         /* If there are DELETE triggers on this table and the
83523         ** recursive-triggers flag is set, call GenerateRowDelete() to
83524         ** remove the conflicting row from the the table. This will fire
83525         ** the triggers and remove both the table and index b-tree entries.
83526         **
83527         ** Otherwise, if there are no triggers or the recursive-triggers
83528         ** flag is not set, but the table has one or more indexes, call 
83529         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
83530         ** only. The table b-tree entry will be replaced by the new entry 
83531         ** when it is inserted.  
83532         **
83533         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
83534         ** also invoke MultiWrite() to indicate that this VDBE may require
83535         ** statement rollback (if the statement is aborted after the delete
83536         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
83537         ** but being more selective here allows statements like:
83538         **
83539         **   REPLACE INTO t(rowid) VALUES($newrowid)
83540         **
83541         ** to run without a statement journal if there are no indexes on the
83542         ** table.
83543         */
83544         Trigger *pTrigger = 0;
83545         if( pParse->db->flags&SQLITE_RecTriggers ){
83546           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
83547         }
83548         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
83549           sqlite3MultiWrite(pParse);
83550           sqlite3GenerateRowDelete(
83551               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
83552           );
83553         }else if( pTab->pIndex ){
83554           sqlite3MultiWrite(pParse);
83555           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
83556         }
83557         seenReplace = 1;
83558         break;
83559       }
83560       case OE_Ignore: {
83561         assert( seenReplace==0 );
83562         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
83563         break;
83564       }
83565     }
83566     sqlite3VdbeJumpHere(v, j3);
83567     if( isUpdate ){
83568       sqlite3VdbeJumpHere(v, j2);
83569     }
83570   }
83571
83572   /* Test all UNIQUE constraints by creating entries for each UNIQUE
83573   ** index and making sure that duplicate entries do not already exist.
83574   ** Add the new records to the indices as we go.
83575   */
83576   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
83577     int regIdx;
83578     int regR;
83579
83580     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
83581
83582     /* Create a key for accessing the index entry */
83583     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
83584     for(i=0; i<pIdx->nColumn; i++){
83585       int idx = pIdx->aiColumn[i];
83586       if( idx==pTab->iPKey ){
83587         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
83588       }else{
83589         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
83590       }
83591     }
83592     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
83593     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
83594     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
83595     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
83596
83597     /* Find out what action to take in case there is an indexing conflict */
83598     onError = pIdx->onError;
83599     if( onError==OE_None ){ 
83600       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
83601       continue;  /* pIdx is not a UNIQUE index */
83602     }
83603     if( overrideError!=OE_Default ){
83604       onError = overrideError;
83605     }else if( onError==OE_Default ){
83606       onError = OE_Abort;
83607     }
83608     if( seenReplace ){
83609       if( onError==OE_Ignore ) onError = OE_Replace;
83610       else if( onError==OE_Fail ) onError = OE_Abort;
83611     }
83612     
83613     /* Check to see if the new index entry will be unique */
83614     regR = sqlite3GetTempReg(pParse);
83615     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
83616     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
83617                            regR, SQLITE_INT_TO_PTR(regIdx),
83618                            P4_INT32);
83619     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
83620
83621     /* Generate code that executes if the new index entry is not unique */
83622     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
83623         || onError==OE_Ignore || onError==OE_Replace );
83624     switch( onError ){
83625       case OE_Rollback:
83626       case OE_Abort:
83627       case OE_Fail: {
83628         int j;
83629         StrAccum errMsg;
83630         const char *zSep;
83631         char *zErr;
83632
83633         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
83634         errMsg.db = pParse->db;
83635         zSep = pIdx->nColumn>1 ? "columns " : "column ";
83636         for(j=0; j<pIdx->nColumn; j++){
83637           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
83638           sqlite3StrAccumAppend(&errMsg, zSep, -1);
83639           zSep = ", ";
83640           sqlite3StrAccumAppend(&errMsg, zCol, -1);
83641         }
83642         sqlite3StrAccumAppend(&errMsg,
83643             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
83644         zErr = sqlite3StrAccumFinish(&errMsg);
83645         sqlite3HaltConstraint(pParse, onError, zErr, 0);
83646         sqlite3DbFree(errMsg.db, zErr);
83647         break;
83648       }
83649       case OE_Ignore: {
83650         assert( seenReplace==0 );
83651         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
83652         break;
83653       }
83654       default: {
83655         Trigger *pTrigger = 0;
83656         assert( onError==OE_Replace );
83657         sqlite3MultiWrite(pParse);
83658         if( pParse->db->flags&SQLITE_RecTriggers ){
83659           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
83660         }
83661         sqlite3GenerateRowDelete(
83662             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
83663         );
83664         seenReplace = 1;
83665         break;
83666       }
83667     }
83668     sqlite3VdbeJumpHere(v, j3);
83669     sqlite3ReleaseTempReg(pParse, regR);
83670   }
83671   
83672   if( pbMayReplace ){
83673     *pbMayReplace = seenReplace;
83674   }
83675 }
83676
83677 /*
83678 ** This routine generates code to finish the INSERT or UPDATE operation
83679 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
83680 ** A consecutive range of registers starting at regRowid contains the
83681 ** rowid and the content to be inserted.
83682 **
83683 ** The arguments to this routine should be the same as the first six
83684 ** arguments to sqlite3GenerateConstraintChecks.
83685 */
83686 SQLITE_PRIVATE void sqlite3CompleteInsertion(
83687   Parse *pParse,      /* The parser context */
83688   Table *pTab,        /* the table into which we are inserting */
83689   int baseCur,        /* Index of a read/write cursor pointing at pTab */
83690   int regRowid,       /* Range of content */
83691   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
83692   int isUpdate,       /* True for UPDATE, False for INSERT */
83693   int appendBias,     /* True if this is likely to be an append */
83694   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
83695 ){
83696   int i;
83697   Vdbe *v;
83698   int nIdx;
83699   Index *pIdx;
83700   u8 pik_flags;
83701   int regData;
83702   int regRec;
83703
83704   v = sqlite3GetVdbe(pParse);
83705   assert( v!=0 );
83706   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
83707   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
83708   for(i=nIdx-1; i>=0; i--){
83709     if( aRegIdx[i]==0 ) continue;
83710     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
83711     if( useSeekResult ){
83712       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83713     }
83714   }
83715   regData = regRowid + 1;
83716   regRec = sqlite3GetTempReg(pParse);
83717   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
83718   sqlite3TableAffinityStr(v, pTab);
83719   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
83720   if( pParse->nested ){
83721     pik_flags = 0;
83722   }else{
83723     pik_flags = OPFLAG_NCHANGE;
83724     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
83725   }
83726   if( appendBias ){
83727     pik_flags |= OPFLAG_APPEND;
83728   }
83729   if( useSeekResult ){
83730     pik_flags |= OPFLAG_USESEEKRESULT;
83731   }
83732   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
83733   if( !pParse->nested ){
83734     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
83735   }
83736   sqlite3VdbeChangeP5(v, pik_flags);
83737 }
83738
83739 /*
83740 ** Generate code that will open cursors for a table and for all
83741 ** indices of that table.  The "baseCur" parameter is the cursor number used
83742 ** for the table.  Indices are opened on subsequent cursors.
83743 **
83744 ** Return the number of indices on the table.
83745 */
83746 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
83747   Parse *pParse,   /* Parsing context */
83748   Table *pTab,     /* Table to be opened */
83749   int baseCur,     /* Cursor number assigned to the table */
83750   int op           /* OP_OpenRead or OP_OpenWrite */
83751 ){
83752   int i;
83753   int iDb;
83754   Index *pIdx;
83755   Vdbe *v;
83756
83757   if( IsVirtual(pTab) ) return 0;
83758   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83759   v = sqlite3GetVdbe(pParse);
83760   assert( v!=0 );
83761   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
83762   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
83763     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
83764     assert( pIdx->pSchema==pTab->pSchema );
83765     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
83766                       (char*)pKey, P4_KEYINFO_HANDOFF);
83767     VdbeComment((v, "%s", pIdx->zName));
83768   }
83769   if( pParse->nTab<baseCur+i ){
83770     pParse->nTab = baseCur+i;
83771   }
83772   return i-1;
83773 }
83774
83775
83776 #ifdef SQLITE_TEST
83777 /*
83778 ** The following global variable is incremented whenever the
83779 ** transfer optimization is used.  This is used for testing
83780 ** purposes only - to make sure the transfer optimization really
83781 ** is happening when it is suppose to.
83782 */
83783 SQLITE_API int sqlite3_xferopt_count;
83784 #endif /* SQLITE_TEST */
83785
83786
83787 #ifndef SQLITE_OMIT_XFER_OPT
83788 /*
83789 ** Check to collation names to see if they are compatible.
83790 */
83791 static int xferCompatibleCollation(const char *z1, const char *z2){
83792   if( z1==0 ){
83793     return z2==0;
83794   }
83795   if( z2==0 ){
83796     return 0;
83797   }
83798   return sqlite3StrICmp(z1, z2)==0;
83799 }
83800
83801
83802 /*
83803 ** Check to see if index pSrc is compatible as a source of data
83804 ** for index pDest in an insert transfer optimization.  The rules
83805 ** for a compatible index:
83806 **
83807 **    *   The index is over the same set of columns
83808 **    *   The same DESC and ASC markings occurs on all columns
83809 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
83810 **    *   The same collating sequence on each column
83811 */
83812 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
83813   int i;
83814   assert( pDest && pSrc );
83815   assert( pDest->pTable!=pSrc->pTable );
83816   if( pDest->nColumn!=pSrc->nColumn ){
83817     return 0;   /* Different number of columns */
83818   }
83819   if( pDest->onError!=pSrc->onError ){
83820     return 0;   /* Different conflict resolution strategies */
83821   }
83822   for(i=0; i<pSrc->nColumn; i++){
83823     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
83824       return 0;   /* Different columns indexed */
83825     }
83826     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
83827       return 0;   /* Different sort orders */
83828     }
83829     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
83830       return 0;   /* Different collating sequences */
83831     }
83832   }
83833
83834   /* If no test above fails then the indices must be compatible */
83835   return 1;
83836 }
83837
83838 /*
83839 ** Attempt the transfer optimization on INSERTs of the form
83840 **
83841 **     INSERT INTO tab1 SELECT * FROM tab2;
83842 **
83843 ** This optimization is only attempted if
83844 **
83845 **    (1)  tab1 and tab2 have identical schemas including all the
83846 **         same indices and constraints
83847 **
83848 **    (2)  tab1 and tab2 are different tables
83849 **
83850 **    (3)  There must be no triggers on tab1
83851 **
83852 **    (4)  The result set of the SELECT statement is "*"
83853 **
83854 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
83855 **         or LIMIT clause.
83856 **
83857 **    (6)  The SELECT statement is a simple (not a compound) select that
83858 **         contains only tab2 in its FROM clause
83859 **
83860 ** This method for implementing the INSERT transfers raw records from
83861 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
83862 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
83863 ** the resulting tab1 has much less fragmentation.
83864 **
83865 ** This routine returns TRUE if the optimization is attempted.  If any
83866 ** of the conditions above fail so that the optimization should not
83867 ** be attempted, then this routine returns FALSE.
83868 */
83869 static int xferOptimization(
83870   Parse *pParse,        /* Parser context */
83871   Table *pDest,         /* The table we are inserting into */
83872   Select *pSelect,      /* A SELECT statement to use as the data source */
83873   int onError,          /* How to handle constraint errors */
83874   int iDbDest           /* The database of pDest */
83875 ){
83876   ExprList *pEList;                /* The result set of the SELECT */
83877   Table *pSrc;                     /* The table in the FROM clause of SELECT */
83878   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
83879   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
83880   int i;                           /* Loop counter */
83881   int iDbSrc;                      /* The database of pSrc */
83882   int iSrc, iDest;                 /* Cursors from source and destination */
83883   int addr1, addr2;                /* Loop addresses */
83884   int emptyDestTest;               /* Address of test for empty pDest */
83885   int emptySrcTest;                /* Address of test for empty pSrc */
83886   Vdbe *v;                         /* The VDBE we are building */
83887   KeyInfo *pKey;                   /* Key information for an index */
83888   int regAutoinc;                  /* Memory register used by AUTOINC */
83889   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
83890   int regData, regRowid;           /* Registers holding data and rowid */
83891
83892   if( pSelect==0 ){
83893     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
83894   }
83895   if( sqlite3TriggerList(pParse, pDest) ){
83896     return 0;   /* tab1 must not have triggers */
83897   }
83898 #ifndef SQLITE_OMIT_VIRTUALTABLE
83899   if( pDest->tabFlags & TF_Virtual ){
83900     return 0;   /* tab1 must not be a virtual table */
83901   }
83902 #endif
83903   if( onError==OE_Default ){
83904     onError = OE_Abort;
83905   }
83906   if( onError!=OE_Abort && onError!=OE_Rollback ){
83907     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
83908   }
83909   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
83910   if( pSelect->pSrc->nSrc!=1 ){
83911     return 0;   /* FROM clause must have exactly one term */
83912   }
83913   if( pSelect->pSrc->a[0].pSelect ){
83914     return 0;   /* FROM clause cannot contain a subquery */
83915   }
83916   if( pSelect->pWhere ){
83917     return 0;   /* SELECT may not have a WHERE clause */
83918   }
83919   if( pSelect->pOrderBy ){
83920     return 0;   /* SELECT may not have an ORDER BY clause */
83921   }
83922   /* Do not need to test for a HAVING clause.  If HAVING is present but
83923   ** there is no ORDER BY, we will get an error. */
83924   if( pSelect->pGroupBy ){
83925     return 0;   /* SELECT may not have a GROUP BY clause */
83926   }
83927   if( pSelect->pLimit ){
83928     return 0;   /* SELECT may not have a LIMIT clause */
83929   }
83930   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
83931   if( pSelect->pPrior ){
83932     return 0;   /* SELECT may not be a compound query */
83933   }
83934   if( pSelect->selFlags & SF_Distinct ){
83935     return 0;   /* SELECT may not be DISTINCT */
83936   }
83937   pEList = pSelect->pEList;
83938   assert( pEList!=0 );
83939   if( pEList->nExpr!=1 ){
83940     return 0;   /* The result set must have exactly one column */
83941   }
83942   assert( pEList->a[0].pExpr );
83943   if( pEList->a[0].pExpr->op!=TK_ALL ){
83944     return 0;   /* The result set must be the special operator "*" */
83945   }
83946
83947   /* At this point we have established that the statement is of the
83948   ** correct syntactic form to participate in this optimization.  Now
83949   ** we have to check the semantics.
83950   */
83951   pItem = pSelect->pSrc->a;
83952   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
83953   if( pSrc==0 ){
83954     return 0;   /* FROM clause does not contain a real table */
83955   }
83956   if( pSrc==pDest ){
83957     return 0;   /* tab1 and tab2 may not be the same table */
83958   }
83959 #ifndef SQLITE_OMIT_VIRTUALTABLE
83960   if( pSrc->tabFlags & TF_Virtual ){
83961     return 0;   /* tab2 must not be a virtual table */
83962   }
83963 #endif
83964   if( pSrc->pSelect ){
83965     return 0;   /* tab2 may not be a view */
83966   }
83967   if( pDest->nCol!=pSrc->nCol ){
83968     return 0;   /* Number of columns must be the same in tab1 and tab2 */
83969   }
83970   if( pDest->iPKey!=pSrc->iPKey ){
83971     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
83972   }
83973   for(i=0; i<pDest->nCol; i++){
83974     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
83975       return 0;    /* Affinity must be the same on all columns */
83976     }
83977     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
83978       return 0;    /* Collating sequence must be the same on all columns */
83979     }
83980     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
83981       return 0;    /* tab2 must be NOT NULL if tab1 is */
83982     }
83983   }
83984   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
83985     if( pDestIdx->onError!=OE_None ){
83986       destHasUniqueIdx = 1;
83987     }
83988     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
83989       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
83990     }
83991     if( pSrcIdx==0 ){
83992       return 0;    /* pDestIdx has no corresponding index in pSrc */
83993     }
83994   }
83995 #ifndef SQLITE_OMIT_CHECK
83996   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
83997     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
83998   }
83999 #endif
84000
84001   /* If we get this far, it means either:
84002   **
84003   **    *   We can always do the transfer if the table contains an
84004   **        an integer primary key
84005   **
84006   **    *   We can conditionally do the transfer if the destination
84007   **        table is empty.
84008   */
84009 #ifdef SQLITE_TEST
84010   sqlite3_xferopt_count++;
84011 #endif
84012   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
84013   v = sqlite3GetVdbe(pParse);
84014   sqlite3CodeVerifySchema(pParse, iDbSrc);
84015   iSrc = pParse->nTab++;
84016   iDest = pParse->nTab++;
84017   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
84018   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
84019   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
84020     /* If tables do not have an INTEGER PRIMARY KEY and there
84021     ** are indices to be copied and the destination is not empty,
84022     ** we have to disallow the transfer optimization because the
84023     ** the rowids might change which will mess up indexing.
84024     **
84025     ** Or if the destination has a UNIQUE index and is not empty,
84026     ** we also disallow the transfer optimization because we cannot
84027     ** insure that all entries in the union of DEST and SRC will be
84028     ** unique.
84029     */
84030     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
84031     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
84032     sqlite3VdbeJumpHere(v, addr1);
84033   }else{
84034     emptyDestTest = 0;
84035   }
84036   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
84037   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
84038   regData = sqlite3GetTempReg(pParse);
84039   regRowid = sqlite3GetTempReg(pParse);
84040   if( pDest->iPKey>=0 ){
84041     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
84042     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
84043     sqlite3HaltConstraint(
84044         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
84045     sqlite3VdbeJumpHere(v, addr2);
84046     autoIncStep(pParse, regAutoinc, regRowid);
84047   }else if( pDest->pIndex==0 ){
84048     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
84049   }else{
84050     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
84051     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
84052   }
84053   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
84054   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
84055   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
84056   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
84057   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
84058   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
84059     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
84060       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
84061     }
84062     assert( pSrcIdx );
84063     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
84064     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
84065     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
84066     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
84067                       (char*)pKey, P4_KEYINFO_HANDOFF);
84068     VdbeComment((v, "%s", pSrcIdx->zName));
84069     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
84070     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
84071                       (char*)pKey, P4_KEYINFO_HANDOFF);
84072     VdbeComment((v, "%s", pDestIdx->zName));
84073     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
84074     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
84075     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
84076     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
84077     sqlite3VdbeJumpHere(v, addr1);
84078   }
84079   sqlite3VdbeJumpHere(v, emptySrcTest);
84080   sqlite3ReleaseTempReg(pParse, regRowid);
84081   sqlite3ReleaseTempReg(pParse, regData);
84082   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
84083   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
84084   if( emptyDestTest ){
84085     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
84086     sqlite3VdbeJumpHere(v, emptyDestTest);
84087     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
84088     return 0;
84089   }else{
84090     return 1;
84091   }
84092 }
84093 #endif /* SQLITE_OMIT_XFER_OPT */
84094
84095 /************** End of insert.c **********************************************/
84096 /************** Begin file legacy.c ******************************************/
84097 /*
84098 ** 2001 September 15
84099 **
84100 ** The author disclaims copyright to this source code.  In place of
84101 ** a legal notice, here is a blessing:
84102 **
84103 **    May you do good and not evil.
84104 **    May you find forgiveness for yourself and forgive others.
84105 **    May you share freely, never taking more than you give.
84106 **
84107 *************************************************************************
84108 ** Main file for the SQLite library.  The routines in this file
84109 ** implement the programmer interface to the library.  Routines in
84110 ** other files are for internal use by SQLite and should not be
84111 ** accessed by users of the library.
84112 */
84113
84114
84115 /*
84116 ** Execute SQL code.  Return one of the SQLITE_ success/failure
84117 ** codes.  Also write an error message into memory obtained from
84118 ** malloc() and make *pzErrMsg point to that message.
84119 **
84120 ** If the SQL is a query, then for each row in the query result
84121 ** the xCallback() function is called.  pArg becomes the first
84122 ** argument to xCallback().  If xCallback=NULL then no callback
84123 ** is invoked, even for queries.
84124 */
84125 SQLITE_API int sqlite3_exec(
84126   sqlite3 *db,                /* The database on which the SQL executes */
84127   const char *zSql,           /* The SQL to be executed */
84128   sqlite3_callback xCallback, /* Invoke this callback routine */
84129   void *pArg,                 /* First argument to xCallback() */
84130   char **pzErrMsg             /* Write error messages here */
84131 ){
84132   int rc = SQLITE_OK;         /* Return code */
84133   const char *zLeftover;      /* Tail of unprocessed SQL */
84134   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
84135   char **azCols = 0;          /* Names of result columns */
84136   int nRetry = 0;             /* Number of retry attempts */
84137   int callbackIsInit;         /* True if callback data is initialized */
84138
84139   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
84140   if( zSql==0 ) zSql = "";
84141
84142   sqlite3_mutex_enter(db->mutex);
84143   sqlite3Error(db, SQLITE_OK, 0);
84144   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
84145     int nCol;
84146     char **azVals = 0;
84147
84148     pStmt = 0;
84149     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
84150     assert( rc==SQLITE_OK || pStmt==0 );
84151     if( rc!=SQLITE_OK ){
84152       continue;
84153     }
84154     if( !pStmt ){
84155       /* this happens for a comment or white-space */
84156       zSql = zLeftover;
84157       continue;
84158     }
84159
84160     callbackIsInit = 0;
84161     nCol = sqlite3_column_count(pStmt);
84162
84163     while( 1 ){
84164       int i;
84165       rc = sqlite3_step(pStmt);
84166
84167       /* Invoke the callback function if required */
84168       if( xCallback && (SQLITE_ROW==rc || 
84169           (SQLITE_DONE==rc && !callbackIsInit
84170                            && db->flags&SQLITE_NullCallback)) ){
84171         if( !callbackIsInit ){
84172           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
84173           if( azCols==0 ){
84174             goto exec_out;
84175           }
84176           for(i=0; i<nCol; i++){
84177             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
84178             /* sqlite3VdbeSetColName() installs column names as UTF8
84179             ** strings so there is no way for sqlite3_column_name() to fail. */
84180             assert( azCols[i]!=0 );
84181           }
84182           callbackIsInit = 1;
84183         }
84184         if( rc==SQLITE_ROW ){
84185           azVals = &azCols[nCol];
84186           for(i=0; i<nCol; i++){
84187             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
84188             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
84189               db->mallocFailed = 1;
84190               goto exec_out;
84191             }
84192           }
84193         }
84194         if( xCallback(pArg, nCol, azVals, azCols) ){
84195           rc = SQLITE_ABORT;
84196           sqlite3VdbeFinalize((Vdbe *)pStmt);
84197           pStmt = 0;
84198           sqlite3Error(db, SQLITE_ABORT, 0);
84199           goto exec_out;
84200         }
84201       }
84202
84203       if( rc!=SQLITE_ROW ){
84204         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
84205         pStmt = 0;
84206         if( rc!=SQLITE_SCHEMA ){
84207           nRetry = 0;
84208           zSql = zLeftover;
84209           while( sqlite3Isspace(zSql[0]) ) zSql++;
84210         }
84211         break;
84212       }
84213     }
84214
84215     sqlite3DbFree(db, azCols);
84216     azCols = 0;
84217   }
84218
84219 exec_out:
84220   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
84221   sqlite3DbFree(db, azCols);
84222
84223   rc = sqlite3ApiExit(db, rc);
84224   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
84225     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
84226     *pzErrMsg = sqlite3Malloc(nErrMsg);
84227     if( *pzErrMsg ){
84228       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
84229     }else{
84230       rc = SQLITE_NOMEM;
84231       sqlite3Error(db, SQLITE_NOMEM, 0);
84232     }
84233   }else if( pzErrMsg ){
84234     *pzErrMsg = 0;
84235   }
84236
84237   assert( (rc&db->errMask)==rc );
84238   sqlite3_mutex_leave(db->mutex);
84239   return rc;
84240 }
84241
84242 /************** End of legacy.c **********************************************/
84243 /************** Begin file loadext.c *****************************************/
84244 /*
84245 ** 2006 June 7
84246 **
84247 ** The author disclaims copyright to this source code.  In place of
84248 ** a legal notice, here is a blessing:
84249 **
84250 **    May you do good and not evil.
84251 **    May you find forgiveness for yourself and forgive others.
84252 **    May you share freely, never taking more than you give.
84253 **
84254 *************************************************************************
84255 ** This file contains code used to dynamically load extensions into
84256 ** the SQLite library.
84257 */
84258
84259 #ifndef SQLITE_CORE
84260   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
84261 #endif
84262 /************** Include sqlite3ext.h in the middle of loadext.c **************/
84263 /************** Begin file sqlite3ext.h **************************************/
84264 /*
84265 ** 2006 June 7
84266 **
84267 ** The author disclaims copyright to this source code.  In place of
84268 ** a legal notice, here is a blessing:
84269 **
84270 **    May you do good and not evil.
84271 **    May you find forgiveness for yourself and forgive others.
84272 **    May you share freely, never taking more than you give.
84273 **
84274 *************************************************************************
84275 ** This header file defines the SQLite interface for use by
84276 ** shared libraries that want to be imported as extensions into
84277 ** an SQLite instance.  Shared libraries that intend to be loaded
84278 ** as extensions by SQLite should #include this file instead of 
84279 ** sqlite3.h.
84280 */
84281 #ifndef _SQLITE3EXT_H_
84282 #define _SQLITE3EXT_H_
84283
84284 typedef struct sqlite3_api_routines sqlite3_api_routines;
84285
84286 /*
84287 ** The following structure holds pointers to all of the SQLite API
84288 ** routines.
84289 **
84290 ** WARNING:  In order to maintain backwards compatibility, add new
84291 ** interfaces to the end of this structure only.  If you insert new
84292 ** interfaces in the middle of this structure, then older different
84293 ** versions of SQLite will not be able to load each others' shared
84294 ** libraries!
84295 */
84296 struct sqlite3_api_routines {
84297   void * (*aggregate_context)(sqlite3_context*,int nBytes);
84298   int  (*aggregate_count)(sqlite3_context*);
84299   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
84300   int  (*bind_double)(sqlite3_stmt*,int,double);
84301   int  (*bind_int)(sqlite3_stmt*,int,int);
84302   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
84303   int  (*bind_null)(sqlite3_stmt*,int);
84304   int  (*bind_parameter_count)(sqlite3_stmt*);
84305   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
84306   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
84307   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
84308   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
84309   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
84310   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
84311   int  (*busy_timeout)(sqlite3*,int ms);
84312   int  (*changes)(sqlite3*);
84313   int  (*close)(sqlite3*);
84314   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
84315   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
84316   const void * (*column_blob)(sqlite3_stmt*,int iCol);
84317   int  (*column_bytes)(sqlite3_stmt*,int iCol);
84318   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
84319   int  (*column_count)(sqlite3_stmt*pStmt);
84320   const char * (*column_database_name)(sqlite3_stmt*,int);
84321   const void * (*column_database_name16)(sqlite3_stmt*,int);
84322   const char * (*column_decltype)(sqlite3_stmt*,int i);
84323   const void * (*column_decltype16)(sqlite3_stmt*,int);
84324   double  (*column_double)(sqlite3_stmt*,int iCol);
84325   int  (*column_int)(sqlite3_stmt*,int iCol);
84326   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
84327   const char * (*column_name)(sqlite3_stmt*,int);
84328   const void * (*column_name16)(sqlite3_stmt*,int);
84329   const char * (*column_origin_name)(sqlite3_stmt*,int);
84330   const void * (*column_origin_name16)(sqlite3_stmt*,int);
84331   const char * (*column_table_name)(sqlite3_stmt*,int);
84332   const void * (*column_table_name16)(sqlite3_stmt*,int);
84333   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
84334   const void * (*column_text16)(sqlite3_stmt*,int iCol);
84335   int  (*column_type)(sqlite3_stmt*,int iCol);
84336   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
84337   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
84338   int  (*complete)(const char*sql);
84339   int  (*complete16)(const void*sql);
84340   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
84341   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
84342   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*));
84343   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*));
84344   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
84345   int  (*data_count)(sqlite3_stmt*pStmt);
84346   sqlite3 * (*db_handle)(sqlite3_stmt*);
84347   int (*declare_vtab)(sqlite3*,const char*);
84348   int  (*enable_shared_cache)(int);
84349   int  (*errcode)(sqlite3*db);
84350   const char * (*errmsg)(sqlite3*);
84351   const void * (*errmsg16)(sqlite3*);
84352   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
84353   int  (*expired)(sqlite3_stmt*);
84354   int  (*finalize)(sqlite3_stmt*pStmt);
84355   void  (*free)(void*);
84356   void  (*free_table)(char**result);
84357   int  (*get_autocommit)(sqlite3*);
84358   void * (*get_auxdata)(sqlite3_context*,int);
84359   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
84360   int  (*global_recover)(void);
84361   void  (*interruptx)(sqlite3*);
84362   sqlite_int64  (*last_insert_rowid)(sqlite3*);
84363   const char * (*libversion)(void);
84364   int  (*libversion_number)(void);
84365   void *(*malloc)(int);
84366   char * (*mprintf)(const char*,...);
84367   int  (*open)(const char*,sqlite3**);
84368   int  (*open16)(const void*,sqlite3**);
84369   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
84370   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
84371   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
84372   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
84373   void *(*realloc)(void*,int);
84374   int  (*reset)(sqlite3_stmt*pStmt);
84375   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
84376   void  (*result_double)(sqlite3_context*,double);
84377   void  (*result_error)(sqlite3_context*,const char*,int);
84378   void  (*result_error16)(sqlite3_context*,const void*,int);
84379   void  (*result_int)(sqlite3_context*,int);
84380   void  (*result_int64)(sqlite3_context*,sqlite_int64);
84381   void  (*result_null)(sqlite3_context*);
84382   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
84383   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
84384   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
84385   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
84386   void  (*result_value)(sqlite3_context*,sqlite3_value*);
84387   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
84388   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
84389   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
84390   char * (*snprintf)(int,char*,const char*,...);
84391   int  (*step)(sqlite3_stmt*);
84392   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
84393   void  (*thread_cleanup)(void);
84394   int  (*total_changes)(sqlite3*);
84395   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
84396   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
84397   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
84398   void * (*user_data)(sqlite3_context*);
84399   const void * (*value_blob)(sqlite3_value*);
84400   int  (*value_bytes)(sqlite3_value*);
84401   int  (*value_bytes16)(sqlite3_value*);
84402   double  (*value_double)(sqlite3_value*);
84403   int  (*value_int)(sqlite3_value*);
84404   sqlite_int64  (*value_int64)(sqlite3_value*);
84405   int  (*value_numeric_type)(sqlite3_value*);
84406   const unsigned char * (*value_text)(sqlite3_value*);
84407   const void * (*value_text16)(sqlite3_value*);
84408   const void * (*value_text16be)(sqlite3_value*);
84409   const void * (*value_text16le)(sqlite3_value*);
84410   int  (*value_type)(sqlite3_value*);
84411   char *(*vmprintf)(const char*,va_list);
84412   /* Added ??? */
84413   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
84414   /* Added by 3.3.13 */
84415   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
84416   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
84417   int (*clear_bindings)(sqlite3_stmt*);
84418   /* Added by 3.4.1 */
84419   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
84420   /* Added by 3.5.0 */
84421   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
84422   int (*blob_bytes)(sqlite3_blob*);
84423   int (*blob_close)(sqlite3_blob*);
84424   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
84425   int (*blob_read)(sqlite3_blob*,void*,int,int);
84426   int (*blob_write)(sqlite3_blob*,const void*,int,int);
84427   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
84428   int (*file_control)(sqlite3*,const char*,int,void*);
84429   sqlite3_int64 (*memory_highwater)(int);
84430   sqlite3_int64 (*memory_used)(void);
84431   sqlite3_mutex *(*mutex_alloc)(int);
84432   void (*mutex_enter)(sqlite3_mutex*);
84433   void (*mutex_free)(sqlite3_mutex*);
84434   void (*mutex_leave)(sqlite3_mutex*);
84435   int (*mutex_try)(sqlite3_mutex*);
84436   int (*open_v2)(const char*,sqlite3**,int,const char*);
84437   int (*release_memory)(int);
84438   void (*result_error_nomem)(sqlite3_context*);
84439   void (*result_error_toobig)(sqlite3_context*);
84440   int (*sleep)(int);
84441   void (*soft_heap_limit)(int);
84442   sqlite3_vfs *(*vfs_find)(const char*);
84443   int (*vfs_register)(sqlite3_vfs*,int);
84444   int (*vfs_unregister)(sqlite3_vfs*);
84445   int (*xthreadsafe)(void);
84446   void (*result_zeroblob)(sqlite3_context*,int);
84447   void (*result_error_code)(sqlite3_context*,int);
84448   int (*test_control)(int, ...);
84449   void (*randomness)(int,void*);
84450   sqlite3 *(*context_db_handle)(sqlite3_context*);
84451   int (*extended_result_codes)(sqlite3*,int);
84452   int (*limit)(sqlite3*,int,int);
84453   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
84454   const char *(*sql)(sqlite3_stmt*);
84455   int (*status)(int,int*,int*,int);
84456   int (*backup_finish)(sqlite3_backup*);
84457   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
84458   int (*backup_pagecount)(sqlite3_backup*);
84459   int (*backup_remaining)(sqlite3_backup*);
84460   int (*backup_step)(sqlite3_backup*,int);
84461   const char *(*compileoption_get)(int);
84462   int (*compileoption_used)(const char*);
84463   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*),void(*xDestroy)(void*));
84464   int (*db_config)(sqlite3*,int,...);
84465   sqlite3_mutex *(*db_mutex)(sqlite3*);
84466   int (*db_status)(sqlite3*,int,int*,int*,int);
84467   int (*extended_errcode)(sqlite3*);
84468   void (*log)(int,const char*,...);
84469   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
84470   const char *(*sourceid)(void);
84471   int (*stmt_status)(sqlite3_stmt*,int,int);
84472   int (*strnicmp)(const char*,const char*,int);
84473   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
84474   int (*wal_autocheckpoint)(sqlite3*,int);
84475   int (*wal_checkpoint)(sqlite3*,const char*);
84476   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
84477 };
84478
84479 /*
84480 ** The following macros redefine the API routines so that they are
84481 ** redirected throught the global sqlite3_api structure.
84482 **
84483 ** This header file is also used by the loadext.c source file
84484 ** (part of the main SQLite library - not an extension) so that
84485 ** it can get access to the sqlite3_api_routines structure
84486 ** definition.  But the main library does not want to redefine
84487 ** the API.  So the redefinition macros are only valid if the
84488 ** SQLITE_CORE macros is undefined.
84489 */
84490 #ifndef SQLITE_CORE
84491 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
84492 #ifndef SQLITE_OMIT_DEPRECATED
84493 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
84494 #endif
84495 #define sqlite3_bind_blob              sqlite3_api->bind_blob
84496 #define sqlite3_bind_double            sqlite3_api->bind_double
84497 #define sqlite3_bind_int               sqlite3_api->bind_int
84498 #define sqlite3_bind_int64             sqlite3_api->bind_int64
84499 #define sqlite3_bind_null              sqlite3_api->bind_null
84500 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
84501 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
84502 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
84503 #define sqlite3_bind_text              sqlite3_api->bind_text
84504 #define sqlite3_bind_text16            sqlite3_api->bind_text16
84505 #define sqlite3_bind_value             sqlite3_api->bind_value
84506 #define sqlite3_busy_handler           sqlite3_api->busy_handler
84507 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
84508 #define sqlite3_changes                sqlite3_api->changes
84509 #define sqlite3_close                  sqlite3_api->close
84510 #define sqlite3_collation_needed       sqlite3_api->collation_needed
84511 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
84512 #define sqlite3_column_blob            sqlite3_api->column_blob
84513 #define sqlite3_column_bytes           sqlite3_api->column_bytes
84514 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
84515 #define sqlite3_column_count           sqlite3_api->column_count
84516 #define sqlite3_column_database_name   sqlite3_api->column_database_name
84517 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
84518 #define sqlite3_column_decltype        sqlite3_api->column_decltype
84519 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
84520 #define sqlite3_column_double          sqlite3_api->column_double
84521 #define sqlite3_column_int             sqlite3_api->column_int
84522 #define sqlite3_column_int64           sqlite3_api->column_int64
84523 #define sqlite3_column_name            sqlite3_api->column_name
84524 #define sqlite3_column_name16          sqlite3_api->column_name16
84525 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
84526 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
84527 #define sqlite3_column_table_name      sqlite3_api->column_table_name
84528 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
84529 #define sqlite3_column_text            sqlite3_api->column_text
84530 #define sqlite3_column_text16          sqlite3_api->column_text16
84531 #define sqlite3_column_type            sqlite3_api->column_type
84532 #define sqlite3_column_value           sqlite3_api->column_value
84533 #define sqlite3_commit_hook            sqlite3_api->commit_hook
84534 #define sqlite3_complete               sqlite3_api->complete
84535 #define sqlite3_complete16             sqlite3_api->complete16
84536 #define sqlite3_create_collation       sqlite3_api->create_collation
84537 #define sqlite3_create_collation16     sqlite3_api->create_collation16
84538 #define sqlite3_create_function        sqlite3_api->create_function
84539 #define sqlite3_create_function16      sqlite3_api->create_function16
84540 #define sqlite3_create_module          sqlite3_api->create_module
84541 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
84542 #define sqlite3_data_count             sqlite3_api->data_count
84543 #define sqlite3_db_handle              sqlite3_api->db_handle
84544 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
84545 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
84546 #define sqlite3_errcode                sqlite3_api->errcode
84547 #define sqlite3_errmsg                 sqlite3_api->errmsg
84548 #define sqlite3_errmsg16               sqlite3_api->errmsg16
84549 #define sqlite3_exec                   sqlite3_api->exec
84550 #ifndef SQLITE_OMIT_DEPRECATED
84551 #define sqlite3_expired                sqlite3_api->expired
84552 #endif
84553 #define sqlite3_finalize               sqlite3_api->finalize
84554 #define sqlite3_free                   sqlite3_api->free
84555 #define sqlite3_free_table             sqlite3_api->free_table
84556 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
84557 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
84558 #define sqlite3_get_table              sqlite3_api->get_table
84559 #ifndef SQLITE_OMIT_DEPRECATED
84560 #define sqlite3_global_recover         sqlite3_api->global_recover
84561 #endif
84562 #define sqlite3_interrupt              sqlite3_api->interruptx
84563 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
84564 #define sqlite3_libversion             sqlite3_api->libversion
84565 #define sqlite3_libversion_number      sqlite3_api->libversion_number
84566 #define sqlite3_malloc                 sqlite3_api->malloc
84567 #define sqlite3_mprintf                sqlite3_api->mprintf
84568 #define sqlite3_open                   sqlite3_api->open
84569 #define sqlite3_open16                 sqlite3_api->open16
84570 #define sqlite3_prepare                sqlite3_api->prepare
84571 #define sqlite3_prepare16              sqlite3_api->prepare16
84572 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
84573 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
84574 #define sqlite3_profile                sqlite3_api->profile
84575 #define sqlite3_progress_handler       sqlite3_api->progress_handler
84576 #define sqlite3_realloc                sqlite3_api->realloc
84577 #define sqlite3_reset                  sqlite3_api->reset
84578 #define sqlite3_result_blob            sqlite3_api->result_blob
84579 #define sqlite3_result_double          sqlite3_api->result_double
84580 #define sqlite3_result_error           sqlite3_api->result_error
84581 #define sqlite3_result_error16         sqlite3_api->result_error16
84582 #define sqlite3_result_int             sqlite3_api->result_int
84583 #define sqlite3_result_int64           sqlite3_api->result_int64
84584 #define sqlite3_result_null            sqlite3_api->result_null
84585 #define sqlite3_result_text            sqlite3_api->result_text
84586 #define sqlite3_result_text16          sqlite3_api->result_text16
84587 #define sqlite3_result_text16be        sqlite3_api->result_text16be
84588 #define sqlite3_result_text16le        sqlite3_api->result_text16le
84589 #define sqlite3_result_value           sqlite3_api->result_value
84590 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
84591 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
84592 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
84593 #define sqlite3_snprintf               sqlite3_api->snprintf
84594 #define sqlite3_step                   sqlite3_api->step
84595 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
84596 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
84597 #define sqlite3_total_changes          sqlite3_api->total_changes
84598 #define sqlite3_trace                  sqlite3_api->trace
84599 #ifndef SQLITE_OMIT_DEPRECATED
84600 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
84601 #endif
84602 #define sqlite3_update_hook            sqlite3_api->update_hook
84603 #define sqlite3_user_data              sqlite3_api->user_data
84604 #define sqlite3_value_blob             sqlite3_api->value_blob
84605 #define sqlite3_value_bytes            sqlite3_api->value_bytes
84606 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
84607 #define sqlite3_value_double           sqlite3_api->value_double
84608 #define sqlite3_value_int              sqlite3_api->value_int
84609 #define sqlite3_value_int64            sqlite3_api->value_int64
84610 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
84611 #define sqlite3_value_text             sqlite3_api->value_text
84612 #define sqlite3_value_text16           sqlite3_api->value_text16
84613 #define sqlite3_value_text16be         sqlite3_api->value_text16be
84614 #define sqlite3_value_text16le         sqlite3_api->value_text16le
84615 #define sqlite3_value_type             sqlite3_api->value_type
84616 #define sqlite3_vmprintf               sqlite3_api->vmprintf
84617 #define sqlite3_overload_function      sqlite3_api->overload_function
84618 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
84619 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
84620 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
84621 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
84622 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
84623 #define sqlite3_blob_close             sqlite3_api->blob_close
84624 #define sqlite3_blob_open              sqlite3_api->blob_open
84625 #define sqlite3_blob_read              sqlite3_api->blob_read
84626 #define sqlite3_blob_write             sqlite3_api->blob_write
84627 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
84628 #define sqlite3_file_control           sqlite3_api->file_control
84629 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
84630 #define sqlite3_memory_used            sqlite3_api->memory_used
84631 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
84632 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
84633 #define sqlite3_mutex_free             sqlite3_api->mutex_free
84634 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
84635 #define sqlite3_mutex_try              sqlite3_api->mutex_try
84636 #define sqlite3_open_v2                sqlite3_api->open_v2
84637 #define sqlite3_release_memory         sqlite3_api->release_memory
84638 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
84639 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
84640 #define sqlite3_sleep                  sqlite3_api->sleep
84641 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
84642 #define sqlite3_vfs_find               sqlite3_api->vfs_find
84643 #define sqlite3_vfs_register           sqlite3_api->vfs_register
84644 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
84645 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
84646 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
84647 #define sqlite3_result_error_code      sqlite3_api->result_error_code
84648 #define sqlite3_test_control           sqlite3_api->test_control
84649 #define sqlite3_randomness             sqlite3_api->randomness
84650 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
84651 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
84652 #define sqlite3_limit                  sqlite3_api->limit
84653 #define sqlite3_next_stmt              sqlite3_api->next_stmt
84654 #define sqlite3_sql                    sqlite3_api->sql
84655 #define sqlite3_status                 sqlite3_api->status
84656 #define sqlite3_backup_finish          sqlite3_api->backup_finish
84657 #define sqlite3_backup_init            sqlite3_api->backup_init
84658 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
84659 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
84660 #define sqlite3_backup_step            sqlite3_api->backup_step
84661 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
84662 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
84663 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
84664 #define sqlite3_db_config              sqlite3_api->db_config
84665 #define sqlite3_db_mutex               sqlite3_api->db_mutex
84666 #define sqlite3_db_status              sqlite3_api->db_status
84667 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
84668 #define sqlite3_log                    sqlite3_api->log
84669 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
84670 #define sqlite3_sourceid               sqlite3_api->sourceid
84671 #define sqlite3_stmt_status            sqlite3_api->stmt_status
84672 #define sqlite3_strnicmp               sqlite3_api->strnicmp
84673 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
84674 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
84675 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
84676 #define sqlite3_wal_hook               sqlite3_api->wal_hook
84677 #endif /* SQLITE_CORE */
84678
84679 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
84680 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
84681
84682 #endif /* _SQLITE3EXT_H_ */
84683
84684 /************** End of sqlite3ext.h ******************************************/
84685 /************** Continuing where we left off in loadext.c ********************/
84686
84687 #ifndef SQLITE_OMIT_LOAD_EXTENSION
84688
84689 /*
84690 ** Some API routines are omitted when various features are
84691 ** excluded from a build of SQLite.  Substitute a NULL pointer
84692 ** for any missing APIs.
84693 */
84694 #ifndef SQLITE_ENABLE_COLUMN_METADATA
84695 # define sqlite3_column_database_name   0
84696 # define sqlite3_column_database_name16 0
84697 # define sqlite3_column_table_name      0
84698 # define sqlite3_column_table_name16    0
84699 # define sqlite3_column_origin_name     0
84700 # define sqlite3_column_origin_name16   0
84701 # define sqlite3_table_column_metadata  0
84702 #endif
84703
84704 #ifdef SQLITE_OMIT_AUTHORIZATION
84705 # define sqlite3_set_authorizer         0
84706 #endif
84707
84708 #ifdef SQLITE_OMIT_UTF16
84709 # define sqlite3_bind_text16            0
84710 # define sqlite3_collation_needed16     0
84711 # define sqlite3_column_decltype16      0
84712 # define sqlite3_column_name16          0
84713 # define sqlite3_column_text16          0
84714 # define sqlite3_complete16             0
84715 # define sqlite3_create_collation16     0
84716 # define sqlite3_create_function16      0
84717 # define sqlite3_errmsg16               0
84718 # define sqlite3_open16                 0
84719 # define sqlite3_prepare16              0
84720 # define sqlite3_prepare16_v2           0
84721 # define sqlite3_result_error16         0
84722 # define sqlite3_result_text16          0
84723 # define sqlite3_result_text16be        0
84724 # define sqlite3_result_text16le        0
84725 # define sqlite3_value_text16           0
84726 # define sqlite3_value_text16be         0
84727 # define sqlite3_value_text16le         0
84728 # define sqlite3_column_database_name16 0
84729 # define sqlite3_column_table_name16    0
84730 # define sqlite3_column_origin_name16   0
84731 #endif
84732
84733 #ifdef SQLITE_OMIT_COMPLETE
84734 # define sqlite3_complete 0
84735 # define sqlite3_complete16 0
84736 #endif
84737
84738 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
84739 # define sqlite3_progress_handler 0
84740 #endif
84741
84742 #ifdef SQLITE_OMIT_VIRTUALTABLE
84743 # define sqlite3_create_module 0
84744 # define sqlite3_create_module_v2 0
84745 # define sqlite3_declare_vtab 0
84746 #endif
84747
84748 #ifdef SQLITE_OMIT_SHARED_CACHE
84749 # define sqlite3_enable_shared_cache 0
84750 #endif
84751
84752 #ifdef SQLITE_OMIT_TRACE
84753 # define sqlite3_profile       0
84754 # define sqlite3_trace         0
84755 #endif
84756
84757 #ifdef SQLITE_OMIT_GET_TABLE
84758 # define sqlite3_free_table    0
84759 # define sqlite3_get_table     0
84760 #endif
84761
84762 #ifdef SQLITE_OMIT_INCRBLOB
84763 #define sqlite3_bind_zeroblob  0
84764 #define sqlite3_blob_bytes     0
84765 #define sqlite3_blob_close     0
84766 #define sqlite3_blob_open      0
84767 #define sqlite3_blob_read      0
84768 #define sqlite3_blob_write     0
84769 #endif
84770
84771 /*
84772 ** The following structure contains pointers to all SQLite API routines.
84773 ** A pointer to this structure is passed into extensions when they are
84774 ** loaded so that the extension can make calls back into the SQLite
84775 ** library.
84776 **
84777 ** When adding new APIs, add them to the bottom of this structure
84778 ** in order to preserve backwards compatibility.
84779 **
84780 ** Extensions that use newer APIs should first call the
84781 ** sqlite3_libversion_number() to make sure that the API they
84782 ** intend to use is supported by the library.  Extensions should
84783 ** also check to make sure that the pointer to the function is
84784 ** not NULL before calling it.
84785 */
84786 static const sqlite3_api_routines sqlite3Apis = {
84787   sqlite3_aggregate_context,
84788 #ifndef SQLITE_OMIT_DEPRECATED
84789   sqlite3_aggregate_count,
84790 #else
84791   0,
84792 #endif
84793   sqlite3_bind_blob,
84794   sqlite3_bind_double,
84795   sqlite3_bind_int,
84796   sqlite3_bind_int64,
84797   sqlite3_bind_null,
84798   sqlite3_bind_parameter_count,
84799   sqlite3_bind_parameter_index,
84800   sqlite3_bind_parameter_name,
84801   sqlite3_bind_text,
84802   sqlite3_bind_text16,
84803   sqlite3_bind_value,
84804   sqlite3_busy_handler,
84805   sqlite3_busy_timeout,
84806   sqlite3_changes,
84807   sqlite3_close,
84808   sqlite3_collation_needed,
84809   sqlite3_collation_needed16,
84810   sqlite3_column_blob,
84811   sqlite3_column_bytes,
84812   sqlite3_column_bytes16,
84813   sqlite3_column_count,
84814   sqlite3_column_database_name,
84815   sqlite3_column_database_name16,
84816   sqlite3_column_decltype,
84817   sqlite3_column_decltype16,
84818   sqlite3_column_double,
84819   sqlite3_column_int,
84820   sqlite3_column_int64,
84821   sqlite3_column_name,
84822   sqlite3_column_name16,
84823   sqlite3_column_origin_name,
84824   sqlite3_column_origin_name16,
84825   sqlite3_column_table_name,
84826   sqlite3_column_table_name16,
84827   sqlite3_column_text,
84828   sqlite3_column_text16,
84829   sqlite3_column_type,
84830   sqlite3_column_value,
84831   sqlite3_commit_hook,
84832   sqlite3_complete,
84833   sqlite3_complete16,
84834   sqlite3_create_collation,
84835   sqlite3_create_collation16,
84836   sqlite3_create_function,
84837   sqlite3_create_function16,
84838   sqlite3_create_module,
84839   sqlite3_data_count,
84840   sqlite3_db_handle,
84841   sqlite3_declare_vtab,
84842   sqlite3_enable_shared_cache,
84843   sqlite3_errcode,
84844   sqlite3_errmsg,
84845   sqlite3_errmsg16,
84846   sqlite3_exec,
84847 #ifndef SQLITE_OMIT_DEPRECATED
84848   sqlite3_expired,
84849 #else
84850   0,
84851 #endif
84852   sqlite3_finalize,
84853   sqlite3_free,
84854   sqlite3_free_table,
84855   sqlite3_get_autocommit,
84856   sqlite3_get_auxdata,
84857   sqlite3_get_table,
84858   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
84859   sqlite3_interrupt,
84860   sqlite3_last_insert_rowid,
84861   sqlite3_libversion,
84862   sqlite3_libversion_number,
84863   sqlite3_malloc,
84864   sqlite3_mprintf,
84865   sqlite3_open,
84866   sqlite3_open16,
84867   sqlite3_prepare,
84868   sqlite3_prepare16,
84869   sqlite3_profile,
84870   sqlite3_progress_handler,
84871   sqlite3_realloc,
84872   sqlite3_reset,
84873   sqlite3_result_blob,
84874   sqlite3_result_double,
84875   sqlite3_result_error,
84876   sqlite3_result_error16,
84877   sqlite3_result_int,
84878   sqlite3_result_int64,
84879   sqlite3_result_null,
84880   sqlite3_result_text,
84881   sqlite3_result_text16,
84882   sqlite3_result_text16be,
84883   sqlite3_result_text16le,
84884   sqlite3_result_value,
84885   sqlite3_rollback_hook,
84886   sqlite3_set_authorizer,
84887   sqlite3_set_auxdata,
84888   sqlite3_snprintf,
84889   sqlite3_step,
84890   sqlite3_table_column_metadata,
84891 #ifndef SQLITE_OMIT_DEPRECATED
84892   sqlite3_thread_cleanup,
84893 #else
84894   0,
84895 #endif
84896   sqlite3_total_changes,
84897   sqlite3_trace,
84898 #ifndef SQLITE_OMIT_DEPRECATED
84899   sqlite3_transfer_bindings,
84900 #else
84901   0,
84902 #endif
84903   sqlite3_update_hook,
84904   sqlite3_user_data,
84905   sqlite3_value_blob,
84906   sqlite3_value_bytes,
84907   sqlite3_value_bytes16,
84908   sqlite3_value_double,
84909   sqlite3_value_int,
84910   sqlite3_value_int64,
84911   sqlite3_value_numeric_type,
84912   sqlite3_value_text,
84913   sqlite3_value_text16,
84914   sqlite3_value_text16be,
84915   sqlite3_value_text16le,
84916   sqlite3_value_type,
84917   sqlite3_vmprintf,
84918   /*
84919   ** The original API set ends here.  All extensions can call any
84920   ** of the APIs above provided that the pointer is not NULL.  But
84921   ** before calling APIs that follow, extension should check the
84922   ** sqlite3_libversion_number() to make sure they are dealing with
84923   ** a library that is new enough to support that API.
84924   *************************************************************************
84925   */
84926   sqlite3_overload_function,
84927
84928   /*
84929   ** Added after 3.3.13
84930   */
84931   sqlite3_prepare_v2,
84932   sqlite3_prepare16_v2,
84933   sqlite3_clear_bindings,
84934
84935   /*
84936   ** Added for 3.4.1
84937   */
84938   sqlite3_create_module_v2,
84939
84940   /*
84941   ** Added for 3.5.0
84942   */
84943   sqlite3_bind_zeroblob,
84944   sqlite3_blob_bytes,
84945   sqlite3_blob_close,
84946   sqlite3_blob_open,
84947   sqlite3_blob_read,
84948   sqlite3_blob_write,
84949   sqlite3_create_collation_v2,
84950   sqlite3_file_control,
84951   sqlite3_memory_highwater,
84952   sqlite3_memory_used,
84953 #ifdef SQLITE_MUTEX_OMIT
84954   0, 
84955   0, 
84956   0,
84957   0,
84958   0,
84959 #else
84960   sqlite3_mutex_alloc,
84961   sqlite3_mutex_enter,
84962   sqlite3_mutex_free,
84963   sqlite3_mutex_leave,
84964   sqlite3_mutex_try,
84965 #endif
84966   sqlite3_open_v2,
84967   sqlite3_release_memory,
84968   sqlite3_result_error_nomem,
84969   sqlite3_result_error_toobig,
84970   sqlite3_sleep,
84971   sqlite3_soft_heap_limit,
84972   sqlite3_vfs_find,
84973   sqlite3_vfs_register,
84974   sqlite3_vfs_unregister,
84975
84976   /*
84977   ** Added for 3.5.8
84978   */
84979   sqlite3_threadsafe,
84980   sqlite3_result_zeroblob,
84981   sqlite3_result_error_code,
84982   sqlite3_test_control,
84983   sqlite3_randomness,
84984   sqlite3_context_db_handle,
84985
84986   /*
84987   ** Added for 3.6.0
84988   */
84989   sqlite3_extended_result_codes,
84990   sqlite3_limit,
84991   sqlite3_next_stmt,
84992   sqlite3_sql,
84993   sqlite3_status,
84994
84995   /*
84996   ** Added for 3.7.4
84997   */
84998   sqlite3_backup_finish,
84999   sqlite3_backup_init,
85000   sqlite3_backup_pagecount,
85001   sqlite3_backup_remaining,
85002   sqlite3_backup_step,
85003 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
85004   sqlite3_compileoption_get,
85005   sqlite3_compileoption_used,
85006 #else
85007   0,
85008   0,
85009 #endif
85010   sqlite3_create_function_v2,
85011   sqlite3_db_config,
85012   sqlite3_db_mutex,
85013   sqlite3_db_status,
85014   sqlite3_extended_errcode,
85015   sqlite3_log,
85016   sqlite3_soft_heap_limit64,
85017   sqlite3_sourceid,
85018   sqlite3_stmt_status,
85019   sqlite3_strnicmp,
85020 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
85021   sqlite3_unlock_notify,
85022 #else
85023   0,
85024 #endif
85025 #ifndef SQLITE_OMIT_WAL
85026   sqlite3_wal_autocheckpoint,
85027   sqlite3_wal_checkpoint,
85028   sqlite3_wal_hook,
85029 #else
85030   0,
85031   0,
85032   0,
85033 #endif
85034 };
85035
85036 /*
85037 ** Attempt to load an SQLite extension library contained in the file
85038 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
85039 ** default entry point name (sqlite3_extension_init) is used.  Use
85040 ** of the default name is recommended.
85041 **
85042 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
85043 **
85044 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
85045 ** error message text.  The calling function should free this memory
85046 ** by calling sqlite3DbFree(db, ).
85047 */
85048 static int sqlite3LoadExtension(
85049   sqlite3 *db,          /* Load the extension into this database connection */
85050   const char *zFile,    /* Name of the shared library containing extension */
85051   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
85052   char **pzErrMsg       /* Put error message here if not 0 */
85053 ){
85054   sqlite3_vfs *pVfs = db->pVfs;
85055   void *handle;
85056   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
85057   char *zErrmsg = 0;
85058   void **aHandle;
85059   const int nMsg = 300;
85060
85061   if( pzErrMsg ) *pzErrMsg = 0;
85062
85063   /* Ticket #1863.  To avoid a creating security problems for older
85064   ** applications that relink against newer versions of SQLite, the
85065   ** ability to run load_extension is turned off by default.  One
85066   ** must call sqlite3_enable_load_extension() to turn on extension
85067   ** loading.  Otherwise you get the following error.
85068   */
85069   if( (db->flags & SQLITE_LoadExtension)==0 ){
85070     if( pzErrMsg ){
85071       *pzErrMsg = sqlite3_mprintf("not authorized");
85072     }
85073     return SQLITE_ERROR;
85074   }
85075
85076   if( zProc==0 ){
85077     zProc = "sqlite3_extension_init";
85078   }
85079
85080   handle = sqlite3OsDlOpen(pVfs, zFile);
85081   if( handle==0 ){
85082     if( pzErrMsg ){
85083       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
85084       if( zErrmsg ){
85085         sqlite3_snprintf(nMsg, zErrmsg, 
85086             "unable to open shared library [%s]", zFile);
85087         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
85088       }
85089     }
85090     return SQLITE_ERROR;
85091   }
85092   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
85093                    sqlite3OsDlSym(pVfs, handle, zProc);
85094   if( xInit==0 ){
85095     if( pzErrMsg ){
85096       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
85097       if( zErrmsg ){
85098         sqlite3_snprintf(nMsg, zErrmsg,
85099             "no entry point [%s] in shared library [%s]", zProc,zFile);
85100         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
85101       }
85102       sqlite3OsDlClose(pVfs, handle);
85103     }
85104     return SQLITE_ERROR;
85105   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
85106     if( pzErrMsg ){
85107       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
85108     }
85109     sqlite3_free(zErrmsg);
85110     sqlite3OsDlClose(pVfs, handle);
85111     return SQLITE_ERROR;
85112   }
85113
85114   /* Append the new shared library handle to the db->aExtension array. */
85115   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
85116   if( aHandle==0 ){
85117     return SQLITE_NOMEM;
85118   }
85119   if( db->nExtension>0 ){
85120     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
85121   }
85122   sqlite3DbFree(db, db->aExtension);
85123   db->aExtension = aHandle;
85124
85125   db->aExtension[db->nExtension++] = handle;
85126   return SQLITE_OK;
85127 }
85128 SQLITE_API int sqlite3_load_extension(
85129   sqlite3 *db,          /* Load the extension into this database connection */
85130   const char *zFile,    /* Name of the shared library containing extension */
85131   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
85132   char **pzErrMsg       /* Put error message here if not 0 */
85133 ){
85134   int rc;
85135   sqlite3_mutex_enter(db->mutex);
85136   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
85137   rc = sqlite3ApiExit(db, rc);
85138   sqlite3_mutex_leave(db->mutex);
85139   return rc;
85140 }
85141
85142 /*
85143 ** Call this routine when the database connection is closing in order
85144 ** to clean up loaded extensions
85145 */
85146 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
85147   int i;
85148   assert( sqlite3_mutex_held(db->mutex) );
85149   for(i=0; i<db->nExtension; i++){
85150     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
85151   }
85152   sqlite3DbFree(db, db->aExtension);
85153 }
85154
85155 /*
85156 ** Enable or disable extension loading.  Extension loading is disabled by
85157 ** default so as not to open security holes in older applications.
85158 */
85159 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
85160   sqlite3_mutex_enter(db->mutex);
85161   if( onoff ){
85162     db->flags |= SQLITE_LoadExtension;
85163   }else{
85164     db->flags &= ~SQLITE_LoadExtension;
85165   }
85166   sqlite3_mutex_leave(db->mutex);
85167   return SQLITE_OK;
85168 }
85169
85170 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
85171
85172 /*
85173 ** The auto-extension code added regardless of whether or not extension
85174 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
85175 ** code if regular extension loading is not available.  This is that
85176 ** dummy pointer.
85177 */
85178 #ifdef SQLITE_OMIT_LOAD_EXTENSION
85179 static const sqlite3_api_routines sqlite3Apis = { 0 };
85180 #endif
85181
85182
85183 /*
85184 ** The following object holds the list of automatically loaded
85185 ** extensions.
85186 **
85187 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
85188 ** mutex must be held while accessing this list.
85189 */
85190 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
85191 static SQLITE_WSD struct sqlite3AutoExtList {
85192   int nExt;              /* Number of entries in aExt[] */          
85193   void (**aExt)(void);   /* Pointers to the extension init functions */
85194 } sqlite3Autoext = { 0, 0 };
85195
85196 /* The "wsdAutoext" macro will resolve to the autoextension
85197 ** state vector.  If writable static data is unsupported on the target,
85198 ** we have to locate the state vector at run-time.  In the more common
85199 ** case where writable static data is supported, wsdStat can refer directly
85200 ** to the "sqlite3Autoext" state vector declared above.
85201 */
85202 #ifdef SQLITE_OMIT_WSD
85203 # define wsdAutoextInit \
85204   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
85205 # define wsdAutoext x[0]
85206 #else
85207 # define wsdAutoextInit
85208 # define wsdAutoext sqlite3Autoext
85209 #endif
85210
85211
85212 /*
85213 ** Register a statically linked extension that is automatically
85214 ** loaded by every new database connection.
85215 */
85216 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
85217   int rc = SQLITE_OK;
85218 #ifndef SQLITE_OMIT_AUTOINIT
85219   rc = sqlite3_initialize();
85220   if( rc ){
85221     return rc;
85222   }else
85223 #endif
85224   {
85225     int i;
85226 #if SQLITE_THREADSAFE
85227     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
85228 #endif
85229     wsdAutoextInit;
85230     sqlite3_mutex_enter(mutex);
85231     for(i=0; i<wsdAutoext.nExt; i++){
85232       if( wsdAutoext.aExt[i]==xInit ) break;
85233     }
85234     if( i==wsdAutoext.nExt ){
85235       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
85236       void (**aNew)(void);
85237       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
85238       if( aNew==0 ){
85239         rc = SQLITE_NOMEM;
85240       }else{
85241         wsdAutoext.aExt = aNew;
85242         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
85243         wsdAutoext.nExt++;
85244       }
85245     }
85246     sqlite3_mutex_leave(mutex);
85247     assert( (rc&0xff)==rc );
85248     return rc;
85249   }
85250 }
85251
85252 /*
85253 ** Reset the automatic extension loading mechanism.
85254 */
85255 SQLITE_API void sqlite3_reset_auto_extension(void){
85256 #ifndef SQLITE_OMIT_AUTOINIT
85257   if( sqlite3_initialize()==SQLITE_OK )
85258 #endif
85259   {
85260 #if SQLITE_THREADSAFE
85261     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
85262 #endif
85263     wsdAutoextInit;
85264     sqlite3_mutex_enter(mutex);
85265     sqlite3_free(wsdAutoext.aExt);
85266     wsdAutoext.aExt = 0;
85267     wsdAutoext.nExt = 0;
85268     sqlite3_mutex_leave(mutex);
85269   }
85270 }
85271
85272 /*
85273 ** Load all automatic extensions.
85274 **
85275 ** If anything goes wrong, set an error in the database connection.
85276 */
85277 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
85278   int i;
85279   int go = 1;
85280   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
85281
85282   wsdAutoextInit;
85283   if( wsdAutoext.nExt==0 ){
85284     /* Common case: early out without every having to acquire a mutex */
85285     return;
85286   }
85287   for(i=0; go; i++){
85288     char *zErrmsg;
85289 #if SQLITE_THREADSAFE
85290     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
85291 #endif
85292     sqlite3_mutex_enter(mutex);
85293     if( i>=wsdAutoext.nExt ){
85294       xInit = 0;
85295       go = 0;
85296     }else{
85297       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
85298               wsdAutoext.aExt[i];
85299     }
85300     sqlite3_mutex_leave(mutex);
85301     zErrmsg = 0;
85302     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
85303       sqlite3Error(db, SQLITE_ERROR,
85304             "automatic extension loading failed: %s", zErrmsg);
85305       go = 0;
85306     }
85307     sqlite3_free(zErrmsg);
85308   }
85309 }
85310
85311 /************** End of loadext.c *********************************************/
85312 /************** Begin file pragma.c ******************************************/
85313 /*
85314 ** 2003 April 6
85315 **
85316 ** The author disclaims copyright to this source code.  In place of
85317 ** a legal notice, here is a blessing:
85318 **
85319 **    May you do good and not evil.
85320 **    May you find forgiveness for yourself and forgive others.
85321 **    May you share freely, never taking more than you give.
85322 **
85323 *************************************************************************
85324 ** This file contains code used to implement the PRAGMA command.
85325 */
85326
85327 /* Ignore this whole file if pragmas are disabled
85328 */
85329 #if !defined(SQLITE_OMIT_PRAGMA)
85330
85331 /*
85332 ** Interpret the given string as a safety level.  Return 0 for OFF,
85333 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
85334 ** unrecognized string argument.
85335 **
85336 ** Note that the values returned are one less that the values that
85337 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
85338 ** to support legacy SQL code.  The safety level used to be boolean
85339 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
85340 */
85341 static u8 getSafetyLevel(const char *z){
85342                              /* 123456789 123456789 */
85343   static const char zText[] = "onoffalseyestruefull";
85344   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
85345   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
85346   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
85347   int i, n;
85348   if( sqlite3Isdigit(*z) ){
85349     return (u8)sqlite3Atoi(z);
85350   }
85351   n = sqlite3Strlen30(z);
85352   for(i=0; i<ArraySize(iLength); i++){
85353     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
85354       return iValue[i];
85355     }
85356   }
85357   return 1;
85358 }
85359
85360 /*
85361 ** Interpret the given string as a boolean value.
85362 */
85363 static u8 getBoolean(const char *z){
85364   return getSafetyLevel(z)&1;
85365 }
85366
85367 /*
85368 ** Interpret the given string as a locking mode value.
85369 */
85370 static int getLockingMode(const char *z){
85371   if( z ){
85372     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
85373     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
85374   }
85375   return PAGER_LOCKINGMODE_QUERY;
85376 }
85377
85378 #ifndef SQLITE_OMIT_AUTOVACUUM
85379 /*
85380 ** Interpret the given string as an auto-vacuum mode value.
85381 **
85382 ** The following strings, "none", "full" and "incremental" are 
85383 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
85384 */
85385 static int getAutoVacuum(const char *z){
85386   int i;
85387   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
85388   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
85389   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
85390   i = sqlite3Atoi(z);
85391   return (u8)((i>=0&&i<=2)?i:0);
85392 }
85393 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
85394
85395 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
85396 /*
85397 ** Interpret the given string as a temp db location. Return 1 for file
85398 ** backed temporary databases, 2 for the Red-Black tree in memory database
85399 ** and 0 to use the compile-time default.
85400 */
85401 static int getTempStore(const char *z){
85402   if( z[0]>='0' && z[0]<='2' ){
85403     return z[0] - '0';
85404   }else if( sqlite3StrICmp(z, "file")==0 ){
85405     return 1;
85406   }else if( sqlite3StrICmp(z, "memory")==0 ){
85407     return 2;
85408   }else{
85409     return 0;
85410   }
85411 }
85412 #endif /* SQLITE_PAGER_PRAGMAS */
85413
85414 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
85415 /*
85416 ** Invalidate temp storage, either when the temp storage is changed
85417 ** from default, or when 'file' and the temp_store_directory has changed
85418 */
85419 static int invalidateTempStorage(Parse *pParse){
85420   sqlite3 *db = pParse->db;
85421   if( db->aDb[1].pBt!=0 ){
85422     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
85423       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
85424         "from within a transaction");
85425       return SQLITE_ERROR;
85426     }
85427     sqlite3BtreeClose(db->aDb[1].pBt);
85428     db->aDb[1].pBt = 0;
85429     sqlite3ResetInternalSchema(db, 0);
85430   }
85431   return SQLITE_OK;
85432 }
85433 #endif /* SQLITE_PAGER_PRAGMAS */
85434
85435 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
85436 /*
85437 ** If the TEMP database is open, close it and mark the database schema
85438 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
85439 ** or DEFAULT_TEMP_STORE pragmas.
85440 */
85441 static int changeTempStorage(Parse *pParse, const char *zStorageType){
85442   int ts = getTempStore(zStorageType);
85443   sqlite3 *db = pParse->db;
85444   if( db->temp_store==ts ) return SQLITE_OK;
85445   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
85446     return SQLITE_ERROR;
85447   }
85448   db->temp_store = (u8)ts;
85449   return SQLITE_OK;
85450 }
85451 #endif /* SQLITE_PAGER_PRAGMAS */
85452
85453 /*
85454 ** Generate code to return a single integer value.
85455 */
85456 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
85457   Vdbe *v = sqlite3GetVdbe(pParse);
85458   int mem = ++pParse->nMem;
85459   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
85460   if( pI64 ){
85461     memcpy(pI64, &value, sizeof(value));
85462   }
85463   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
85464   sqlite3VdbeSetNumCols(v, 1);
85465   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
85466   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
85467 }
85468
85469 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
85470 /*
85471 ** Check to see if zRight and zLeft refer to a pragma that queries
85472 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
85473 ** Also, implement the pragma.
85474 */
85475 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
85476   static const struct sPragmaType {
85477     const char *zName;  /* Name of the pragma */
85478     int mask;           /* Mask for the db->flags value */
85479   } aPragma[] = {
85480     { "full_column_names",        SQLITE_FullColNames  },
85481     { "short_column_names",       SQLITE_ShortColNames },
85482     { "count_changes",            SQLITE_CountRows     },
85483     { "empty_result_callbacks",   SQLITE_NullCallback  },
85484     { "legacy_file_format",       SQLITE_LegacyFileFmt },
85485     { "fullfsync",                SQLITE_FullFSync     },
85486     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
85487     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
85488 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
85489     { "automatic_index",          SQLITE_AutoIndex     },
85490 #endif
85491 #ifdef SQLITE_DEBUG
85492     { "sql_trace",                SQLITE_SqlTrace      },
85493     { "vdbe_listing",             SQLITE_VdbeListing   },
85494     { "vdbe_trace",               SQLITE_VdbeTrace     },
85495 #endif
85496 #ifndef SQLITE_OMIT_CHECK
85497     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
85498 #endif
85499     /* The following is VERY experimental */
85500     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
85501     { "omit_readlock",            SQLITE_NoReadlock    },
85502
85503     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
85504     ** flag if there are any active statements. */
85505     { "read_uncommitted",         SQLITE_ReadUncommitted },
85506     { "recursive_triggers",       SQLITE_RecTriggers },
85507
85508     /* This flag may only be set if both foreign-key and trigger support
85509     ** are present in the build.  */
85510 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
85511     { "foreign_keys",             SQLITE_ForeignKeys },
85512 #endif
85513   };
85514   int i;
85515   const struct sPragmaType *p;
85516   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
85517     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
85518       sqlite3 *db = pParse->db;
85519       Vdbe *v;
85520       v = sqlite3GetVdbe(pParse);
85521       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
85522       if( ALWAYS(v) ){
85523         if( zRight==0 ){
85524           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
85525         }else{
85526           int mask = p->mask;          /* Mask of bits to set or clear. */
85527           if( db->autoCommit==0 ){
85528             /* Foreign key support may not be enabled or disabled while not
85529             ** in auto-commit mode.  */
85530             mask &= ~(SQLITE_ForeignKeys);
85531           }
85532
85533           if( getBoolean(zRight) ){
85534             db->flags |= mask;
85535           }else{
85536             db->flags &= ~mask;
85537           }
85538
85539           /* Many of the flag-pragmas modify the code generated by the SQL 
85540           ** compiler (eg. count_changes). So add an opcode to expire all
85541           ** compiled SQL statements after modifying a pragma value.
85542           */
85543           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
85544         }
85545       }
85546
85547       return 1;
85548     }
85549   }
85550   return 0;
85551 }
85552 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
85553
85554 /*
85555 ** Return a human-readable name for a constraint resolution action.
85556 */
85557 #ifndef SQLITE_OMIT_FOREIGN_KEY
85558 static const char *actionName(u8 action){
85559   const char *zName;
85560   switch( action ){
85561     case OE_SetNull:  zName = "SET NULL";        break;
85562     case OE_SetDflt:  zName = "SET DEFAULT";     break;
85563     case OE_Cascade:  zName = "CASCADE";         break;
85564     case OE_Restrict: zName = "RESTRICT";        break;
85565     default:          zName = "NO ACTION";  
85566                       assert( action==OE_None ); break;
85567   }
85568   return zName;
85569 }
85570 #endif
85571
85572
85573 /*
85574 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
85575 ** defined in pager.h. This function returns the associated lowercase
85576 ** journal-mode name.
85577 */
85578 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
85579   static char * const azModeName[] = {
85580     "delete", "persist", "off", "truncate", "memory"
85581 #ifndef SQLITE_OMIT_WAL
85582      , "wal"
85583 #endif
85584   };
85585   assert( PAGER_JOURNALMODE_DELETE==0 );
85586   assert( PAGER_JOURNALMODE_PERSIST==1 );
85587   assert( PAGER_JOURNALMODE_OFF==2 );
85588   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
85589   assert( PAGER_JOURNALMODE_MEMORY==4 );
85590   assert( PAGER_JOURNALMODE_WAL==5 );
85591   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
85592
85593   if( eMode==ArraySize(azModeName) ) return 0;
85594   return azModeName[eMode];
85595 }
85596
85597 /*
85598 ** Process a pragma statement.  
85599 **
85600 ** Pragmas are of this form:
85601 **
85602 **      PRAGMA [database.]id [= value]
85603 **
85604 ** The identifier might also be a string.  The value is a string, and
85605 ** identifier, or a number.  If minusFlag is true, then the value is
85606 ** a number that was preceded by a minus sign.
85607 **
85608 ** If the left side is "database.id" then pId1 is the database name
85609 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
85610 ** id and pId2 is any empty string.
85611 */
85612 SQLITE_PRIVATE void sqlite3Pragma(
85613   Parse *pParse, 
85614   Token *pId1,        /* First part of [database.]id field */
85615   Token *pId2,        /* Second part of [database.]id field, or NULL */
85616   Token *pValue,      /* Token for <value>, or NULL */
85617   int minusFlag       /* True if a '-' sign preceded <value> */
85618 ){
85619   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
85620   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
85621   const char *zDb = 0;   /* The database name */
85622   Token *pId;            /* Pointer to <id> token */
85623   int iDb;               /* Database index for <database> */
85624   sqlite3 *db = pParse->db;
85625   Db *pDb;
85626   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
85627   if( v==0 ) return;
85628   sqlite3VdbeRunOnlyOnce(v);
85629   pParse->nMem = 2;
85630
85631   /* Interpret the [database.] part of the pragma statement. iDb is the
85632   ** index of the database this pragma is being applied to in db.aDb[]. */
85633   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
85634   if( iDb<0 ) return;
85635   pDb = &db->aDb[iDb];
85636
85637   /* If the temp database has been explicitly named as part of the 
85638   ** pragma, make sure it is open. 
85639   */
85640   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
85641     return;
85642   }
85643
85644   zLeft = sqlite3NameFromToken(db, pId);
85645   if( !zLeft ) return;
85646   if( minusFlag ){
85647     zRight = sqlite3MPrintf(db, "-%T", pValue);
85648   }else{
85649     zRight = sqlite3NameFromToken(db, pValue);
85650   }
85651
85652   assert( pId2 );
85653   zDb = pId2->n>0 ? pDb->zName : 0;
85654   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
85655     goto pragma_out;
85656   }
85657  
85658 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
85659   /*
85660   **  PRAGMA [database.]default_cache_size
85661   **  PRAGMA [database.]default_cache_size=N
85662   **
85663   ** The first form reports the current persistent setting for the
85664   ** page cache size.  The value returned is the maximum number of
85665   ** pages in the page cache.  The second form sets both the current
85666   ** page cache size value and the persistent page cache size value
85667   ** stored in the database file.
85668   **
85669   ** Older versions of SQLite would set the default cache size to a
85670   ** negative number to indicate synchronous=OFF.  These days, synchronous
85671   ** is always on by default regardless of the sign of the default cache
85672   ** size.  But continue to take the absolute value of the default cache
85673   ** size of historical compatibility.
85674   */
85675   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
85676     static const VdbeOpList getCacheSize[] = {
85677       { OP_Transaction, 0, 0,        0},                         /* 0 */
85678       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
85679       { OP_IfPos,       1, 7,        0},
85680       { OP_Integer,     0, 2,        0},
85681       { OP_Subtract,    1, 2,        1},
85682       { OP_IfPos,       1, 7,        0},
85683       { OP_Integer,     0, 1,        0},                         /* 6 */
85684       { OP_ResultRow,   1, 1,        0},
85685     };
85686     int addr;
85687     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85688     sqlite3VdbeUsesBtree(v, iDb);
85689     if( !zRight ){
85690       sqlite3VdbeSetNumCols(v, 1);
85691       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
85692       pParse->nMem += 2;
85693       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
85694       sqlite3VdbeChangeP1(v, addr, iDb);
85695       sqlite3VdbeChangeP1(v, addr+1, iDb);
85696       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
85697     }else{
85698       int size = sqlite3Atoi(zRight);
85699       if( size<0 ) size = -size;
85700       sqlite3BeginWriteOperation(pParse, 0, iDb);
85701       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
85702       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
85703       pDb->pSchema->cache_size = size;
85704       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
85705     }
85706   }else
85707
85708   /*
85709   **  PRAGMA [database.]page_size
85710   **  PRAGMA [database.]page_size=N
85711   **
85712   ** The first form reports the current setting for the
85713   ** database page size in bytes.  The second form sets the
85714   ** database page size value.  The value can only be set if
85715   ** the database has not yet been created.
85716   */
85717   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
85718     Btree *pBt = pDb->pBt;
85719     assert( pBt!=0 );
85720     if( !zRight ){
85721       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
85722       returnSingleInt(pParse, "page_size", size);
85723     }else{
85724       /* Malloc may fail when setting the page-size, as there is an internal
85725       ** buffer that the pager module resizes using sqlite3_realloc().
85726       */
85727       db->nextPagesize = sqlite3Atoi(zRight);
85728       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
85729         db->mallocFailed = 1;
85730       }
85731     }
85732   }else
85733
85734   /*
85735   **  PRAGMA [database.]secure_delete
85736   **  PRAGMA [database.]secure_delete=ON/OFF
85737   **
85738   ** The first form reports the current setting for the
85739   ** secure_delete flag.  The second form changes the secure_delete
85740   ** flag setting and reports thenew value.
85741   */
85742   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
85743     Btree *pBt = pDb->pBt;
85744     int b = -1;
85745     assert( pBt!=0 );
85746     if( zRight ){
85747       b = getBoolean(zRight);
85748     }
85749     if( pId2->n==0 && b>=0 ){
85750       int ii;
85751       for(ii=0; ii<db->nDb; ii++){
85752         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
85753       }
85754     }
85755     b = sqlite3BtreeSecureDelete(pBt, b);
85756     returnSingleInt(pParse, "secure_delete", b);
85757   }else
85758
85759   /*
85760   **  PRAGMA [database.]max_page_count
85761   **  PRAGMA [database.]max_page_count=N
85762   **
85763   ** The first form reports the current setting for the
85764   ** maximum number of pages in the database file.  The 
85765   ** second form attempts to change this setting.  Both
85766   ** forms return the current setting.
85767   **
85768   **  PRAGMA [database.]page_count
85769   **
85770   ** Return the number of pages in the specified database.
85771   */
85772   if( sqlite3StrICmp(zLeft,"page_count")==0
85773    || sqlite3StrICmp(zLeft,"max_page_count")==0
85774   ){
85775     int iReg;
85776     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
85777     sqlite3CodeVerifySchema(pParse, iDb);
85778     iReg = ++pParse->nMem;
85779     if( zLeft[0]=='p' ){
85780       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
85781     }else{
85782       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
85783     }
85784     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
85785     sqlite3VdbeSetNumCols(v, 1);
85786     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
85787   }else
85788
85789   /*
85790   **  PRAGMA [database.]locking_mode
85791   **  PRAGMA [database.]locking_mode = (normal|exclusive)
85792   */
85793   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
85794     const char *zRet = "normal";
85795     int eMode = getLockingMode(zRight);
85796
85797     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
85798       /* Simple "PRAGMA locking_mode;" statement. This is a query for
85799       ** the current default locking mode (which may be different to
85800       ** the locking-mode of the main database).
85801       */
85802       eMode = db->dfltLockMode;
85803     }else{
85804       Pager *pPager;
85805       if( pId2->n==0 ){
85806         /* This indicates that no database name was specified as part
85807         ** of the PRAGMA command. In this case the locking-mode must be
85808         ** set on all attached databases, as well as the main db file.
85809         **
85810         ** Also, the sqlite3.dfltLockMode variable is set so that
85811         ** any subsequently attached databases also use the specified
85812         ** locking mode.
85813         */
85814         int ii;
85815         assert(pDb==&db->aDb[0]);
85816         for(ii=2; ii<db->nDb; ii++){
85817           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
85818           sqlite3PagerLockingMode(pPager, eMode);
85819         }
85820         db->dfltLockMode = (u8)eMode;
85821       }
85822       pPager = sqlite3BtreePager(pDb->pBt);
85823       eMode = sqlite3PagerLockingMode(pPager, eMode);
85824     }
85825
85826     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
85827     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
85828       zRet = "exclusive";
85829     }
85830     sqlite3VdbeSetNumCols(v, 1);
85831     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
85832     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
85833     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
85834   }else
85835
85836   /*
85837   **  PRAGMA [database.]journal_mode
85838   **  PRAGMA [database.]journal_mode =
85839   **                      (delete|persist|off|truncate|memory|wal|off)
85840   */
85841   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
85842     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
85843     int ii;           /* Loop counter */
85844
85845     /* Force the schema to be loaded on all databases.  This cases all
85846     ** database files to be opened and the journal_modes set. */
85847     if( sqlite3ReadSchema(pParse) ){
85848       goto pragma_out;
85849     }
85850
85851     sqlite3VdbeSetNumCols(v, 1);
85852     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
85853
85854     if( zRight==0 ){
85855       /* If there is no "=MODE" part of the pragma, do a query for the
85856       ** current mode */
85857       eMode = PAGER_JOURNALMODE_QUERY;
85858     }else{
85859       const char *zMode;
85860       int n = sqlite3Strlen30(zRight);
85861       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
85862         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
85863       }
85864       if( !zMode ){
85865         /* If the "=MODE" part does not match any known journal mode,
85866         ** then do a query */
85867         eMode = PAGER_JOURNALMODE_QUERY;
85868       }
85869     }
85870     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
85871       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
85872       iDb = 0;
85873       pId2->n = 1;
85874     }
85875     for(ii=db->nDb-1; ii>=0; ii--){
85876       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
85877         sqlite3VdbeUsesBtree(v, ii);
85878         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
85879       }
85880     }
85881     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
85882   }else
85883
85884   /*
85885   **  PRAGMA [database.]journal_size_limit
85886   **  PRAGMA [database.]journal_size_limit=N
85887   **
85888   ** Get or set the size limit on rollback journal files.
85889   */
85890   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
85891     Pager *pPager = sqlite3BtreePager(pDb->pBt);
85892     i64 iLimit = -2;
85893     if( zRight ){
85894       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
85895       if( iLimit<-1 ) iLimit = -1;
85896     }
85897     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
85898     returnSingleInt(pParse, "journal_size_limit", iLimit);
85899   }else
85900
85901 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
85902
85903   /*
85904   **  PRAGMA [database.]auto_vacuum
85905   **  PRAGMA [database.]auto_vacuum=N
85906   **
85907   ** Get or set the value of the database 'auto-vacuum' parameter.
85908   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
85909   */
85910 #ifndef SQLITE_OMIT_AUTOVACUUM
85911   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
85912     Btree *pBt = pDb->pBt;
85913     assert( pBt!=0 );
85914     if( sqlite3ReadSchema(pParse) ){
85915       goto pragma_out;
85916     }
85917     if( !zRight ){
85918       int auto_vacuum;
85919       if( ALWAYS(pBt) ){
85920          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
85921       }else{
85922          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
85923       }
85924       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
85925     }else{
85926       int eAuto = getAutoVacuum(zRight);
85927       assert( eAuto>=0 && eAuto<=2 );
85928       db->nextAutovac = (u8)eAuto;
85929       if( ALWAYS(eAuto>=0) ){
85930         /* Call SetAutoVacuum() to set initialize the internal auto and
85931         ** incr-vacuum flags. This is required in case this connection
85932         ** creates the database file. It is important that it is created
85933         ** as an auto-vacuum capable db.
85934         */
85935         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
85936         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
85937           /* When setting the auto_vacuum mode to either "full" or 
85938           ** "incremental", write the value of meta[6] in the database
85939           ** file. Before writing to meta[6], check that meta[3] indicates
85940           ** that this really is an auto-vacuum capable database.
85941           */
85942           static const VdbeOpList setMeta6[] = {
85943             { OP_Transaction,    0,         1,                 0},    /* 0 */
85944             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
85945             { OP_If,             1,         0,                 0},    /* 2 */
85946             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
85947             { OP_Integer,        0,         1,                 0},    /* 4 */
85948             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
85949           };
85950           int iAddr;
85951           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
85952           sqlite3VdbeChangeP1(v, iAddr, iDb);
85953           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
85954           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
85955           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
85956           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
85957           sqlite3VdbeUsesBtree(v, iDb);
85958         }
85959       }
85960     }
85961   }else
85962 #endif
85963
85964   /*
85965   **  PRAGMA [database.]incremental_vacuum(N)
85966   **
85967   ** Do N steps of incremental vacuuming on a database.
85968   */
85969 #ifndef SQLITE_OMIT_AUTOVACUUM
85970   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
85971     int iLimit, addr;
85972     if( sqlite3ReadSchema(pParse) ){
85973       goto pragma_out;
85974     }
85975     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
85976       iLimit = 0x7fffffff;
85977     }
85978     sqlite3BeginWriteOperation(pParse, 0, iDb);
85979     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
85980     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
85981     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
85982     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
85983     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
85984     sqlite3VdbeJumpHere(v, addr);
85985   }else
85986 #endif
85987
85988 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
85989   /*
85990   **  PRAGMA [database.]cache_size
85991   **  PRAGMA [database.]cache_size=N
85992   **
85993   ** The first form reports the current local setting for the
85994   ** page cache size.  The local setting can be different from
85995   ** the persistent cache size value that is stored in the database
85996   ** file itself.  The value returned is the maximum number of
85997   ** pages in the page cache.  The second form sets the local
85998   ** page cache size value.  It does not change the persistent
85999   ** cache size stored on the disk so the cache size will revert
86000   ** to its default value when the database is closed and reopened.
86001   ** N should be a positive integer.
86002   */
86003   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
86004     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86005     if( !zRight ){
86006       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
86007     }else{
86008       int size = sqlite3Atoi(zRight);
86009       if( size<0 ) size = -size;
86010       pDb->pSchema->cache_size = size;
86011       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
86012     }
86013   }else
86014
86015   /*
86016   **   PRAGMA temp_store
86017   **   PRAGMA temp_store = "default"|"memory"|"file"
86018   **
86019   ** Return or set the local value of the temp_store flag.  Changing
86020   ** the local value does not make changes to the disk file and the default
86021   ** value will be restored the next time the database is opened.
86022   **
86023   ** Note that it is possible for the library compile-time options to
86024   ** override this setting
86025   */
86026   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
86027     if( !zRight ){
86028       returnSingleInt(pParse, "temp_store", db->temp_store);
86029     }else{
86030       changeTempStorage(pParse, zRight);
86031     }
86032   }else
86033
86034   /*
86035   **   PRAGMA temp_store_directory
86036   **   PRAGMA temp_store_directory = ""|"directory_name"
86037   **
86038   ** Return or set the local value of the temp_store_directory flag.  Changing
86039   ** the value sets a specific directory to be used for temporary files.
86040   ** Setting to a null string reverts to the default temporary directory search.
86041   ** If temporary directory is changed, then invalidateTempStorage.
86042   **
86043   */
86044   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
86045     if( !zRight ){
86046       if( sqlite3_temp_directory ){
86047         sqlite3VdbeSetNumCols(v, 1);
86048         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
86049             "temp_store_directory", SQLITE_STATIC);
86050         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
86051         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86052       }
86053     }else{
86054 #ifndef SQLITE_OMIT_WSD
86055       if( zRight[0] ){
86056         int rc;
86057         int res;
86058         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
86059         if( rc!=SQLITE_OK || res==0 ){
86060           sqlite3ErrorMsg(pParse, "not a writable directory");
86061           goto pragma_out;
86062         }
86063       }
86064       if( SQLITE_TEMP_STORE==0
86065        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
86066        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
86067       ){
86068         invalidateTempStorage(pParse);
86069       }
86070       sqlite3_free(sqlite3_temp_directory);
86071       if( zRight[0] ){
86072         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
86073       }else{
86074         sqlite3_temp_directory = 0;
86075       }
86076 #endif /* SQLITE_OMIT_WSD */
86077     }
86078   }else
86079
86080 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
86081 #  if defined(__APPLE__)
86082 #    define SQLITE_ENABLE_LOCKING_STYLE 1
86083 #  else
86084 #    define SQLITE_ENABLE_LOCKING_STYLE 0
86085 #  endif
86086 #endif
86087 #if SQLITE_ENABLE_LOCKING_STYLE
86088   /*
86089    **   PRAGMA [database.]lock_proxy_file
86090    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
86091    **
86092    ** Return or set the value of the lock_proxy_file flag.  Changing
86093    ** the value sets a specific file to be used for database access locks.
86094    **
86095    */
86096   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
86097     if( !zRight ){
86098       Pager *pPager = sqlite3BtreePager(pDb->pBt);
86099       char *proxy_file_path = NULL;
86100       sqlite3_file *pFile = sqlite3PagerFile(pPager);
86101       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
86102                            &proxy_file_path);
86103       
86104       if( proxy_file_path ){
86105         sqlite3VdbeSetNumCols(v, 1);
86106         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
86107                               "lock_proxy_file", SQLITE_STATIC);
86108         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
86109         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86110       }
86111     }else{
86112       Pager *pPager = sqlite3BtreePager(pDb->pBt);
86113       sqlite3_file *pFile = sqlite3PagerFile(pPager);
86114       int res;
86115       if( zRight[0] ){
86116         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
86117                                      zRight);
86118       } else {
86119         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
86120                                      NULL);
86121       }
86122       if( res!=SQLITE_OK ){
86123         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
86124         goto pragma_out;
86125       }
86126     }
86127   }else
86128 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
86129     
86130   /*
86131   **   PRAGMA [database.]synchronous
86132   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
86133   **
86134   ** Return or set the local value of the synchronous flag.  Changing
86135   ** the local value does not make changes to the disk file and the
86136   ** default value will be restored the next time the database is
86137   ** opened.
86138   */
86139   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
86140     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86141     if( !zRight ){
86142       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
86143     }else{
86144       if( !db->autoCommit ){
86145         sqlite3ErrorMsg(pParse, 
86146             "Safety level may not be changed inside a transaction");
86147       }else{
86148         pDb->safety_level = getSafetyLevel(zRight)+1;
86149       }
86150     }
86151   }else
86152 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
86153
86154 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
86155   if( flagPragma(pParse, zLeft, zRight) ){
86156     /* The flagPragma() subroutine also generates any necessary code
86157     ** there is nothing more to do here */
86158   }else
86159 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
86160
86161 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
86162   /*
86163   **   PRAGMA table_info(<table>)
86164   **
86165   ** Return a single row for each column of the named table. The columns of
86166   ** the returned data set are:
86167   **
86168   ** cid:        Column id (numbered from left to right, starting at 0)
86169   ** name:       Column name
86170   ** type:       Column declaration type.
86171   ** notnull:    True if 'NOT NULL' is part of column declaration
86172   ** dflt_value: The default value for the column, if any.
86173   */
86174   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
86175     Table *pTab;
86176     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86177     pTab = sqlite3FindTable(db, zRight, zDb);
86178     if( pTab ){
86179       int i;
86180       int nHidden = 0;
86181       Column *pCol;
86182       sqlite3VdbeSetNumCols(v, 6);
86183       pParse->nMem = 6;
86184       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
86185       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
86186       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
86187       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
86188       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
86189       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
86190       sqlite3ViewGetColumnNames(pParse, pTab);
86191       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
86192         if( IsHiddenColumn(pCol) ){
86193           nHidden++;
86194           continue;
86195         }
86196         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
86197         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
86198         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
86199            pCol->zType ? pCol->zType : "", 0);
86200         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
86201         if( pCol->zDflt ){
86202           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
86203         }else{
86204           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
86205         }
86206         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
86207         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
86208       }
86209     }
86210   }else
86211
86212   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
86213     Index *pIdx;
86214     Table *pTab;
86215     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86216     pIdx = sqlite3FindIndex(db, zRight, zDb);
86217     if( pIdx ){
86218       int i;
86219       pTab = pIdx->pTable;
86220       sqlite3VdbeSetNumCols(v, 3);
86221       pParse->nMem = 3;
86222       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
86223       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
86224       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
86225       for(i=0; i<pIdx->nColumn; i++){
86226         int cnum = pIdx->aiColumn[i];
86227         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
86228         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
86229         assert( pTab->nCol>cnum );
86230         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
86231         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
86232       }
86233     }
86234   }else
86235
86236   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
86237     Index *pIdx;
86238     Table *pTab;
86239     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86240     pTab = sqlite3FindTable(db, zRight, zDb);
86241     if( pTab ){
86242       v = sqlite3GetVdbe(pParse);
86243       pIdx = pTab->pIndex;
86244       if( pIdx ){
86245         int i = 0; 
86246         sqlite3VdbeSetNumCols(v, 3);
86247         pParse->nMem = 3;
86248         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
86249         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
86250         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
86251         while(pIdx){
86252           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
86253           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
86254           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
86255           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
86256           ++i;
86257           pIdx = pIdx->pNext;
86258         }
86259       }
86260     }
86261   }else
86262
86263   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
86264     int i;
86265     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86266     sqlite3VdbeSetNumCols(v, 3);
86267     pParse->nMem = 3;
86268     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
86269     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
86270     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
86271     for(i=0; i<db->nDb; i++){
86272       if( db->aDb[i].pBt==0 ) continue;
86273       assert( db->aDb[i].zName!=0 );
86274       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
86275       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
86276       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
86277            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
86278       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
86279     }
86280   }else
86281
86282   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
86283     int i = 0;
86284     HashElem *p;
86285     sqlite3VdbeSetNumCols(v, 2);
86286     pParse->nMem = 2;
86287     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
86288     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
86289     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
86290       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
86291       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
86292       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
86293       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
86294     }
86295   }else
86296 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
86297
86298 #ifndef SQLITE_OMIT_FOREIGN_KEY
86299   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
86300     FKey *pFK;
86301     Table *pTab;
86302     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86303     pTab = sqlite3FindTable(db, zRight, zDb);
86304     if( pTab ){
86305       v = sqlite3GetVdbe(pParse);
86306       pFK = pTab->pFKey;
86307       if( pFK ){
86308         int i = 0; 
86309         sqlite3VdbeSetNumCols(v, 8);
86310         pParse->nMem = 8;
86311         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
86312         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
86313         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
86314         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
86315         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
86316         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
86317         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
86318         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
86319         while(pFK){
86320           int j;
86321           for(j=0; j<pFK->nCol; j++){
86322             char *zCol = pFK->aCol[j].zCol;
86323             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
86324             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
86325             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
86326             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
86327             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
86328             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
86329                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
86330             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
86331             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
86332             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
86333             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
86334             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
86335           }
86336           ++i;
86337           pFK = pFK->pNextFrom;
86338         }
86339       }
86340     }
86341   }else
86342 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
86343
86344 #ifndef NDEBUG
86345   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
86346     if( zRight ){
86347       if( getBoolean(zRight) ){
86348         sqlite3ParserTrace(stderr, "parser: ");
86349       }else{
86350         sqlite3ParserTrace(0, 0);
86351       }
86352     }
86353   }else
86354 #endif
86355
86356   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
86357   ** used will be case sensitive or not depending on the RHS.
86358   */
86359   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
86360     if( zRight ){
86361       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
86362     }
86363   }else
86364
86365 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
86366 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
86367 #endif
86368
86369 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
86370   /* Pragma "quick_check" is an experimental reduced version of 
86371   ** integrity_check designed to detect most database corruption
86372   ** without most of the overhead of a full integrity-check.
86373   */
86374   if( sqlite3StrICmp(zLeft, "integrity_check")==0
86375    || sqlite3StrICmp(zLeft, "quick_check")==0 
86376   ){
86377     int i, j, addr, mxErr;
86378
86379     /* Code that appears at the end of the integrity check.  If no error
86380     ** messages have been generated, output OK.  Otherwise output the
86381     ** error message
86382     */
86383     static const VdbeOpList endCode[] = {
86384       { OP_AddImm,      1, 0,        0},    /* 0 */
86385       { OP_IfNeg,       1, 0,        0},    /* 1 */
86386       { OP_String8,     0, 3,        0},    /* 2 */
86387       { OP_ResultRow,   3, 1,        0},
86388     };
86389
86390     int isQuick = (zLeft[0]=='q');
86391
86392     /* Initialize the VDBE program */
86393     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86394     pParse->nMem = 6;
86395     sqlite3VdbeSetNumCols(v, 1);
86396     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
86397
86398     /* Set the maximum error count */
86399     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
86400     if( zRight ){
86401       sqlite3GetInt32(zRight, &mxErr);
86402       if( mxErr<=0 ){
86403         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
86404       }
86405     }
86406     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
86407
86408     /* Do an integrity check on each database file */
86409     for(i=0; i<db->nDb; i++){
86410       HashElem *x;
86411       Hash *pTbls;
86412       int cnt = 0;
86413
86414       if( OMIT_TEMPDB && i==1 ) continue;
86415
86416       sqlite3CodeVerifySchema(pParse, i);
86417       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
86418       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
86419       sqlite3VdbeJumpHere(v, addr);
86420
86421       /* Do an integrity check of the B-Tree
86422       **
86423       ** Begin by filling registers 2, 3, ... with the root pages numbers
86424       ** for all tables and indices in the database.
86425       */
86426       pTbls = &db->aDb[i].pSchema->tblHash;
86427       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
86428         Table *pTab = sqliteHashData(x);
86429         Index *pIdx;
86430         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
86431         cnt++;
86432         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86433           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
86434           cnt++;
86435         }
86436       }
86437
86438       /* Make sure sufficient number of registers have been allocated */
86439       if( pParse->nMem < cnt+4 ){
86440         pParse->nMem = cnt+4;
86441       }
86442
86443       /* Do the b-tree integrity checks */
86444       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
86445       sqlite3VdbeChangeP5(v, (u8)i);
86446       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
86447       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
86448          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
86449          P4_DYNAMIC);
86450       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
86451       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
86452       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
86453       sqlite3VdbeJumpHere(v, addr);
86454
86455       /* Make sure all the indices are constructed correctly.
86456       */
86457       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
86458         Table *pTab = sqliteHashData(x);
86459         Index *pIdx;
86460         int loopTop;
86461
86462         if( pTab->pIndex==0 ) continue;
86463         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
86464         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
86465         sqlite3VdbeJumpHere(v, addr);
86466         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
86467         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
86468         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
86469         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
86470         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
86471           int jmp2;
86472           int r1;
86473           static const VdbeOpList idxErr[] = {
86474             { OP_AddImm,      1, -1,  0},
86475             { OP_String8,     0,  3,  0},    /* 1 */
86476             { OP_Rowid,       1,  4,  0},
86477             { OP_String8,     0,  5,  0},    /* 3 */
86478             { OP_String8,     0,  6,  0},    /* 4 */
86479             { OP_Concat,      4,  3,  3},
86480             { OP_Concat,      5,  3,  3},
86481             { OP_Concat,      6,  3,  3},
86482             { OP_ResultRow,   3,  1,  0},
86483             { OP_IfPos,       1,  0,  0},    /* 9 */
86484             { OP_Halt,        0,  0,  0},
86485           };
86486           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
86487           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
86488           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
86489           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
86490           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
86491           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
86492           sqlite3VdbeJumpHere(v, addr+9);
86493           sqlite3VdbeJumpHere(v, jmp2);
86494         }
86495         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
86496         sqlite3VdbeJumpHere(v, loopTop);
86497         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
86498           static const VdbeOpList cntIdx[] = {
86499              { OP_Integer,      0,  3,  0},
86500              { OP_Rewind,       0,  0,  0},  /* 1 */
86501              { OP_AddImm,       3,  1,  0},
86502              { OP_Next,         0,  0,  0},  /* 3 */
86503              { OP_Eq,           2,  0,  3},  /* 4 */
86504              { OP_AddImm,       1, -1,  0},
86505              { OP_String8,      0,  2,  0},  /* 6 */
86506              { OP_String8,      0,  3,  0},  /* 7 */
86507              { OP_Concat,       3,  2,  2},
86508              { OP_ResultRow,    2,  1,  0},
86509           };
86510           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
86511           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
86512           sqlite3VdbeJumpHere(v, addr);
86513           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
86514           sqlite3VdbeChangeP1(v, addr+1, j+2);
86515           sqlite3VdbeChangeP2(v, addr+1, addr+4);
86516           sqlite3VdbeChangeP1(v, addr+3, j+2);
86517           sqlite3VdbeChangeP2(v, addr+3, addr+2);
86518           sqlite3VdbeJumpHere(v, addr+4);
86519           sqlite3VdbeChangeP4(v, addr+6, 
86520                      "wrong # of entries in index ", P4_STATIC);
86521           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
86522         }
86523       } 
86524     }
86525     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
86526     sqlite3VdbeChangeP2(v, addr, -mxErr);
86527     sqlite3VdbeJumpHere(v, addr+1);
86528     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
86529   }else
86530 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
86531
86532 #ifndef SQLITE_OMIT_UTF16
86533   /*
86534   **   PRAGMA encoding
86535   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
86536   **
86537   ** In its first form, this pragma returns the encoding of the main
86538   ** database. If the database is not initialized, it is initialized now.
86539   **
86540   ** The second form of this pragma is a no-op if the main database file
86541   ** has not already been initialized. In this case it sets the default
86542   ** encoding that will be used for the main database file if a new file
86543   ** is created. If an existing main database file is opened, then the
86544   ** default text encoding for the existing database is used.
86545   ** 
86546   ** In all cases new databases created using the ATTACH command are
86547   ** created to use the same default text encoding as the main database. If
86548   ** the main database has not been initialized and/or created when ATTACH
86549   ** is executed, this is done before the ATTACH operation.
86550   **
86551   ** In the second form this pragma sets the text encoding to be used in
86552   ** new database files created using this database handle. It is only
86553   ** useful if invoked immediately after the main database i
86554   */
86555   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
86556     static const struct EncName {
86557       char *zName;
86558       u8 enc;
86559     } encnames[] = {
86560       { "UTF8",     SQLITE_UTF8        },
86561       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
86562       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
86563       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
86564       { "UTF16le",  SQLITE_UTF16LE     },
86565       { "UTF16be",  SQLITE_UTF16BE     },
86566       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
86567       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
86568       { 0, 0 }
86569     };
86570     const struct EncName *pEnc;
86571     if( !zRight ){    /* "PRAGMA encoding" */
86572       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86573       sqlite3VdbeSetNumCols(v, 1);
86574       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
86575       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
86576       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
86577       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
86578       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
86579       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
86580       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86581     }else{                        /* "PRAGMA encoding = XXX" */
86582       /* Only change the value of sqlite.enc if the database handle is not
86583       ** initialized. If the main database exists, the new sqlite.enc value
86584       ** will be overwritten when the schema is next loaded. If it does not
86585       ** already exists, it will be created to use the new encoding value.
86586       */
86587       if( 
86588         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
86589         DbHasProperty(db, 0, DB_Empty) 
86590       ){
86591         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
86592           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
86593             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
86594             break;
86595           }
86596         }
86597         if( !pEnc->zName ){
86598           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
86599         }
86600       }
86601     }
86602   }else
86603 #endif /* SQLITE_OMIT_UTF16 */
86604
86605 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
86606   /*
86607   **   PRAGMA [database.]schema_version
86608   **   PRAGMA [database.]schema_version = <integer>
86609   **
86610   **   PRAGMA [database.]user_version
86611   **   PRAGMA [database.]user_version = <integer>
86612   **
86613   ** The pragma's schema_version and user_version are used to set or get
86614   ** the value of the schema-version and user-version, respectively. Both
86615   ** the schema-version and the user-version are 32-bit signed integers
86616   ** stored in the database header.
86617   **
86618   ** The schema-cookie is usually only manipulated internally by SQLite. It
86619   ** is incremented by SQLite whenever the database schema is modified (by
86620   ** creating or dropping a table or index). The schema version is used by
86621   ** SQLite each time a query is executed to ensure that the internal cache
86622   ** of the schema used when compiling the SQL query matches the schema of
86623   ** the database against which the compiled query is actually executed.
86624   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
86625   ** the schema-version is potentially dangerous and may lead to program
86626   ** crashes or database corruption. Use with caution!
86627   **
86628   ** The user-version is not used internally by SQLite. It may be used by
86629   ** applications for any purpose.
86630   */
86631   if( sqlite3StrICmp(zLeft, "schema_version")==0 
86632    || sqlite3StrICmp(zLeft, "user_version")==0 
86633    || sqlite3StrICmp(zLeft, "freelist_count")==0 
86634   ){
86635     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
86636     sqlite3VdbeUsesBtree(v, iDb);
86637     switch( zLeft[0] ){
86638       case 'f': case 'F':
86639         iCookie = BTREE_FREE_PAGE_COUNT;
86640         break;
86641       case 's': case 'S':
86642         iCookie = BTREE_SCHEMA_VERSION;
86643         break;
86644       default:
86645         iCookie = BTREE_USER_VERSION;
86646         break;
86647     }
86648
86649     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
86650       /* Write the specified cookie value */
86651       static const VdbeOpList setCookie[] = {
86652         { OP_Transaction,    0,  1,  0},    /* 0 */
86653         { OP_Integer,        0,  1,  0},    /* 1 */
86654         { OP_SetCookie,      0,  0,  1},    /* 2 */
86655       };
86656       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
86657       sqlite3VdbeChangeP1(v, addr, iDb);
86658       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
86659       sqlite3VdbeChangeP1(v, addr+2, iDb);
86660       sqlite3VdbeChangeP2(v, addr+2, iCookie);
86661     }else{
86662       /* Read the specified cookie value */
86663       static const VdbeOpList readCookie[] = {
86664         { OP_Transaction,     0,  0,  0},    /* 0 */
86665         { OP_ReadCookie,      0,  1,  0},    /* 1 */
86666         { OP_ResultRow,       1,  1,  0}
86667       };
86668       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
86669       sqlite3VdbeChangeP1(v, addr, iDb);
86670       sqlite3VdbeChangeP1(v, addr+1, iDb);
86671       sqlite3VdbeChangeP3(v, addr+1, iCookie);
86672       sqlite3VdbeSetNumCols(v, 1);
86673       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
86674     }
86675   }else
86676 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
86677
86678 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86679   /*
86680   **   PRAGMA compile_options
86681   **
86682   ** Return the names of all compile-time options used in this build,
86683   ** one option per row.
86684   */
86685   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
86686     int i = 0;
86687     const char *zOpt;
86688     sqlite3VdbeSetNumCols(v, 1);
86689     pParse->nMem = 1;
86690     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
86691     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
86692       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
86693       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
86694     }
86695   }else
86696 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86697
86698 #ifndef SQLITE_OMIT_WAL
86699   /*
86700   **   PRAGMA [database.]wal_checkpoint
86701   **
86702   ** Checkpoint the database.
86703   */
86704   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
86705     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
86706     sqlite3VdbeAddOp3(v, OP_Checkpoint, pId2->z?iDb:SQLITE_MAX_ATTACHED, 0, 0);
86707   }else
86708
86709   /*
86710   **   PRAGMA wal_autocheckpoint
86711   **   PRAGMA wal_autocheckpoint = N
86712   **
86713   ** Configure a database connection to automatically checkpoint a database
86714   ** after accumulating N frames in the log. Or query for the current value
86715   ** of N.
86716   */
86717   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
86718     if( zRight ){
86719       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
86720     }
86721     returnSingleInt(pParse, "wal_autocheckpoint", 
86722        db->xWalCallback==sqlite3WalDefaultHook ? 
86723            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
86724   }else
86725 #endif
86726
86727 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
86728   /*
86729   ** Report the current state of file logs for all databases
86730   */
86731   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
86732     static const char *const azLockName[] = {
86733       "unlocked", "shared", "reserved", "pending", "exclusive"
86734     };
86735     int i;
86736     sqlite3VdbeSetNumCols(v, 2);
86737     pParse->nMem = 2;
86738     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
86739     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
86740     for(i=0; i<db->nDb; i++){
86741       Btree *pBt;
86742       Pager *pPager;
86743       const char *zState = "unknown";
86744       int j;
86745       if( db->aDb[i].zName==0 ) continue;
86746       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
86747       pBt = db->aDb[i].pBt;
86748       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
86749         zState = "closed";
86750       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
86751                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
86752          zState = azLockName[j];
86753       }
86754       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
86755       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
86756     }
86757
86758   }else
86759 #endif
86760
86761 #ifdef SQLITE_HAS_CODEC
86762   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
86763     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
86764   }else
86765   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
86766     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
86767   }else
86768   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
86769                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
86770     int i, h1, h2;
86771     char zKey[40];
86772     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
86773       h1 += 9*(1&(h1>>6));
86774       h2 += 9*(1&(h2>>6));
86775       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
86776     }
86777     if( (zLeft[3] & 0xf)==0xb ){
86778       sqlite3_key(db, zKey, i/2);
86779     }else{
86780       sqlite3_rekey(db, zKey, i/2);
86781     }
86782   }else
86783 #endif
86784 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
86785   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
86786 #ifdef SQLITE_HAS_CODEC
86787     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
86788       sqlite3_activate_see(&zRight[4]);
86789     }
86790 #endif
86791 #ifdef SQLITE_ENABLE_CEROD
86792     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
86793       sqlite3_activate_cerod(&zRight[6]);
86794     }
86795 #endif
86796   }else
86797 #endif
86798
86799  
86800   {/* Empty ELSE clause */}
86801
86802   /*
86803   ** Reset the safety level, in case the fullfsync flag or synchronous
86804   ** setting changed.
86805   */
86806 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
86807   if( db->autoCommit ){
86808     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
86809                (db->flags&SQLITE_FullFSync)!=0,
86810                (db->flags&SQLITE_CkptFullFSync)!=0);
86811   }
86812 #endif
86813 pragma_out:
86814   sqlite3DbFree(db, zLeft);
86815   sqlite3DbFree(db, zRight);
86816 }
86817
86818 #endif /* SQLITE_OMIT_PRAGMA */
86819
86820 /************** End of pragma.c **********************************************/
86821 /************** Begin file prepare.c *****************************************/
86822 /*
86823 ** 2005 May 25
86824 **
86825 ** The author disclaims copyright to this source code.  In place of
86826 ** a legal notice, here is a blessing:
86827 **
86828 **    May you do good and not evil.
86829 **    May you find forgiveness for yourself and forgive others.
86830 **    May you share freely, never taking more than you give.
86831 **
86832 *************************************************************************
86833 ** This file contains the implementation of the sqlite3_prepare()
86834 ** interface, and routines that contribute to loading the database schema
86835 ** from disk.
86836 */
86837
86838 /*
86839 ** Fill the InitData structure with an error message that indicates
86840 ** that the database is corrupt.
86841 */
86842 static void corruptSchema(
86843   InitData *pData,     /* Initialization context */
86844   const char *zObj,    /* Object being parsed at the point of error */
86845   const char *zExtra   /* Error information */
86846 ){
86847   sqlite3 *db = pData->db;
86848   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
86849     if( zObj==0 ) zObj = "?";
86850     sqlite3SetString(pData->pzErrMsg, db,
86851       "malformed database schema (%s)", zObj);
86852     if( zExtra ){
86853       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
86854                                  "%s - %s", *pData->pzErrMsg, zExtra);
86855     }
86856   }
86857   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
86858 }
86859
86860 /*
86861 ** This is the callback routine for the code that initializes the
86862 ** database.  See sqlite3Init() below for additional information.
86863 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
86864 **
86865 ** Each callback contains the following information:
86866 **
86867 **     argv[0] = name of thing being created
86868 **     argv[1] = root page number for table or index. 0 for trigger or view.
86869 **     argv[2] = SQL text for the CREATE statement.
86870 **
86871 */
86872 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
86873   InitData *pData = (InitData*)pInit;
86874   sqlite3 *db = pData->db;
86875   int iDb = pData->iDb;
86876
86877   assert( argc==3 );
86878   UNUSED_PARAMETER2(NotUsed, argc);
86879   assert( sqlite3_mutex_held(db->mutex) );
86880   DbClearProperty(db, iDb, DB_Empty);
86881   if( db->mallocFailed ){
86882     corruptSchema(pData, argv[0], 0);
86883     return 1;
86884   }
86885
86886   assert( iDb>=0 && iDb<db->nDb );
86887   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
86888   if( argv[1]==0 ){
86889     corruptSchema(pData, argv[0], 0);
86890   }else if( argv[2] && argv[2][0] ){
86891     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
86892     ** But because db->init.busy is set to 1, no VDBE code is generated
86893     ** or executed.  All the parser does is build the internal data
86894     ** structures that describe the table, index, or view.
86895     */
86896     int rc;
86897     sqlite3_stmt *pStmt;
86898     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
86899
86900     assert( db->init.busy );
86901     db->init.iDb = iDb;
86902     db->init.newTnum = sqlite3Atoi(argv[1]);
86903     db->init.orphanTrigger = 0;
86904     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
86905     rc = db->errCode;
86906     assert( (rc&0xFF)==(rcp&0xFF) );
86907     db->init.iDb = 0;
86908     if( SQLITE_OK!=rc ){
86909       if( db->init.orphanTrigger ){
86910         assert( iDb==1 );
86911       }else{
86912         pData->rc = rc;
86913         if( rc==SQLITE_NOMEM ){
86914           db->mallocFailed = 1;
86915         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
86916           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
86917         }
86918       }
86919     }
86920     sqlite3_finalize(pStmt);
86921   }else if( argv[0]==0 ){
86922     corruptSchema(pData, 0, 0);
86923   }else{
86924     /* If the SQL column is blank it means this is an index that
86925     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
86926     ** constraint for a CREATE TABLE.  The index should have already
86927     ** been created when we processed the CREATE TABLE.  All we have
86928     ** to do here is record the root page number for that index.
86929     */
86930     Index *pIndex;
86931     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
86932     if( pIndex==0 ){
86933       /* This can occur if there exists an index on a TEMP table which
86934       ** has the same name as another index on a permanent index.  Since
86935       ** the permanent table is hidden by the TEMP table, we can also
86936       ** safely ignore the index on the permanent table.
86937       */
86938       /* Do Nothing */;
86939     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
86940       corruptSchema(pData, argv[0], "invalid rootpage");
86941     }
86942   }
86943   return 0;
86944 }
86945
86946 /*
86947 ** Attempt to read the database schema and initialize internal
86948 ** data structures for a single database file.  The index of the
86949 ** database file is given by iDb.  iDb==0 is used for the main
86950 ** database.  iDb==1 should never be used.  iDb>=2 is used for
86951 ** auxiliary databases.  Return one of the SQLITE_ error codes to
86952 ** indicate success or failure.
86953 */
86954 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
86955   int rc;
86956   int i;
86957   int size;
86958   Table *pTab;
86959   Db *pDb;
86960   char const *azArg[4];
86961   int meta[5];
86962   InitData initData;
86963   char const *zMasterSchema;
86964   char const *zMasterName = SCHEMA_TABLE(iDb);
86965   int openedTransaction = 0;
86966
86967   /*
86968   ** The master database table has a structure like this
86969   */
86970   static const char master_schema[] = 
86971      "CREATE TABLE sqlite_master(\n"
86972      "  type text,\n"
86973      "  name text,\n"
86974      "  tbl_name text,\n"
86975      "  rootpage integer,\n"
86976      "  sql text\n"
86977      ")"
86978   ;
86979 #ifndef SQLITE_OMIT_TEMPDB
86980   static const char temp_master_schema[] = 
86981      "CREATE TEMP TABLE sqlite_temp_master(\n"
86982      "  type text,\n"
86983      "  name text,\n"
86984      "  tbl_name text,\n"
86985      "  rootpage integer,\n"
86986      "  sql text\n"
86987      ")"
86988   ;
86989 #else
86990   #define temp_master_schema 0
86991 #endif
86992
86993   assert( iDb>=0 && iDb<db->nDb );
86994   assert( db->aDb[iDb].pSchema );
86995   assert( sqlite3_mutex_held(db->mutex) );
86996   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
86997
86998   /* zMasterSchema and zInitScript are set to point at the master schema
86999   ** and initialisation script appropriate for the database being
87000   ** initialised. zMasterName is the name of the master table.
87001   */
87002   if( !OMIT_TEMPDB && iDb==1 ){
87003     zMasterSchema = temp_master_schema;
87004   }else{
87005     zMasterSchema = master_schema;
87006   }
87007   zMasterName = SCHEMA_TABLE(iDb);
87008
87009   /* Construct the schema tables.  */
87010   azArg[0] = zMasterName;
87011   azArg[1] = "1";
87012   azArg[2] = zMasterSchema;
87013   azArg[3] = 0;
87014   initData.db = db;
87015   initData.iDb = iDb;
87016   initData.rc = SQLITE_OK;
87017   initData.pzErrMsg = pzErrMsg;
87018   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
87019   if( initData.rc ){
87020     rc = initData.rc;
87021     goto error_out;
87022   }
87023   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
87024   if( ALWAYS(pTab) ){
87025     pTab->tabFlags |= TF_Readonly;
87026   }
87027
87028   /* Create a cursor to hold the database open
87029   */
87030   pDb = &db->aDb[iDb];
87031   if( pDb->pBt==0 ){
87032     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
87033       DbSetProperty(db, 1, DB_SchemaLoaded);
87034     }
87035     return SQLITE_OK;
87036   }
87037
87038   /* If there is not already a read-only (or read-write) transaction opened
87039   ** on the b-tree database, open one now. If a transaction is opened, it 
87040   ** will be closed before this function returns.  */
87041   sqlite3BtreeEnter(pDb->pBt);
87042   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
87043     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
87044     if( rc!=SQLITE_OK ){
87045       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
87046       goto initone_error_out;
87047     }
87048     openedTransaction = 1;
87049   }
87050
87051   /* Get the database meta information.
87052   **
87053   ** Meta values are as follows:
87054   **    meta[0]   Schema cookie.  Changes with each schema change.
87055   **    meta[1]   File format of schema layer.
87056   **    meta[2]   Size of the page cache.
87057   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
87058   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
87059   **    meta[5]   User version
87060   **    meta[6]   Incremental vacuum mode
87061   **    meta[7]   unused
87062   **    meta[8]   unused
87063   **    meta[9]   unused
87064   **
87065   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
87066   ** the possible values of meta[4].
87067   */
87068   for(i=0; i<ArraySize(meta); i++){
87069     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
87070   }
87071   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
87072
87073   /* If opening a non-empty database, check the text encoding. For the
87074   ** main database, set sqlite3.enc to the encoding of the main database.
87075   ** For an attached db, it is an error if the encoding is not the same
87076   ** as sqlite3.enc.
87077   */
87078   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
87079     if( iDb==0 ){
87080       u8 encoding;
87081       /* If opening the main database, set ENC(db). */
87082       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
87083       if( encoding==0 ) encoding = SQLITE_UTF8;
87084       ENC(db) = encoding;
87085       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
87086     }else{
87087       /* If opening an attached database, the encoding much match ENC(db) */
87088       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
87089         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
87090             " text encoding as main database");
87091         rc = SQLITE_ERROR;
87092         goto initone_error_out;
87093       }
87094     }
87095   }else{
87096     DbSetProperty(db, iDb, DB_Empty);
87097   }
87098   pDb->pSchema->enc = ENC(db);
87099
87100   if( pDb->pSchema->cache_size==0 ){
87101     size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
87102     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
87103     if( size<0 ) size = -size;
87104     pDb->pSchema->cache_size = size;
87105     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
87106   }
87107
87108   /*
87109   ** file_format==1    Version 3.0.0.
87110   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
87111   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
87112   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
87113   */
87114   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
87115   if( pDb->pSchema->file_format==0 ){
87116     pDb->pSchema->file_format = 1;
87117   }
87118   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
87119     sqlite3SetString(pzErrMsg, db, "unsupported file format");
87120     rc = SQLITE_ERROR;
87121     goto initone_error_out;
87122   }
87123
87124   /* Ticket #2804:  When we open a database in the newer file format,
87125   ** clear the legacy_file_format pragma flag so that a VACUUM will
87126   ** not downgrade the database and thus invalidate any descending
87127   ** indices that the user might have created.
87128   */
87129   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
87130     db->flags &= ~SQLITE_LegacyFileFmt;
87131   }
87132
87133   /* Read the schema information out of the schema tables
87134   */
87135   assert( db->init.busy );
87136   {
87137     char *zSql;
87138     zSql = sqlite3MPrintf(db, 
87139         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
87140         db->aDb[iDb].zName, zMasterName);
87141 #ifndef SQLITE_OMIT_AUTHORIZATION
87142     {
87143       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
87144       xAuth = db->xAuth;
87145       db->xAuth = 0;
87146 #endif
87147       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
87148 #ifndef SQLITE_OMIT_AUTHORIZATION
87149       db->xAuth = xAuth;
87150     }
87151 #endif
87152     if( rc==SQLITE_OK ) rc = initData.rc;
87153     sqlite3DbFree(db, zSql);
87154 #ifndef SQLITE_OMIT_ANALYZE
87155     if( rc==SQLITE_OK ){
87156       sqlite3AnalysisLoad(db, iDb);
87157     }
87158 #endif
87159   }
87160   if( db->mallocFailed ){
87161     rc = SQLITE_NOMEM;
87162     sqlite3ResetInternalSchema(db, 0);
87163   }
87164   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
87165     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
87166     ** the schema loaded, even if errors occurred. In this situation the 
87167     ** current sqlite3_prepare() operation will fail, but the following one
87168     ** will attempt to compile the supplied statement against whatever subset
87169     ** of the schema was loaded before the error occurred. The primary
87170     ** purpose of this is to allow access to the sqlite_master table
87171     ** even when its contents have been corrupted.
87172     */
87173     DbSetProperty(db, iDb, DB_SchemaLoaded);
87174     rc = SQLITE_OK;
87175   }
87176
87177   /* Jump here for an error that occurs after successfully allocating
87178   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
87179   ** before that point, jump to error_out.
87180   */
87181 initone_error_out:
87182   if( openedTransaction ){
87183     sqlite3BtreeCommit(pDb->pBt);
87184   }
87185   sqlite3BtreeLeave(pDb->pBt);
87186
87187 error_out:
87188   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
87189     db->mallocFailed = 1;
87190   }
87191   return rc;
87192 }
87193
87194 /*
87195 ** Initialize all database files - the main database file, the file
87196 ** used to store temporary tables, and any additional database files
87197 ** created using ATTACH statements.  Return a success code.  If an
87198 ** error occurs, write an error message into *pzErrMsg.
87199 **
87200 ** After a database is initialized, the DB_SchemaLoaded bit is set
87201 ** bit is set in the flags field of the Db structure. If the database
87202 ** file was of zero-length, then the DB_Empty flag is also set.
87203 */
87204 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
87205   int i, rc;
87206   int commit_internal = !(db->flags&SQLITE_InternChanges);
87207   
87208   assert( sqlite3_mutex_held(db->mutex) );
87209   rc = SQLITE_OK;
87210   db->init.busy = 1;
87211   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
87212     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
87213     rc = sqlite3InitOne(db, i, pzErrMsg);
87214     if( rc ){
87215       sqlite3ResetInternalSchema(db, i);
87216     }
87217   }
87218
87219   /* Once all the other databases have been initialised, load the schema
87220   ** for the TEMP database. This is loaded last, as the TEMP database
87221   ** schema may contain references to objects in other databases.
87222   */
87223 #ifndef SQLITE_OMIT_TEMPDB
87224   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
87225                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
87226     rc = sqlite3InitOne(db, 1, pzErrMsg);
87227     if( rc ){
87228       sqlite3ResetInternalSchema(db, 1);
87229     }
87230   }
87231 #endif
87232
87233   db->init.busy = 0;
87234   if( rc==SQLITE_OK && commit_internal ){
87235     sqlite3CommitInternalChanges(db);
87236   }
87237
87238   return rc; 
87239 }
87240
87241 /*
87242 ** This routine is a no-op if the database schema is already initialised.
87243 ** Otherwise, the schema is loaded. An error code is returned.
87244 */
87245 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
87246   int rc = SQLITE_OK;
87247   sqlite3 *db = pParse->db;
87248   assert( sqlite3_mutex_held(db->mutex) );
87249   if( !db->init.busy ){
87250     rc = sqlite3Init(db, &pParse->zErrMsg);
87251   }
87252   if( rc!=SQLITE_OK ){
87253     pParse->rc = rc;
87254     pParse->nErr++;
87255   }
87256   return rc;
87257 }
87258
87259
87260 /*
87261 ** Check schema cookies in all databases.  If any cookie is out
87262 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
87263 ** make no changes to pParse->rc.
87264 */
87265 static void schemaIsValid(Parse *pParse){
87266   sqlite3 *db = pParse->db;
87267   int iDb;
87268   int rc;
87269   int cookie;
87270
87271   assert( pParse->checkSchema );
87272   assert( sqlite3_mutex_held(db->mutex) );
87273   for(iDb=0; iDb<db->nDb; iDb++){
87274     int openedTransaction = 0;         /* True if a transaction is opened */
87275     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
87276     if( pBt==0 ) continue;
87277
87278     /* If there is not already a read-only (or read-write) transaction opened
87279     ** on the b-tree database, open one now. If a transaction is opened, it 
87280     ** will be closed immediately after reading the meta-value. */
87281     if( !sqlite3BtreeIsInReadTrans(pBt) ){
87282       rc = sqlite3BtreeBeginTrans(pBt, 0);
87283       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
87284         db->mallocFailed = 1;
87285       }
87286       if( rc!=SQLITE_OK ) return;
87287       openedTransaction = 1;
87288     }
87289
87290     /* Read the schema cookie from the database. If it does not match the 
87291     ** value stored as part of the in-memory schema representation,
87292     ** set Parse.rc to SQLITE_SCHEMA. */
87293     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
87294     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
87295       pParse->rc = SQLITE_SCHEMA;
87296     }
87297
87298     /* Close the transaction, if one was opened. */
87299     if( openedTransaction ){
87300       sqlite3BtreeCommit(pBt);
87301     }
87302   }
87303 }
87304
87305 /*
87306 ** Convert a schema pointer into the iDb index that indicates
87307 ** which database file in db->aDb[] the schema refers to.
87308 **
87309 ** If the same database is attached more than once, the first
87310 ** attached database is returned.
87311 */
87312 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
87313   int i = -1000000;
87314
87315   /* If pSchema is NULL, then return -1000000. This happens when code in 
87316   ** expr.c is trying to resolve a reference to a transient table (i.e. one
87317   ** created by a sub-select). In this case the return value of this 
87318   ** function should never be used.
87319   **
87320   ** We return -1000000 instead of the more usual -1 simply because using
87321   ** -1000000 as the incorrect index into db->aDb[] is much 
87322   ** more likely to cause a segfault than -1 (of course there are assert()
87323   ** statements too, but it never hurts to play the odds).
87324   */
87325   assert( sqlite3_mutex_held(db->mutex) );
87326   if( pSchema ){
87327     for(i=0; ALWAYS(i<db->nDb); i++){
87328       if( db->aDb[i].pSchema==pSchema ){
87329         break;
87330       }
87331     }
87332     assert( i>=0 && i<db->nDb );
87333   }
87334   return i;
87335 }
87336
87337 /*
87338 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
87339 */
87340 static int sqlite3Prepare(
87341   sqlite3 *db,              /* Database handle. */
87342   const char *zSql,         /* UTF-8 encoded SQL statement. */
87343   int nBytes,               /* Length of zSql in bytes. */
87344   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
87345   Vdbe *pReprepare,         /* VM being reprepared */
87346   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87347   const char **pzTail       /* OUT: End of parsed string */
87348 ){
87349   Parse *pParse;            /* Parsing context */
87350   char *zErrMsg = 0;        /* Error message */
87351   int rc = SQLITE_OK;       /* Result code */
87352   int i;                    /* Loop counter */
87353
87354   /* Allocate the parsing context */
87355   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
87356   if( pParse==0 ){
87357     rc = SQLITE_NOMEM;
87358     goto end_prepare;
87359   }
87360   pParse->pReprepare = pReprepare;
87361   assert( ppStmt && *ppStmt==0 );
87362   assert( !db->mallocFailed );
87363   assert( sqlite3_mutex_held(db->mutex) );
87364
87365   /* Check to verify that it is possible to get a read lock on all
87366   ** database schemas.  The inability to get a read lock indicates that
87367   ** some other database connection is holding a write-lock, which in
87368   ** turn means that the other connection has made uncommitted changes
87369   ** to the schema.
87370   **
87371   ** Were we to proceed and prepare the statement against the uncommitted
87372   ** schema changes and if those schema changes are subsequently rolled
87373   ** back and different changes are made in their place, then when this
87374   ** prepared statement goes to run the schema cookie would fail to detect
87375   ** the schema change.  Disaster would follow.
87376   **
87377   ** This thread is currently holding mutexes on all Btrees (because
87378   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
87379   ** is not possible for another thread to start a new schema change
87380   ** while this routine is running.  Hence, we do not need to hold 
87381   ** locks on the schema, we just need to make sure nobody else is 
87382   ** holding them.
87383   **
87384   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
87385   ** but it does *not* override schema lock detection, so this all still
87386   ** works even if READ_UNCOMMITTED is set.
87387   */
87388   for(i=0; i<db->nDb; i++) {
87389     Btree *pBt = db->aDb[i].pBt;
87390     if( pBt ){
87391       assert( sqlite3BtreeHoldsMutex(pBt) );
87392       rc = sqlite3BtreeSchemaLocked(pBt);
87393       if( rc ){
87394         const char *zDb = db->aDb[i].zName;
87395         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
87396         testcase( db->flags & SQLITE_ReadUncommitted );
87397         goto end_prepare;
87398       }
87399     }
87400   }
87401
87402   sqlite3VtabUnlockList(db);
87403
87404   pParse->db = db;
87405   pParse->nQueryLoop = (double)1;
87406   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
87407     char *zSqlCopy;
87408     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
87409     testcase( nBytes==mxLen );
87410     testcase( nBytes==mxLen+1 );
87411     if( nBytes>mxLen ){
87412       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
87413       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
87414       goto end_prepare;
87415     }
87416     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
87417     if( zSqlCopy ){
87418       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
87419       sqlite3DbFree(db, zSqlCopy);
87420       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
87421     }else{
87422       pParse->zTail = &zSql[nBytes];
87423     }
87424   }else{
87425     sqlite3RunParser(pParse, zSql, &zErrMsg);
87426   }
87427   assert( 1==(int)pParse->nQueryLoop );
87428
87429   if( db->mallocFailed ){
87430     pParse->rc = SQLITE_NOMEM;
87431   }
87432   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
87433   if( pParse->checkSchema ){
87434     schemaIsValid(pParse);
87435   }
87436   if( pParse->rc==SQLITE_SCHEMA ){
87437     sqlite3ResetInternalSchema(db, 0);
87438   }
87439   if( db->mallocFailed ){
87440     pParse->rc = SQLITE_NOMEM;
87441   }
87442   if( pzTail ){
87443     *pzTail = pParse->zTail;
87444   }
87445   rc = pParse->rc;
87446
87447 #ifndef SQLITE_OMIT_EXPLAIN
87448   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
87449     static const char * const azColName[] = {
87450        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
87451        "selectid", "order", "from", "detail"
87452     };
87453     int iFirst, mx;
87454     if( pParse->explain==2 ){
87455       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
87456       iFirst = 8;
87457       mx = 12;
87458     }else{
87459       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
87460       iFirst = 0;
87461       mx = 8;
87462     }
87463     for(i=iFirst; i<mx; i++){
87464       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
87465                             azColName[i], SQLITE_STATIC);
87466     }
87467   }
87468 #endif
87469
87470   assert( db->init.busy==0 || saveSqlFlag==0 );
87471   if( db->init.busy==0 ){
87472     Vdbe *pVdbe = pParse->pVdbe;
87473     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
87474   }
87475   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
87476     sqlite3VdbeFinalize(pParse->pVdbe);
87477     assert(!(*ppStmt));
87478   }else{
87479     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
87480   }
87481
87482   if( zErrMsg ){
87483     sqlite3Error(db, rc, "%s", zErrMsg);
87484     sqlite3DbFree(db, zErrMsg);
87485   }else{
87486     sqlite3Error(db, rc, 0);
87487   }
87488
87489   /* Delete any TriggerPrg structures allocated while parsing this statement. */
87490   while( pParse->pTriggerPrg ){
87491     TriggerPrg *pT = pParse->pTriggerPrg;
87492     pParse->pTriggerPrg = pT->pNext;
87493     sqlite3DbFree(db, pT);
87494   }
87495
87496 end_prepare:
87497
87498   sqlite3StackFree(db, pParse);
87499   rc = sqlite3ApiExit(db, rc);
87500   assert( (rc&db->errMask)==rc );
87501   return rc;
87502 }
87503 static int sqlite3LockAndPrepare(
87504   sqlite3 *db,              /* Database handle. */
87505   const char *zSql,         /* UTF-8 encoded SQL statement. */
87506   int nBytes,               /* Length of zSql in bytes. */
87507   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
87508   Vdbe *pOld,               /* VM being reprepared */
87509   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87510   const char **pzTail       /* OUT: End of parsed string */
87511 ){
87512   int rc;
87513   assert( ppStmt!=0 );
87514   *ppStmt = 0;
87515   if( !sqlite3SafetyCheckOk(db) ){
87516     return SQLITE_MISUSE_BKPT;
87517   }
87518   sqlite3_mutex_enter(db->mutex);
87519   sqlite3BtreeEnterAll(db);
87520   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
87521   if( rc==SQLITE_SCHEMA ){
87522     sqlite3_finalize(*ppStmt);
87523     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
87524   }
87525   sqlite3BtreeLeaveAll(db);
87526   sqlite3_mutex_leave(db->mutex);
87527   return rc;
87528 }
87529
87530 /*
87531 ** Rerun the compilation of a statement after a schema change.
87532 **
87533 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
87534 ** if the statement cannot be recompiled because another connection has
87535 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
87536 ** occurs, return SQLITE_SCHEMA.
87537 */
87538 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
87539   int rc;
87540   sqlite3_stmt *pNew;
87541   const char *zSql;
87542   sqlite3 *db;
87543
87544   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
87545   zSql = sqlite3_sql((sqlite3_stmt *)p);
87546   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
87547   db = sqlite3VdbeDb(p);
87548   assert( sqlite3_mutex_held(db->mutex) );
87549   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
87550   if( rc ){
87551     if( rc==SQLITE_NOMEM ){
87552       db->mallocFailed = 1;
87553     }
87554     assert( pNew==0 );
87555     return rc;
87556   }else{
87557     assert( pNew!=0 );
87558   }
87559   sqlite3VdbeSwap((Vdbe*)pNew, p);
87560   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
87561   sqlite3VdbeResetStepResult((Vdbe*)pNew);
87562   sqlite3VdbeFinalize((Vdbe*)pNew);
87563   return SQLITE_OK;
87564 }
87565
87566
87567 /*
87568 ** Two versions of the official API.  Legacy and new use.  In the legacy
87569 ** version, the original SQL text is not saved in the prepared statement
87570 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
87571 ** sqlite3_step().  In the new version, the original SQL text is retained
87572 ** and the statement is automatically recompiled if an schema change
87573 ** occurs.
87574 */
87575 SQLITE_API int sqlite3_prepare(
87576   sqlite3 *db,              /* Database handle. */
87577   const char *zSql,         /* UTF-8 encoded SQL statement. */
87578   int nBytes,               /* Length of zSql in bytes. */
87579   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87580   const char **pzTail       /* OUT: End of parsed string */
87581 ){
87582   int rc;
87583   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
87584   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
87585   return rc;
87586 }
87587 SQLITE_API int sqlite3_prepare_v2(
87588   sqlite3 *db,              /* Database handle. */
87589   const char *zSql,         /* UTF-8 encoded SQL statement. */
87590   int nBytes,               /* Length of zSql in bytes. */
87591   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87592   const char **pzTail       /* OUT: End of parsed string */
87593 ){
87594   int rc;
87595   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
87596   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
87597   return rc;
87598 }
87599
87600
87601 #ifndef SQLITE_OMIT_UTF16
87602 /*
87603 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
87604 */
87605 static int sqlite3Prepare16(
87606   sqlite3 *db,              /* Database handle. */ 
87607   const void *zSql,         /* UTF-8 encoded SQL statement. */
87608   int nBytes,               /* Length of zSql in bytes. */
87609   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
87610   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87611   const void **pzTail       /* OUT: End of parsed string */
87612 ){
87613   /* This function currently works by first transforming the UTF-16
87614   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
87615   ** tricky bit is figuring out the pointer to return in *pzTail.
87616   */
87617   char *zSql8;
87618   const char *zTail8 = 0;
87619   int rc = SQLITE_OK;
87620
87621   assert( ppStmt );
87622   *ppStmt = 0;
87623   if( !sqlite3SafetyCheckOk(db) ){
87624     return SQLITE_MISUSE_BKPT;
87625   }
87626   sqlite3_mutex_enter(db->mutex);
87627   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
87628   if( zSql8 ){
87629     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
87630   }
87631
87632   if( zTail8 && pzTail ){
87633     /* If sqlite3_prepare returns a tail pointer, we calculate the
87634     ** equivalent pointer into the UTF-16 string by counting the unicode
87635     ** characters between zSql8 and zTail8, and then returning a pointer
87636     ** the same number of characters into the UTF-16 string.
87637     */
87638     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
87639     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
87640   }
87641   sqlite3DbFree(db, zSql8); 
87642   rc = sqlite3ApiExit(db, rc);
87643   sqlite3_mutex_leave(db->mutex);
87644   return rc;
87645 }
87646
87647 /*
87648 ** Two versions of the official API.  Legacy and new use.  In the legacy
87649 ** version, the original SQL text is not saved in the prepared statement
87650 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
87651 ** sqlite3_step().  In the new version, the original SQL text is retained
87652 ** and the statement is automatically recompiled if an schema change
87653 ** occurs.
87654 */
87655 SQLITE_API int sqlite3_prepare16(
87656   sqlite3 *db,              /* Database handle. */ 
87657   const void *zSql,         /* UTF-8 encoded SQL statement. */
87658   int nBytes,               /* Length of zSql in bytes. */
87659   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87660   const void **pzTail       /* OUT: End of parsed string */
87661 ){
87662   int rc;
87663   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
87664   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
87665   return rc;
87666 }
87667 SQLITE_API int sqlite3_prepare16_v2(
87668   sqlite3 *db,              /* Database handle. */ 
87669   const void *zSql,         /* UTF-8 encoded SQL statement. */
87670   int nBytes,               /* Length of zSql in bytes. */
87671   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
87672   const void **pzTail       /* OUT: End of parsed string */
87673 ){
87674   int rc;
87675   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
87676   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
87677   return rc;
87678 }
87679
87680 #endif /* SQLITE_OMIT_UTF16 */
87681
87682 /************** End of prepare.c *********************************************/
87683 /************** Begin file select.c ******************************************/
87684 /*
87685 ** 2001 September 15
87686 **
87687 ** The author disclaims copyright to this source code.  In place of
87688 ** a legal notice, here is a blessing:
87689 **
87690 **    May you do good and not evil.
87691 **    May you find forgiveness for yourself and forgive others.
87692 **    May you share freely, never taking more than you give.
87693 **
87694 *************************************************************************
87695 ** This file contains C code routines that are called by the parser
87696 ** to handle SELECT statements in SQLite.
87697 */
87698
87699
87700 /*
87701 ** Delete all the content of a Select structure but do not deallocate
87702 ** the select structure itself.
87703 */
87704 static void clearSelect(sqlite3 *db, Select *p){
87705   sqlite3ExprListDelete(db, p->pEList);
87706   sqlite3SrcListDelete(db, p->pSrc);
87707   sqlite3ExprDelete(db, p->pWhere);
87708   sqlite3ExprListDelete(db, p->pGroupBy);
87709   sqlite3ExprDelete(db, p->pHaving);
87710   sqlite3ExprListDelete(db, p->pOrderBy);
87711   sqlite3SelectDelete(db, p->pPrior);
87712   sqlite3ExprDelete(db, p->pLimit);
87713   sqlite3ExprDelete(db, p->pOffset);
87714 }
87715
87716 /*
87717 ** Initialize a SelectDest structure.
87718 */
87719 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
87720   pDest->eDest = (u8)eDest;
87721   pDest->iParm = iParm;
87722   pDest->affinity = 0;
87723   pDest->iMem = 0;
87724   pDest->nMem = 0;
87725 }
87726
87727
87728 /*
87729 ** Allocate a new Select structure and return a pointer to that
87730 ** structure.
87731 */
87732 SQLITE_PRIVATE Select *sqlite3SelectNew(
87733   Parse *pParse,        /* Parsing context */
87734   ExprList *pEList,     /* which columns to include in the result */
87735   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
87736   Expr *pWhere,         /* the WHERE clause */
87737   ExprList *pGroupBy,   /* the GROUP BY clause */
87738   Expr *pHaving,        /* the HAVING clause */
87739   ExprList *pOrderBy,   /* the ORDER BY clause */
87740   int isDistinct,       /* true if the DISTINCT keyword is present */
87741   Expr *pLimit,         /* LIMIT value.  NULL means not used */
87742   Expr *pOffset         /* OFFSET value.  NULL means no offset */
87743 ){
87744   Select *pNew;
87745   Select standin;
87746   sqlite3 *db = pParse->db;
87747   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
87748   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
87749   if( pNew==0 ){
87750     pNew = &standin;
87751     memset(pNew, 0, sizeof(*pNew));
87752   }
87753   if( pEList==0 ){
87754     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
87755   }
87756   pNew->pEList = pEList;
87757   pNew->pSrc = pSrc;
87758   pNew->pWhere = pWhere;
87759   pNew->pGroupBy = pGroupBy;
87760   pNew->pHaving = pHaving;
87761   pNew->pOrderBy = pOrderBy;
87762   pNew->selFlags = isDistinct ? SF_Distinct : 0;
87763   pNew->op = TK_SELECT;
87764   pNew->pLimit = pLimit;
87765   pNew->pOffset = pOffset;
87766   assert( pOffset==0 || pLimit!=0 );
87767   pNew->addrOpenEphm[0] = -1;
87768   pNew->addrOpenEphm[1] = -1;
87769   pNew->addrOpenEphm[2] = -1;
87770   if( db->mallocFailed ) {
87771     clearSelect(db, pNew);
87772     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
87773     pNew = 0;
87774   }
87775   return pNew;
87776 }
87777
87778 /*
87779 ** Delete the given Select structure and all of its substructures.
87780 */
87781 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
87782   if( p ){
87783     clearSelect(db, p);
87784     sqlite3DbFree(db, p);
87785   }
87786 }
87787
87788 /*
87789 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
87790 ** type of join.  Return an integer constant that expresses that type
87791 ** in terms of the following bit values:
87792 **
87793 **     JT_INNER
87794 **     JT_CROSS
87795 **     JT_OUTER
87796 **     JT_NATURAL
87797 **     JT_LEFT
87798 **     JT_RIGHT
87799 **
87800 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
87801 **
87802 ** If an illegal or unsupported join type is seen, then still return
87803 ** a join type, but put an error in the pParse structure.
87804 */
87805 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
87806   int jointype = 0;
87807   Token *apAll[3];
87808   Token *p;
87809                              /*   0123456789 123456789 123456789 123 */
87810   static const char zKeyText[] = "naturaleftouterightfullinnercross";
87811   static const struct {
87812     u8 i;        /* Beginning of keyword text in zKeyText[] */
87813     u8 nChar;    /* Length of the keyword in characters */
87814     u8 code;     /* Join type mask */
87815   } aKeyword[] = {
87816     /* natural */ { 0,  7, JT_NATURAL                },
87817     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
87818     /* outer   */ { 10, 5, JT_OUTER                  },
87819     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
87820     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
87821     /* inner   */ { 23, 5, JT_INNER                  },
87822     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
87823   };
87824   int i, j;
87825   apAll[0] = pA;
87826   apAll[1] = pB;
87827   apAll[2] = pC;
87828   for(i=0; i<3 && apAll[i]; i++){
87829     p = apAll[i];
87830     for(j=0; j<ArraySize(aKeyword); j++){
87831       if( p->n==aKeyword[j].nChar 
87832           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
87833         jointype |= aKeyword[j].code;
87834         break;
87835       }
87836     }
87837     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
87838     if( j>=ArraySize(aKeyword) ){
87839       jointype |= JT_ERROR;
87840       break;
87841     }
87842   }
87843   if(
87844      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
87845      (jointype & JT_ERROR)!=0
87846   ){
87847     const char *zSp = " ";
87848     assert( pB!=0 );
87849     if( pC==0 ){ zSp++; }
87850     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
87851        "%T %T%s%T", pA, pB, zSp, pC);
87852     jointype = JT_INNER;
87853   }else if( (jointype & JT_OUTER)!=0 
87854          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
87855     sqlite3ErrorMsg(pParse, 
87856       "RIGHT and FULL OUTER JOINs are not currently supported");
87857     jointype = JT_INNER;
87858   }
87859   return jointype;
87860 }
87861
87862 /*
87863 ** Return the index of a column in a table.  Return -1 if the column
87864 ** is not contained in the table.
87865 */
87866 static int columnIndex(Table *pTab, const char *zCol){
87867   int i;
87868   for(i=0; i<pTab->nCol; i++){
87869     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
87870   }
87871   return -1;
87872 }
87873
87874 /*
87875 ** Search the first N tables in pSrc, from left to right, looking for a
87876 ** table that has a column named zCol.  
87877 **
87878 ** When found, set *piTab and *piCol to the table index and column index
87879 ** of the matching column and return TRUE.
87880 **
87881 ** If not found, return FALSE.
87882 */
87883 static int tableAndColumnIndex(
87884   SrcList *pSrc,       /* Array of tables to search */
87885   int N,               /* Number of tables in pSrc->a[] to search */
87886   const char *zCol,    /* Name of the column we are looking for */
87887   int *piTab,          /* Write index of pSrc->a[] here */
87888   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
87889 ){
87890   int i;               /* For looping over tables in pSrc */
87891   int iCol;            /* Index of column matching zCol */
87892
87893   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
87894   for(i=0; i<N; i++){
87895     iCol = columnIndex(pSrc->a[i].pTab, zCol);
87896     if( iCol>=0 ){
87897       if( piTab ){
87898         *piTab = i;
87899         *piCol = iCol;
87900       }
87901       return 1;
87902     }
87903   }
87904   return 0;
87905 }
87906
87907 /*
87908 ** This function is used to add terms implied by JOIN syntax to the
87909 ** WHERE clause expression of a SELECT statement. The new term, which
87910 ** is ANDed with the existing WHERE clause, is of the form:
87911 **
87912 **    (tab1.col1 = tab2.col2)
87913 **
87914 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
87915 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
87916 ** column iColRight of tab2.
87917 */
87918 static void addWhereTerm(
87919   Parse *pParse,                  /* Parsing context */
87920   SrcList *pSrc,                  /* List of tables in FROM clause */
87921   int iLeft,                      /* Index of first table to join in pSrc */
87922   int iColLeft,                   /* Index of column in first table */
87923   int iRight,                     /* Index of second table in pSrc */
87924   int iColRight,                  /* Index of column in second table */
87925   int isOuterJoin,                /* True if this is an OUTER join */
87926   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
87927 ){
87928   sqlite3 *db = pParse->db;
87929   Expr *pE1;
87930   Expr *pE2;
87931   Expr *pEq;
87932
87933   assert( iLeft<iRight );
87934   assert( pSrc->nSrc>iRight );
87935   assert( pSrc->a[iLeft].pTab );
87936   assert( pSrc->a[iRight].pTab );
87937
87938   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
87939   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
87940
87941   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
87942   if( pEq && isOuterJoin ){
87943     ExprSetProperty(pEq, EP_FromJoin);
87944     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
87945     ExprSetIrreducible(pEq);
87946     pEq->iRightJoinTable = (i16)pE2->iTable;
87947   }
87948   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
87949 }
87950
87951 /*
87952 ** Set the EP_FromJoin property on all terms of the given expression.
87953 ** And set the Expr.iRightJoinTable to iTable for every term in the
87954 ** expression.
87955 **
87956 ** The EP_FromJoin property is used on terms of an expression to tell
87957 ** the LEFT OUTER JOIN processing logic that this term is part of the
87958 ** join restriction specified in the ON or USING clause and not a part
87959 ** of the more general WHERE clause.  These terms are moved over to the
87960 ** WHERE clause during join processing but we need to remember that they
87961 ** originated in the ON or USING clause.
87962 **
87963 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
87964 ** expression depends on table iRightJoinTable even if that table is not
87965 ** explicitly mentioned in the expression.  That information is needed
87966 ** for cases like this:
87967 **
87968 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
87969 **
87970 ** The where clause needs to defer the handling of the t1.x=5
87971 ** term until after the t2 loop of the join.  In that way, a
87972 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
87973 ** defer the handling of t1.x=5, it will be processed immediately
87974 ** after the t1 loop and rows with t1.x!=5 will never appear in
87975 ** the output, which is incorrect.
87976 */
87977 static void setJoinExpr(Expr *p, int iTable){
87978   while( p ){
87979     ExprSetProperty(p, EP_FromJoin);
87980     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
87981     ExprSetIrreducible(p);
87982     p->iRightJoinTable = (i16)iTable;
87983     setJoinExpr(p->pLeft, iTable);
87984     p = p->pRight;
87985   } 
87986 }
87987
87988 /*
87989 ** This routine processes the join information for a SELECT statement.
87990 ** ON and USING clauses are converted into extra terms of the WHERE clause.
87991 ** NATURAL joins also create extra WHERE clause terms.
87992 **
87993 ** The terms of a FROM clause are contained in the Select.pSrc structure.
87994 ** The left most table is the first entry in Select.pSrc.  The right-most
87995 ** table is the last entry.  The join operator is held in the entry to
87996 ** the left.  Thus entry 0 contains the join operator for the join between
87997 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
87998 ** also attached to the left entry.
87999 **
88000 ** This routine returns the number of errors encountered.
88001 */
88002 static int sqliteProcessJoin(Parse *pParse, Select *p){
88003   SrcList *pSrc;                  /* All tables in the FROM clause */
88004   int i, j;                       /* Loop counters */
88005   struct SrcList_item *pLeft;     /* Left table being joined */
88006   struct SrcList_item *pRight;    /* Right table being joined */
88007
88008   pSrc = p->pSrc;
88009   pLeft = &pSrc->a[0];
88010   pRight = &pLeft[1];
88011   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
88012     Table *pLeftTab = pLeft->pTab;
88013     Table *pRightTab = pRight->pTab;
88014     int isOuter;
88015
88016     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
88017     isOuter = (pRight->jointype & JT_OUTER)!=0;
88018
88019     /* When the NATURAL keyword is present, add WHERE clause terms for
88020     ** every column that the two tables have in common.
88021     */
88022     if( pRight->jointype & JT_NATURAL ){
88023       if( pRight->pOn || pRight->pUsing ){
88024         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
88025            "an ON or USING clause", 0);
88026         return 1;
88027       }
88028       for(j=0; j<pRightTab->nCol; j++){
88029         char *zName;   /* Name of column in the right table */
88030         int iLeft;     /* Matching left table */
88031         int iLeftCol;  /* Matching column in the left table */
88032
88033         zName = pRightTab->aCol[j].zName;
88034         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
88035           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
88036                        isOuter, &p->pWhere);
88037         }
88038       }
88039     }
88040
88041     /* Disallow both ON and USING clauses in the same join
88042     */
88043     if( pRight->pOn && pRight->pUsing ){
88044       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
88045         "clauses in the same join");
88046       return 1;
88047     }
88048
88049     /* Add the ON clause to the end of the WHERE clause, connected by
88050     ** an AND operator.
88051     */
88052     if( pRight->pOn ){
88053       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
88054       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
88055       pRight->pOn = 0;
88056     }
88057
88058     /* Create extra terms on the WHERE clause for each column named
88059     ** in the USING clause.  Example: If the two tables to be joined are 
88060     ** A and B and the USING clause names X, Y, and Z, then add this
88061     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
88062     ** Report an error if any column mentioned in the USING clause is
88063     ** not contained in both tables to be joined.
88064     */
88065     if( pRight->pUsing ){
88066       IdList *pList = pRight->pUsing;
88067       for(j=0; j<pList->nId; j++){
88068         char *zName;     /* Name of the term in the USING clause */
88069         int iLeft;       /* Table on the left with matching column name */
88070         int iLeftCol;    /* Column number of matching column on the left */
88071         int iRightCol;   /* Column number of matching column on the right */
88072
88073         zName = pList->a[j].zName;
88074         iRightCol = columnIndex(pRightTab, zName);
88075         if( iRightCol<0
88076          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
88077         ){
88078           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
88079             "not present in both tables", zName);
88080           return 1;
88081         }
88082         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
88083                      isOuter, &p->pWhere);
88084       }
88085     }
88086   }
88087   return 0;
88088 }
88089
88090 /*
88091 ** Insert code into "v" that will push the record on the top of the
88092 ** stack into the sorter.
88093 */
88094 static void pushOntoSorter(
88095   Parse *pParse,         /* Parser context */
88096   ExprList *pOrderBy,    /* The ORDER BY clause */
88097   Select *pSelect,       /* The whole SELECT statement */
88098   int regData            /* Register holding data to be sorted */
88099 ){
88100   Vdbe *v = pParse->pVdbe;
88101   int nExpr = pOrderBy->nExpr;
88102   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
88103   int regRecord = sqlite3GetTempReg(pParse);
88104   sqlite3ExprCacheClear(pParse);
88105   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
88106   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
88107   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
88108   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
88109   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
88110   sqlite3ReleaseTempReg(pParse, regRecord);
88111   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
88112   if( pSelect->iLimit ){
88113     int addr1, addr2;
88114     int iLimit;
88115     if( pSelect->iOffset ){
88116       iLimit = pSelect->iOffset+1;
88117     }else{
88118       iLimit = pSelect->iLimit;
88119     }
88120     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
88121     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
88122     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
88123     sqlite3VdbeJumpHere(v, addr1);
88124     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
88125     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
88126     sqlite3VdbeJumpHere(v, addr2);
88127   }
88128 }
88129
88130 /*
88131 ** Add code to implement the OFFSET
88132 */
88133 static void codeOffset(
88134   Vdbe *v,          /* Generate code into this VM */
88135   Select *p,        /* The SELECT statement being coded */
88136   int iContinue     /* Jump here to skip the current record */
88137 ){
88138   if( p->iOffset && iContinue!=0 ){
88139     int addr;
88140     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
88141     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
88142     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
88143     VdbeComment((v, "skip OFFSET records"));
88144     sqlite3VdbeJumpHere(v, addr);
88145   }
88146 }
88147
88148 /*
88149 ** Add code that will check to make sure the N registers starting at iMem
88150 ** form a distinct entry.  iTab is a sorting index that holds previously
88151 ** seen combinations of the N values.  A new entry is made in iTab
88152 ** if the current N values are new.
88153 **
88154 ** A jump to addrRepeat is made and the N+1 values are popped from the
88155 ** stack if the top N elements are not distinct.
88156 */
88157 static void codeDistinct(
88158   Parse *pParse,     /* Parsing and code generating context */
88159   int iTab,          /* A sorting index used to test for distinctness */
88160   int addrRepeat,    /* Jump to here if not distinct */
88161   int N,             /* Number of elements */
88162   int iMem           /* First element */
88163 ){
88164   Vdbe *v;
88165   int r1;
88166
88167   v = pParse->pVdbe;
88168   r1 = sqlite3GetTempReg(pParse);
88169   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
88170   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
88171   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
88172   sqlite3ReleaseTempReg(pParse, r1);
88173 }
88174
88175 #ifndef SQLITE_OMIT_SUBQUERY
88176 /*
88177 ** Generate an error message when a SELECT is used within a subexpression
88178 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
88179 ** column.  We do this in a subroutine because the error used to occur
88180 ** in multiple places.  (The error only occurs in one place now, but we
88181 ** retain the subroutine to minimize code disruption.)
88182 */
88183 static int checkForMultiColumnSelectError(
88184   Parse *pParse,       /* Parse context. */
88185   SelectDest *pDest,   /* Destination of SELECT results */
88186   int nExpr            /* Number of result columns returned by SELECT */
88187 ){
88188   int eDest = pDest->eDest;
88189   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
88190     sqlite3ErrorMsg(pParse, "only a single result allowed for "
88191        "a SELECT that is part of an expression");
88192     return 1;
88193   }else{
88194     return 0;
88195   }
88196 }
88197 #endif
88198
88199 /*
88200 ** This routine generates the code for the inside of the inner loop
88201 ** of a SELECT.
88202 **
88203 ** If srcTab and nColumn are both zero, then the pEList expressions
88204 ** are evaluated in order to get the data for this row.  If nColumn>0
88205 ** then data is pulled from srcTab and pEList is used only to get the
88206 ** datatypes for each column.
88207 */
88208 static void selectInnerLoop(
88209   Parse *pParse,          /* The parser context */
88210   Select *p,              /* The complete select statement being coded */
88211   ExprList *pEList,       /* List of values being extracted */
88212   int srcTab,             /* Pull data from this table */
88213   int nColumn,            /* Number of columns in the source table */
88214   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
88215   int distinct,           /* If >=0, make sure results are distinct */
88216   SelectDest *pDest,      /* How to dispose of the results */
88217   int iContinue,          /* Jump here to continue with next row */
88218   int iBreak              /* Jump here to break out of the inner loop */
88219 ){
88220   Vdbe *v = pParse->pVdbe;
88221   int i;
88222   int hasDistinct;        /* True if the DISTINCT keyword is present */
88223   int regResult;              /* Start of memory holding result set */
88224   int eDest = pDest->eDest;   /* How to dispose of results */
88225   int iParm = pDest->iParm;   /* First argument to disposal method */
88226   int nResultCol;             /* Number of result columns */
88227
88228   assert( v );
88229   if( NEVER(v==0) ) return;
88230   assert( pEList!=0 );
88231   hasDistinct = distinct>=0;
88232   if( pOrderBy==0 && !hasDistinct ){
88233     codeOffset(v, p, iContinue);
88234   }
88235
88236   /* Pull the requested columns.
88237   */
88238   if( nColumn>0 ){
88239     nResultCol = nColumn;
88240   }else{
88241     nResultCol = pEList->nExpr;
88242   }
88243   if( pDest->iMem==0 ){
88244     pDest->iMem = pParse->nMem+1;
88245     pDest->nMem = nResultCol;
88246     pParse->nMem += nResultCol;
88247   }else{ 
88248     assert( pDest->nMem==nResultCol );
88249   }
88250   regResult = pDest->iMem;
88251   if( nColumn>0 ){
88252     for(i=0; i<nColumn; i++){
88253       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
88254     }
88255   }else if( eDest!=SRT_Exists ){
88256     /* If the destination is an EXISTS(...) expression, the actual
88257     ** values returned by the SELECT are not required.
88258     */
88259     sqlite3ExprCacheClear(pParse);
88260     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
88261   }
88262   nColumn = nResultCol;
88263
88264   /* If the DISTINCT keyword was present on the SELECT statement
88265   ** and this row has been seen before, then do not make this row
88266   ** part of the result.
88267   */
88268   if( hasDistinct ){
88269     assert( pEList!=0 );
88270     assert( pEList->nExpr==nColumn );
88271     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
88272     if( pOrderBy==0 ){
88273       codeOffset(v, p, iContinue);
88274     }
88275   }
88276
88277   switch( eDest ){
88278     /* In this mode, write each query result to the key of the temporary
88279     ** table iParm.
88280     */
88281 #ifndef SQLITE_OMIT_COMPOUND_SELECT
88282     case SRT_Union: {
88283       int r1;
88284       r1 = sqlite3GetTempReg(pParse);
88285       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
88286       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
88287       sqlite3ReleaseTempReg(pParse, r1);
88288       break;
88289     }
88290
88291     /* Construct a record from the query result, but instead of
88292     ** saving that record, use it as a key to delete elements from
88293     ** the temporary table iParm.
88294     */
88295     case SRT_Except: {
88296       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
88297       break;
88298     }
88299 #endif
88300
88301     /* Store the result as data using a unique key.
88302     */
88303     case SRT_Table:
88304     case SRT_EphemTab: {
88305       int r1 = sqlite3GetTempReg(pParse);
88306       testcase( eDest==SRT_Table );
88307       testcase( eDest==SRT_EphemTab );
88308       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
88309       if( pOrderBy ){
88310         pushOntoSorter(pParse, pOrderBy, p, r1);
88311       }else{
88312         int r2 = sqlite3GetTempReg(pParse);
88313         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
88314         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
88315         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
88316         sqlite3ReleaseTempReg(pParse, r2);
88317       }
88318       sqlite3ReleaseTempReg(pParse, r1);
88319       break;
88320     }
88321
88322 #ifndef SQLITE_OMIT_SUBQUERY
88323     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
88324     ** then there should be a single item on the stack.  Write this
88325     ** item into the set table with bogus data.
88326     */
88327     case SRT_Set: {
88328       assert( nColumn==1 );
88329       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
88330       if( pOrderBy ){
88331         /* At first glance you would think we could optimize out the
88332         ** ORDER BY in this case since the order of entries in the set
88333         ** does not matter.  But there might be a LIMIT clause, in which
88334         ** case the order does matter */
88335         pushOntoSorter(pParse, pOrderBy, p, regResult);
88336       }else{
88337         int r1 = sqlite3GetTempReg(pParse);
88338         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
88339         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
88340         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
88341         sqlite3ReleaseTempReg(pParse, r1);
88342       }
88343       break;
88344     }
88345
88346     /* If any row exist in the result set, record that fact and abort.
88347     */
88348     case SRT_Exists: {
88349       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
88350       /* The LIMIT clause will terminate the loop for us */
88351       break;
88352     }
88353
88354     /* If this is a scalar select that is part of an expression, then
88355     ** store the results in the appropriate memory cell and break out
88356     ** of the scan loop.
88357     */
88358     case SRT_Mem: {
88359       assert( nColumn==1 );
88360       if( pOrderBy ){
88361         pushOntoSorter(pParse, pOrderBy, p, regResult);
88362       }else{
88363         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
88364         /* The LIMIT clause will jump out of the loop for us */
88365       }
88366       break;
88367     }
88368 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
88369
88370     /* Send the data to the callback function or to a subroutine.  In the
88371     ** case of a subroutine, the subroutine itself is responsible for
88372     ** popping the data from the stack.
88373     */
88374     case SRT_Coroutine:
88375     case SRT_Output: {
88376       testcase( eDest==SRT_Coroutine );
88377       testcase( eDest==SRT_Output );
88378       if( pOrderBy ){
88379         int r1 = sqlite3GetTempReg(pParse);
88380         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
88381         pushOntoSorter(pParse, pOrderBy, p, r1);
88382         sqlite3ReleaseTempReg(pParse, r1);
88383       }else if( eDest==SRT_Coroutine ){
88384         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
88385       }else{
88386         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
88387         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
88388       }
88389       break;
88390     }
88391
88392 #if !defined(SQLITE_OMIT_TRIGGER)
88393     /* Discard the results.  This is used for SELECT statements inside
88394     ** the body of a TRIGGER.  The purpose of such selects is to call
88395     ** user-defined functions that have side effects.  We do not care
88396     ** about the actual results of the select.
88397     */
88398     default: {
88399       assert( eDest==SRT_Discard );
88400       break;
88401     }
88402 #endif
88403   }
88404
88405   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
88406   ** there is a sorter, in which case the sorter has already limited
88407   ** the output for us.
88408   */
88409   if( pOrderBy==0 && p->iLimit ){
88410     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
88411   }
88412 }
88413
88414 /*
88415 ** Given an expression list, generate a KeyInfo structure that records
88416 ** the collating sequence for each expression in that expression list.
88417 **
88418 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
88419 ** KeyInfo structure is appropriate for initializing a virtual index to
88420 ** implement that clause.  If the ExprList is the result set of a SELECT
88421 ** then the KeyInfo structure is appropriate for initializing a virtual
88422 ** index to implement a DISTINCT test.
88423 **
88424 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
88425 ** function is responsible for seeing that this structure is eventually
88426 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
88427 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
88428 */
88429 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
88430   sqlite3 *db = pParse->db;
88431   int nExpr;
88432   KeyInfo *pInfo;
88433   struct ExprList_item *pItem;
88434   int i;
88435
88436   nExpr = pList->nExpr;
88437   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
88438   if( pInfo ){
88439     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
88440     pInfo->nField = (u16)nExpr;
88441     pInfo->enc = ENC(db);
88442     pInfo->db = db;
88443     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
88444       CollSeq *pColl;
88445       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
88446       if( !pColl ){
88447         pColl = db->pDfltColl;
88448       }
88449       pInfo->aColl[i] = pColl;
88450       pInfo->aSortOrder[i] = pItem->sortOrder;
88451     }
88452   }
88453   return pInfo;
88454 }
88455
88456 #ifndef SQLITE_OMIT_COMPOUND_SELECT
88457 /*
88458 ** Name of the connection operator, used for error messages.
88459 */
88460 static const char *selectOpName(int id){
88461   char *z;
88462   switch( id ){
88463     case TK_ALL:       z = "UNION ALL";   break;
88464     case TK_INTERSECT: z = "INTERSECT";   break;
88465     case TK_EXCEPT:    z = "EXCEPT";      break;
88466     default:           z = "UNION";       break;
88467   }
88468   return z;
88469 }
88470 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
88471
88472 #ifndef SQLITE_OMIT_EXPLAIN
88473 /*
88474 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
88475 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
88476 ** where the caption is of the form:
88477 **
88478 **   "USE TEMP B-TREE FOR xxx"
88479 **
88480 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
88481 ** is determined by the zUsage argument.
88482 */
88483 static void explainTempTable(Parse *pParse, const char *zUsage){
88484   if( pParse->explain==2 ){
88485     Vdbe *v = pParse->pVdbe;
88486     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
88487     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
88488   }
88489 }
88490
88491 /*
88492 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
88493 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
88494 ** where the caption is of one of the two forms:
88495 **
88496 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
88497 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
88498 **
88499 ** where iSub1 and iSub2 are the integers passed as the corresponding
88500 ** function parameters, and op is the text representation of the parameter
88501 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
88502 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
88503 ** false, or the second form if it is true.
88504 */
88505 static void explainComposite(
88506   Parse *pParse,                  /* Parse context */
88507   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
88508   int iSub1,                      /* Subquery id 1 */
88509   int iSub2,                      /* Subquery id 2 */
88510   int bUseTmp                     /* True if a temp table was used */
88511 ){
88512   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
88513   if( pParse->explain==2 ){
88514     Vdbe *v = pParse->pVdbe;
88515     char *zMsg = sqlite3MPrintf(
88516         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
88517         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
88518     );
88519     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
88520   }
88521 }
88522
88523 /*
88524 ** Assign expression b to lvalue a. A second, no-op, version of this macro
88525 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
88526 ** in sqlite3Select() to assign values to structure member variables that
88527 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
88528 ** code with #ifndef directives.
88529 */
88530 # define explainSetInteger(a, b) a = b
88531
88532 #else
88533 /* No-op versions of the explainXXX() functions and macros. */
88534 # define explainTempTable(y,z)
88535 # define explainComposite(v,w,x,y,z)
88536 # define explainSetInteger(y,z)
88537 #endif
88538
88539 /*
88540 ** If the inner loop was generated using a non-null pOrderBy argument,
88541 ** then the results were placed in a sorter.  After the loop is terminated
88542 ** we need to run the sorter and output the results.  The following
88543 ** routine generates the code needed to do that.
88544 */
88545 static void generateSortTail(
88546   Parse *pParse,    /* Parsing context */
88547   Select *p,        /* The SELECT statement */
88548   Vdbe *v,          /* Generate code into this VDBE */
88549   int nColumn,      /* Number of columns of data */
88550   SelectDest *pDest /* Write the sorted results here */
88551 ){
88552   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
88553   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
88554   int addr;
88555   int iTab;
88556   int pseudoTab = 0;
88557   ExprList *pOrderBy = p->pOrderBy;
88558
88559   int eDest = pDest->eDest;
88560   int iParm = pDest->iParm;
88561
88562   int regRow;
88563   int regRowid;
88564
88565   iTab = pOrderBy->iECursor;
88566   regRow = sqlite3GetTempReg(pParse);
88567   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
88568     pseudoTab = pParse->nTab++;
88569     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
88570     regRowid = 0;
88571   }else{
88572     regRowid = sqlite3GetTempReg(pParse);
88573   }
88574   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
88575   codeOffset(v, p, addrContinue);
88576   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
88577   switch( eDest ){
88578     case SRT_Table:
88579     case SRT_EphemTab: {
88580       testcase( eDest==SRT_Table );
88581       testcase( eDest==SRT_EphemTab );
88582       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
88583       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
88584       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
88585       break;
88586     }
88587 #ifndef SQLITE_OMIT_SUBQUERY
88588     case SRT_Set: {
88589       assert( nColumn==1 );
88590       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
88591       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
88592       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
88593       break;
88594     }
88595     case SRT_Mem: {
88596       assert( nColumn==1 );
88597       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
88598       /* The LIMIT clause will terminate the loop for us */
88599       break;
88600     }
88601 #endif
88602     default: {
88603       int i;
88604       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
88605       testcase( eDest==SRT_Output );
88606       testcase( eDest==SRT_Coroutine );
88607       for(i=0; i<nColumn; i++){
88608         assert( regRow!=pDest->iMem+i );
88609         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
88610         if( i==0 ){
88611           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
88612         }
88613       }
88614       if( eDest==SRT_Output ){
88615         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
88616         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
88617       }else{
88618         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
88619       }
88620       break;
88621     }
88622   }
88623   sqlite3ReleaseTempReg(pParse, regRow);
88624   sqlite3ReleaseTempReg(pParse, regRowid);
88625
88626   /* The bottom of the loop
88627   */
88628   sqlite3VdbeResolveLabel(v, addrContinue);
88629   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
88630   sqlite3VdbeResolveLabel(v, addrBreak);
88631   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
88632     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
88633   }
88634 }
88635
88636 /*
88637 ** Return a pointer to a string containing the 'declaration type' of the
88638 ** expression pExpr. The string may be treated as static by the caller.
88639 **
88640 ** The declaration type is the exact datatype definition extracted from the
88641 ** original CREATE TABLE statement if the expression is a column. The
88642 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
88643 ** is considered a column can be complex in the presence of subqueries. The
88644 ** result-set expression in all of the following SELECT statements is 
88645 ** considered a column by this function.
88646 **
88647 **   SELECT col FROM tbl;
88648 **   SELECT (SELECT col FROM tbl;
88649 **   SELECT (SELECT col FROM tbl);
88650 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
88651 ** 
88652 ** The declaration type for any expression other than a column is NULL.
88653 */
88654 static const char *columnType(
88655   NameContext *pNC, 
88656   Expr *pExpr,
88657   const char **pzOriginDb,
88658   const char **pzOriginTab,
88659   const char **pzOriginCol
88660 ){
88661   char const *zType = 0;
88662   char const *zOriginDb = 0;
88663   char const *zOriginTab = 0;
88664   char const *zOriginCol = 0;
88665   int j;
88666   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
88667
88668   switch( pExpr->op ){
88669     case TK_AGG_COLUMN:
88670     case TK_COLUMN: {
88671       /* The expression is a column. Locate the table the column is being
88672       ** extracted from in NameContext.pSrcList. This table may be real
88673       ** database table or a subquery.
88674       */
88675       Table *pTab = 0;            /* Table structure column is extracted from */
88676       Select *pS = 0;             /* Select the column is extracted from */
88677       int iCol = pExpr->iColumn;  /* Index of column in pTab */
88678       testcase( pExpr->op==TK_AGG_COLUMN );
88679       testcase( pExpr->op==TK_COLUMN );
88680       while( pNC && !pTab ){
88681         SrcList *pTabList = pNC->pSrcList;
88682         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
88683         if( j<pTabList->nSrc ){
88684           pTab = pTabList->a[j].pTab;
88685           pS = pTabList->a[j].pSelect;
88686         }else{
88687           pNC = pNC->pNext;
88688         }
88689       }
88690
88691       if( pTab==0 ){
88692         /* At one time, code such as "SELECT new.x" within a trigger would
88693         ** cause this condition to run.  Since then, we have restructured how
88694         ** trigger code is generated and so this condition is no longer 
88695         ** possible. However, it can still be true for statements like
88696         ** the following:
88697         **
88698         **   CREATE TABLE t1(col INTEGER);
88699         **   SELECT (SELECT t1.col) FROM FROM t1;
88700         **
88701         ** when columnType() is called on the expression "t1.col" in the 
88702         ** sub-select. In this case, set the column type to NULL, even
88703         ** though it should really be "INTEGER".
88704         **
88705         ** This is not a problem, as the column type of "t1.col" is never
88706         ** used. When columnType() is called on the expression 
88707         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
88708         ** branch below.  */
88709         break;
88710       }
88711
88712       assert( pTab && pExpr->pTab==pTab );
88713       if( pS ){
88714         /* The "table" is actually a sub-select or a view in the FROM clause
88715         ** of the SELECT statement. Return the declaration type and origin
88716         ** data for the result-set column of the sub-select.
88717         */
88718         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
88719           /* If iCol is less than zero, then the expression requests the
88720           ** rowid of the sub-select or view. This expression is legal (see 
88721           ** test case misc2.2.2) - it always evaluates to NULL.
88722           */
88723           NameContext sNC;
88724           Expr *p = pS->pEList->a[iCol].pExpr;
88725           sNC.pSrcList = pS->pSrc;
88726           sNC.pNext = pNC;
88727           sNC.pParse = pNC->pParse;
88728           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
88729         }
88730       }else if( ALWAYS(pTab->pSchema) ){
88731         /* A real table */
88732         assert( !pS );
88733         if( iCol<0 ) iCol = pTab->iPKey;
88734         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
88735         if( iCol<0 ){
88736           zType = "INTEGER";
88737           zOriginCol = "rowid";
88738         }else{
88739           zType = pTab->aCol[iCol].zType;
88740           zOriginCol = pTab->aCol[iCol].zName;
88741         }
88742         zOriginTab = pTab->zName;
88743         if( pNC->pParse ){
88744           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
88745           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
88746         }
88747       }
88748       break;
88749     }
88750 #ifndef SQLITE_OMIT_SUBQUERY
88751     case TK_SELECT: {
88752       /* The expression is a sub-select. Return the declaration type and
88753       ** origin info for the single column in the result set of the SELECT
88754       ** statement.
88755       */
88756       NameContext sNC;
88757       Select *pS = pExpr->x.pSelect;
88758       Expr *p = pS->pEList->a[0].pExpr;
88759       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
88760       sNC.pSrcList = pS->pSrc;
88761       sNC.pNext = pNC;
88762       sNC.pParse = pNC->pParse;
88763       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
88764       break;
88765     }
88766 #endif
88767   }
88768   
88769   if( pzOriginDb ){
88770     assert( pzOriginTab && pzOriginCol );
88771     *pzOriginDb = zOriginDb;
88772     *pzOriginTab = zOriginTab;
88773     *pzOriginCol = zOriginCol;
88774   }
88775   return zType;
88776 }
88777
88778 /*
88779 ** Generate code that will tell the VDBE the declaration types of columns
88780 ** in the result set.
88781 */
88782 static void generateColumnTypes(
88783   Parse *pParse,      /* Parser context */
88784   SrcList *pTabList,  /* List of tables */
88785   ExprList *pEList    /* Expressions defining the result set */
88786 ){
88787 #ifndef SQLITE_OMIT_DECLTYPE
88788   Vdbe *v = pParse->pVdbe;
88789   int i;
88790   NameContext sNC;
88791   sNC.pSrcList = pTabList;
88792   sNC.pParse = pParse;
88793   for(i=0; i<pEList->nExpr; i++){
88794     Expr *p = pEList->a[i].pExpr;
88795     const char *zType;
88796 #ifdef SQLITE_ENABLE_COLUMN_METADATA
88797     const char *zOrigDb = 0;
88798     const char *zOrigTab = 0;
88799     const char *zOrigCol = 0;
88800     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
88801
88802     /* The vdbe must make its own copy of the column-type and other 
88803     ** column specific strings, in case the schema is reset before this
88804     ** virtual machine is deleted.
88805     */
88806     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
88807     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
88808     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
88809 #else
88810     zType = columnType(&sNC, p, 0, 0, 0);
88811 #endif
88812     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
88813   }
88814 #endif /* SQLITE_OMIT_DECLTYPE */
88815 }
88816
88817 /*
88818 ** Generate code that will tell the VDBE the names of columns
88819 ** in the result set.  This information is used to provide the
88820 ** azCol[] values in the callback.
88821 */
88822 static void generateColumnNames(
88823   Parse *pParse,      /* Parser context */
88824   SrcList *pTabList,  /* List of tables */
88825   ExprList *pEList    /* Expressions defining the result set */
88826 ){
88827   Vdbe *v = pParse->pVdbe;
88828   int i, j;
88829   sqlite3 *db = pParse->db;
88830   int fullNames, shortNames;
88831
88832 #ifndef SQLITE_OMIT_EXPLAIN
88833   /* If this is an EXPLAIN, skip this step */
88834   if( pParse->explain ){
88835     return;
88836   }
88837 #endif
88838
88839   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
88840   pParse->colNamesSet = 1;
88841   fullNames = (db->flags & SQLITE_FullColNames)!=0;
88842   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
88843   sqlite3VdbeSetNumCols(v, pEList->nExpr);
88844   for(i=0; i<pEList->nExpr; i++){
88845     Expr *p;
88846     p = pEList->a[i].pExpr;
88847     if( NEVER(p==0) ) continue;
88848     if( pEList->a[i].zName ){
88849       char *zName = pEList->a[i].zName;
88850       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
88851     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
88852       Table *pTab;
88853       char *zCol;
88854       int iCol = p->iColumn;
88855       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
88856         if( pTabList->a[j].iCursor==p->iTable ) break;
88857       }
88858       assert( j<pTabList->nSrc );
88859       pTab = pTabList->a[j].pTab;
88860       if( iCol<0 ) iCol = pTab->iPKey;
88861       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
88862       if( iCol<0 ){
88863         zCol = "rowid";
88864       }else{
88865         zCol = pTab->aCol[iCol].zName;
88866       }
88867       if( !shortNames && !fullNames ){
88868         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
88869             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
88870       }else if( fullNames ){
88871         char *zName = 0;
88872         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
88873         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
88874       }else{
88875         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
88876       }
88877     }else{
88878       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
88879           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
88880     }
88881   }
88882   generateColumnTypes(pParse, pTabList, pEList);
88883 }
88884
88885 /*
88886 ** Given a an expression list (which is really the list of expressions
88887 ** that form the result set of a SELECT statement) compute appropriate
88888 ** column names for a table that would hold the expression list.
88889 **
88890 ** All column names will be unique.
88891 **
88892 ** Only the column names are computed.  Column.zType, Column.zColl,
88893 ** and other fields of Column are zeroed.
88894 **
88895 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
88896 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
88897 */
88898 static int selectColumnsFromExprList(
88899   Parse *pParse,          /* Parsing context */
88900   ExprList *pEList,       /* Expr list from which to derive column names */
88901   int *pnCol,             /* Write the number of columns here */
88902   Column **paCol          /* Write the new column list here */
88903 ){
88904   sqlite3 *db = pParse->db;   /* Database connection */
88905   int i, j;                   /* Loop counters */
88906   int cnt;                    /* Index added to make the name unique */
88907   Column *aCol, *pCol;        /* For looping over result columns */
88908   int nCol;                   /* Number of columns in the result set */
88909   Expr *p;                    /* Expression for a single result column */
88910   char *zName;                /* Column name */
88911   int nName;                  /* Size of name in zName[] */
88912
88913   *pnCol = nCol = pEList->nExpr;
88914   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
88915   if( aCol==0 ) return SQLITE_NOMEM;
88916   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
88917     /* Get an appropriate name for the column
88918     */
88919     p = pEList->a[i].pExpr;
88920     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
88921                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
88922     if( (zName = pEList->a[i].zName)!=0 ){
88923       /* If the column contains an "AS <name>" phrase, use <name> as the name */
88924       zName = sqlite3DbStrDup(db, zName);
88925     }else{
88926       Expr *pColExpr = p;  /* The expression that is the result column name */
88927       Table *pTab;         /* Table associated with this expression */
88928       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
88929       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
88930         /* For columns use the column name name */
88931         int iCol = pColExpr->iColumn;
88932         pTab = pColExpr->pTab;
88933         if( iCol<0 ) iCol = pTab->iPKey;
88934         zName = sqlite3MPrintf(db, "%s",
88935                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
88936       }else if( pColExpr->op==TK_ID ){
88937         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
88938         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
88939       }else{
88940         /* Use the original text of the column expression as its name */
88941         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
88942       }
88943     }
88944     if( db->mallocFailed ){
88945       sqlite3DbFree(db, zName);
88946       break;
88947     }
88948
88949     /* Make sure the column name is unique.  If the name is not unique,
88950     ** append a integer to the name so that it becomes unique.
88951     */
88952     nName = sqlite3Strlen30(zName);
88953     for(j=cnt=0; j<i; j++){
88954       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
88955         char *zNewName;
88956         zName[nName] = 0;
88957         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
88958         sqlite3DbFree(db, zName);
88959         zName = zNewName;
88960         j = -1;
88961         if( zName==0 ) break;
88962       }
88963     }
88964     pCol->zName = zName;
88965   }
88966   if( db->mallocFailed ){
88967     for(j=0; j<i; j++){
88968       sqlite3DbFree(db, aCol[j].zName);
88969     }
88970     sqlite3DbFree(db, aCol);
88971     *paCol = 0;
88972     *pnCol = 0;
88973     return SQLITE_NOMEM;
88974   }
88975   return SQLITE_OK;
88976 }
88977
88978 /*
88979 ** Add type and collation information to a column list based on
88980 ** a SELECT statement.
88981 ** 
88982 ** The column list presumably came from selectColumnNamesFromExprList().
88983 ** The column list has only names, not types or collations.  This
88984 ** routine goes through and adds the types and collations.
88985 **
88986 ** This routine requires that all identifiers in the SELECT
88987 ** statement be resolved.
88988 */
88989 static void selectAddColumnTypeAndCollation(
88990   Parse *pParse,        /* Parsing contexts */
88991   int nCol,             /* Number of columns */
88992   Column *aCol,         /* List of columns */
88993   Select *pSelect       /* SELECT used to determine types and collations */
88994 ){
88995   sqlite3 *db = pParse->db;
88996   NameContext sNC;
88997   Column *pCol;
88998   CollSeq *pColl;
88999   int i;
89000   Expr *p;
89001   struct ExprList_item *a;
89002
89003   assert( pSelect!=0 );
89004   assert( (pSelect->selFlags & SF_Resolved)!=0 );
89005   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
89006   if( db->mallocFailed ) return;
89007   memset(&sNC, 0, sizeof(sNC));
89008   sNC.pSrcList = pSelect->pSrc;
89009   a = pSelect->pEList->a;
89010   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
89011     p = a[i].pExpr;
89012     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
89013     pCol->affinity = sqlite3ExprAffinity(p);
89014     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
89015     pColl = sqlite3ExprCollSeq(pParse, p);
89016     if( pColl ){
89017       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
89018     }
89019   }
89020 }
89021
89022 /*
89023 ** Given a SELECT statement, generate a Table structure that describes
89024 ** the result set of that SELECT.
89025 */
89026 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
89027   Table *pTab;
89028   sqlite3 *db = pParse->db;
89029   int savedFlags;
89030
89031   savedFlags = db->flags;
89032   db->flags &= ~SQLITE_FullColNames;
89033   db->flags |= SQLITE_ShortColNames;
89034   sqlite3SelectPrep(pParse, pSelect, 0);
89035   if( pParse->nErr ) return 0;
89036   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
89037   db->flags = savedFlags;
89038   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
89039   if( pTab==0 ){
89040     return 0;
89041   }
89042   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
89043   ** is disabled */
89044   assert( db->lookaside.bEnabled==0 );
89045   pTab->nRef = 1;
89046   pTab->zName = 0;
89047   pTab->nRowEst = 1000000;
89048   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
89049   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
89050   pTab->iPKey = -1;
89051   if( db->mallocFailed ){
89052     sqlite3DeleteTable(db, pTab);
89053     return 0;
89054   }
89055   return pTab;
89056 }
89057
89058 /*
89059 ** Get a VDBE for the given parser context.  Create a new one if necessary.
89060 ** If an error occurs, return NULL and leave a message in pParse.
89061 */
89062 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
89063   Vdbe *v = pParse->pVdbe;
89064   if( v==0 ){
89065     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
89066 #ifndef SQLITE_OMIT_TRACE
89067     if( v ){
89068       sqlite3VdbeAddOp0(v, OP_Trace);
89069     }
89070 #endif
89071   }
89072   return v;
89073 }
89074
89075
89076 /*
89077 ** Compute the iLimit and iOffset fields of the SELECT based on the
89078 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
89079 ** that appear in the original SQL statement after the LIMIT and OFFSET
89080 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
89081 ** are the integer memory register numbers for counters used to compute 
89082 ** the limit and offset.  If there is no limit and/or offset, then 
89083 ** iLimit and iOffset are negative.
89084 **
89085 ** This routine changes the values of iLimit and iOffset only if
89086 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
89087 ** iOffset should have been preset to appropriate default values
89088 ** (usually but not always -1) prior to calling this routine.
89089 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
89090 ** redefined.  The UNION ALL operator uses this property to force
89091 ** the reuse of the same limit and offset registers across multiple
89092 ** SELECT statements.
89093 */
89094 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
89095   Vdbe *v = 0;
89096   int iLimit = 0;
89097   int iOffset;
89098   int addr1, n;
89099   if( p->iLimit ) return;
89100
89101   /* 
89102   ** "LIMIT -1" always shows all rows.  There is some
89103   ** contraversy about what the correct behavior should be.
89104   ** The current implementation interprets "LIMIT 0" to mean
89105   ** no rows.
89106   */
89107   sqlite3ExprCacheClear(pParse);
89108   assert( p->pOffset==0 || p->pLimit!=0 );
89109   if( p->pLimit ){
89110     p->iLimit = iLimit = ++pParse->nMem;
89111     v = sqlite3GetVdbe(pParse);
89112     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
89113     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
89114       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
89115       VdbeComment((v, "LIMIT counter"));
89116       if( n==0 ){
89117         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
89118       }else{
89119         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
89120       }
89121     }else{
89122       sqlite3ExprCode(pParse, p->pLimit, iLimit);
89123       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
89124       VdbeComment((v, "LIMIT counter"));
89125       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
89126     }
89127     if( p->pOffset ){
89128       p->iOffset = iOffset = ++pParse->nMem;
89129       pParse->nMem++;   /* Allocate an extra register for limit+offset */
89130       sqlite3ExprCode(pParse, p->pOffset, iOffset);
89131       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
89132       VdbeComment((v, "OFFSET counter"));
89133       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
89134       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
89135       sqlite3VdbeJumpHere(v, addr1);
89136       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
89137       VdbeComment((v, "LIMIT+OFFSET"));
89138       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
89139       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
89140       sqlite3VdbeJumpHere(v, addr1);
89141     }
89142   }
89143 }
89144
89145 #ifndef SQLITE_OMIT_COMPOUND_SELECT
89146 /*
89147 ** Return the appropriate collating sequence for the iCol-th column of
89148 ** the result set for the compound-select statement "p".  Return NULL if
89149 ** the column has no default collating sequence.
89150 **
89151 ** The collating sequence for the compound select is taken from the
89152 ** left-most term of the select that has a collating sequence.
89153 */
89154 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
89155   CollSeq *pRet;
89156   if( p->pPrior ){
89157     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
89158   }else{
89159     pRet = 0;
89160   }
89161   assert( iCol>=0 );
89162   if( pRet==0 && iCol<p->pEList->nExpr ){
89163     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
89164   }
89165   return pRet;
89166 }
89167 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
89168
89169 /* Forward reference */
89170 static int multiSelectOrderBy(
89171   Parse *pParse,        /* Parsing context */
89172   Select *p,            /* The right-most of SELECTs to be coded */
89173   SelectDest *pDest     /* What to do with query results */
89174 );
89175
89176
89177 #ifndef SQLITE_OMIT_COMPOUND_SELECT
89178 /*
89179 ** This routine is called to process a compound query form from
89180 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
89181 ** INTERSECT
89182 **
89183 ** "p" points to the right-most of the two queries.  the query on the
89184 ** left is p->pPrior.  The left query could also be a compound query
89185 ** in which case this routine will be called recursively. 
89186 **
89187 ** The results of the total query are to be written into a destination
89188 ** of type eDest with parameter iParm.
89189 **
89190 ** Example 1:  Consider a three-way compound SQL statement.
89191 **
89192 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
89193 **
89194 ** This statement is parsed up as follows:
89195 **
89196 **     SELECT c FROM t3
89197 **      |
89198 **      `----->  SELECT b FROM t2
89199 **                |
89200 **                `------>  SELECT a FROM t1
89201 **
89202 ** The arrows in the diagram above represent the Select.pPrior pointer.
89203 ** So if this routine is called with p equal to the t3 query, then
89204 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
89205 **
89206 ** Notice that because of the way SQLite parses compound SELECTs, the
89207 ** individual selects always group from left to right.
89208 */
89209 static int multiSelect(
89210   Parse *pParse,        /* Parsing context */
89211   Select *p,            /* The right-most of SELECTs to be coded */
89212   SelectDest *pDest     /* What to do with query results */
89213 ){
89214   int rc = SQLITE_OK;   /* Success code from a subroutine */
89215   Select *pPrior;       /* Another SELECT immediately to our left */
89216   Vdbe *v;              /* Generate code to this VDBE */
89217   SelectDest dest;      /* Alternative data destination */
89218   Select *pDelete = 0;  /* Chain of simple selects to delete */
89219   sqlite3 *db;          /* Database connection */
89220 #ifndef SQLITE_OMIT_EXPLAIN
89221   int iSub1;            /* EQP id of left-hand query */
89222   int iSub2;            /* EQP id of right-hand query */
89223 #endif
89224
89225   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
89226   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
89227   */
89228   assert( p && p->pPrior );  /* Calling function guarantees this much */
89229   db = pParse->db;
89230   pPrior = p->pPrior;
89231   assert( pPrior->pRightmost!=pPrior );
89232   assert( pPrior->pRightmost==p->pRightmost );
89233   dest = *pDest;
89234   if( pPrior->pOrderBy ){
89235     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
89236       selectOpName(p->op));
89237     rc = 1;
89238     goto multi_select_end;
89239   }
89240   if( pPrior->pLimit ){
89241     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
89242       selectOpName(p->op));
89243     rc = 1;
89244     goto multi_select_end;
89245   }
89246
89247   v = sqlite3GetVdbe(pParse);
89248   assert( v!=0 );  /* The VDBE already created by calling function */
89249
89250   /* Create the destination temporary table if necessary
89251   */
89252   if( dest.eDest==SRT_EphemTab ){
89253     assert( p->pEList );
89254     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
89255     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
89256     dest.eDest = SRT_Table;
89257   }
89258
89259   /* Make sure all SELECTs in the statement have the same number of elements
89260   ** in their result sets.
89261   */
89262   assert( p->pEList && pPrior->pEList );
89263   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
89264     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
89265       " do not have the same number of result columns", selectOpName(p->op));
89266     rc = 1;
89267     goto multi_select_end;
89268   }
89269
89270   /* Compound SELECTs that have an ORDER BY clause are handled separately.
89271   */
89272   if( p->pOrderBy ){
89273     return multiSelectOrderBy(pParse, p, pDest);
89274   }
89275
89276   /* Generate code for the left and right SELECT statements.
89277   */
89278   switch( p->op ){
89279     case TK_ALL: {
89280       int addr = 0;
89281       int nLimit;
89282       assert( !pPrior->pLimit );
89283       pPrior->pLimit = p->pLimit;
89284       pPrior->pOffset = p->pOffset;
89285       explainSetInteger(iSub1, pParse->iNextSelectId);
89286       rc = sqlite3Select(pParse, pPrior, &dest);
89287       p->pLimit = 0;
89288       p->pOffset = 0;
89289       if( rc ){
89290         goto multi_select_end;
89291       }
89292       p->pPrior = 0;
89293       p->iLimit = pPrior->iLimit;
89294       p->iOffset = pPrior->iOffset;
89295       if( p->iLimit ){
89296         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
89297         VdbeComment((v, "Jump ahead if LIMIT reached"));
89298       }
89299       explainSetInteger(iSub2, pParse->iNextSelectId);
89300       rc = sqlite3Select(pParse, p, &dest);
89301       testcase( rc!=SQLITE_OK );
89302       pDelete = p->pPrior;
89303       p->pPrior = pPrior;
89304       p->nSelectRow += pPrior->nSelectRow;
89305       if( pPrior->pLimit
89306        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
89307        && p->nSelectRow > (double)nLimit 
89308       ){
89309         p->nSelectRow = (double)nLimit;
89310       }
89311       if( addr ){
89312         sqlite3VdbeJumpHere(v, addr);
89313       }
89314       break;
89315     }
89316     case TK_EXCEPT:
89317     case TK_UNION: {
89318       int unionTab;    /* Cursor number of the temporary table holding result */
89319       u8 op = 0;       /* One of the SRT_ operations to apply to self */
89320       int priorOp;     /* The SRT_ operation to apply to prior selects */
89321       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
89322       int addr;
89323       SelectDest uniondest;
89324
89325       testcase( p->op==TK_EXCEPT );
89326       testcase( p->op==TK_UNION );
89327       priorOp = SRT_Union;
89328       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
89329         /* We can reuse a temporary table generated by a SELECT to our
89330         ** right.
89331         */
89332         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
89333                                      ** of a 3-way or more compound */
89334         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
89335         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
89336         unionTab = dest.iParm;
89337       }else{
89338         /* We will need to create our own temporary table to hold the
89339         ** intermediate results.
89340         */
89341         unionTab = pParse->nTab++;
89342         assert( p->pOrderBy==0 );
89343         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
89344         assert( p->addrOpenEphm[0] == -1 );
89345         p->addrOpenEphm[0] = addr;
89346         p->pRightmost->selFlags |= SF_UsesEphemeral;
89347         assert( p->pEList );
89348       }
89349
89350       /* Code the SELECT statements to our left
89351       */
89352       assert( !pPrior->pOrderBy );
89353       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
89354       explainSetInteger(iSub1, pParse->iNextSelectId);
89355       rc = sqlite3Select(pParse, pPrior, &uniondest);
89356       if( rc ){
89357         goto multi_select_end;
89358       }
89359
89360       /* Code the current SELECT statement
89361       */
89362       if( p->op==TK_EXCEPT ){
89363         op = SRT_Except;
89364       }else{
89365         assert( p->op==TK_UNION );
89366         op = SRT_Union;
89367       }
89368       p->pPrior = 0;
89369       pLimit = p->pLimit;
89370       p->pLimit = 0;
89371       pOffset = p->pOffset;
89372       p->pOffset = 0;
89373       uniondest.eDest = op;
89374       explainSetInteger(iSub2, pParse->iNextSelectId);
89375       rc = sqlite3Select(pParse, p, &uniondest);
89376       testcase( rc!=SQLITE_OK );
89377       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
89378       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
89379       sqlite3ExprListDelete(db, p->pOrderBy);
89380       pDelete = p->pPrior;
89381       p->pPrior = pPrior;
89382       p->pOrderBy = 0;
89383       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
89384       sqlite3ExprDelete(db, p->pLimit);
89385       p->pLimit = pLimit;
89386       p->pOffset = pOffset;
89387       p->iLimit = 0;
89388       p->iOffset = 0;
89389
89390       /* Convert the data in the temporary table into whatever form
89391       ** it is that we currently need.
89392       */
89393       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
89394       if( dest.eDest!=priorOp ){
89395         int iCont, iBreak, iStart;
89396         assert( p->pEList );
89397         if( dest.eDest==SRT_Output ){
89398           Select *pFirst = p;
89399           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
89400           generateColumnNames(pParse, 0, pFirst->pEList);
89401         }
89402         iBreak = sqlite3VdbeMakeLabel(v);
89403         iCont = sqlite3VdbeMakeLabel(v);
89404         computeLimitRegisters(pParse, p, iBreak);
89405         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
89406         iStart = sqlite3VdbeCurrentAddr(v);
89407         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
89408                         0, -1, &dest, iCont, iBreak);
89409         sqlite3VdbeResolveLabel(v, iCont);
89410         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
89411         sqlite3VdbeResolveLabel(v, iBreak);
89412         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
89413       }
89414       break;
89415     }
89416     default: assert( p->op==TK_INTERSECT ); {
89417       int tab1, tab2;
89418       int iCont, iBreak, iStart;
89419       Expr *pLimit, *pOffset;
89420       int addr;
89421       SelectDest intersectdest;
89422       int r1;
89423
89424       /* INTERSECT is different from the others since it requires
89425       ** two temporary tables.  Hence it has its own case.  Begin
89426       ** by allocating the tables we will need.
89427       */
89428       tab1 = pParse->nTab++;
89429       tab2 = pParse->nTab++;
89430       assert( p->pOrderBy==0 );
89431
89432       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
89433       assert( p->addrOpenEphm[0] == -1 );
89434       p->addrOpenEphm[0] = addr;
89435       p->pRightmost->selFlags |= SF_UsesEphemeral;
89436       assert( p->pEList );
89437
89438       /* Code the SELECTs to our left into temporary table "tab1".
89439       */
89440       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
89441       explainSetInteger(iSub1, pParse->iNextSelectId);
89442       rc = sqlite3Select(pParse, pPrior, &intersectdest);
89443       if( rc ){
89444         goto multi_select_end;
89445       }
89446
89447       /* Code the current SELECT into temporary table "tab2"
89448       */
89449       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
89450       assert( p->addrOpenEphm[1] == -1 );
89451       p->addrOpenEphm[1] = addr;
89452       p->pPrior = 0;
89453       pLimit = p->pLimit;
89454       p->pLimit = 0;
89455       pOffset = p->pOffset;
89456       p->pOffset = 0;
89457       intersectdest.iParm = tab2;
89458       explainSetInteger(iSub2, pParse->iNextSelectId);
89459       rc = sqlite3Select(pParse, p, &intersectdest);
89460       testcase( rc!=SQLITE_OK );
89461       pDelete = p->pPrior;
89462       p->pPrior = pPrior;
89463       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
89464       sqlite3ExprDelete(db, p->pLimit);
89465       p->pLimit = pLimit;
89466       p->pOffset = pOffset;
89467
89468       /* Generate code to take the intersection of the two temporary
89469       ** tables.
89470       */
89471       assert( p->pEList );
89472       if( dest.eDest==SRT_Output ){
89473         Select *pFirst = p;
89474         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
89475         generateColumnNames(pParse, 0, pFirst->pEList);
89476       }
89477       iBreak = sqlite3VdbeMakeLabel(v);
89478       iCont = sqlite3VdbeMakeLabel(v);
89479       computeLimitRegisters(pParse, p, iBreak);
89480       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
89481       r1 = sqlite3GetTempReg(pParse);
89482       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
89483       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
89484       sqlite3ReleaseTempReg(pParse, r1);
89485       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
89486                       0, -1, &dest, iCont, iBreak);
89487       sqlite3VdbeResolveLabel(v, iCont);
89488       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
89489       sqlite3VdbeResolveLabel(v, iBreak);
89490       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
89491       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
89492       break;
89493     }
89494   }
89495
89496   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
89497
89498   /* Compute collating sequences used by 
89499   ** temporary tables needed to implement the compound select.
89500   ** Attach the KeyInfo structure to all temporary tables.
89501   **
89502   ** This section is run by the right-most SELECT statement only.
89503   ** SELECT statements to the left always skip this part.  The right-most
89504   ** SELECT might also skip this part if it has no ORDER BY clause and
89505   ** no temp tables are required.
89506   */
89507   if( p->selFlags & SF_UsesEphemeral ){
89508     int i;                        /* Loop counter */
89509     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
89510     Select *pLoop;                /* For looping through SELECT statements */
89511     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
89512     int nCol;                     /* Number of columns in result set */
89513
89514     assert( p->pRightmost==p );
89515     nCol = p->pEList->nExpr;
89516     pKeyInfo = sqlite3DbMallocZero(db,
89517                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
89518     if( !pKeyInfo ){
89519       rc = SQLITE_NOMEM;
89520       goto multi_select_end;
89521     }
89522
89523     pKeyInfo->enc = ENC(db);
89524     pKeyInfo->nField = (u16)nCol;
89525
89526     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
89527       *apColl = multiSelectCollSeq(pParse, p, i);
89528       if( 0==*apColl ){
89529         *apColl = db->pDfltColl;
89530       }
89531     }
89532
89533     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
89534       for(i=0; i<2; i++){
89535         int addr = pLoop->addrOpenEphm[i];
89536         if( addr<0 ){
89537           /* If [0] is unused then [1] is also unused.  So we can
89538           ** always safely abort as soon as the first unused slot is found */
89539           assert( pLoop->addrOpenEphm[1]<0 );
89540           break;
89541         }
89542         sqlite3VdbeChangeP2(v, addr, nCol);
89543         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
89544         pLoop->addrOpenEphm[i] = -1;
89545       }
89546     }
89547     sqlite3DbFree(db, pKeyInfo);
89548   }
89549
89550 multi_select_end:
89551   pDest->iMem = dest.iMem;
89552   pDest->nMem = dest.nMem;
89553   sqlite3SelectDelete(db, pDelete);
89554   return rc;
89555 }
89556 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
89557
89558 /*
89559 ** Code an output subroutine for a coroutine implementation of a
89560 ** SELECT statment.
89561 **
89562 ** The data to be output is contained in pIn->iMem.  There are
89563 ** pIn->nMem columns to be output.  pDest is where the output should
89564 ** be sent.
89565 **
89566 ** regReturn is the number of the register holding the subroutine
89567 ** return address.
89568 **
89569 ** If regPrev>0 then it is the first register in a vector that
89570 ** records the previous output.  mem[regPrev] is a flag that is false
89571 ** if there has been no previous output.  If regPrev>0 then code is
89572 ** generated to suppress duplicates.  pKeyInfo is used for comparing
89573 ** keys.
89574 **
89575 ** If the LIMIT found in p->iLimit is reached, jump immediately to
89576 ** iBreak.
89577 */
89578 static int generateOutputSubroutine(
89579   Parse *pParse,          /* Parsing context */
89580   Select *p,              /* The SELECT statement */
89581   SelectDest *pIn,        /* Coroutine supplying data */
89582   SelectDest *pDest,      /* Where to send the data */
89583   int regReturn,          /* The return address register */
89584   int regPrev,            /* Previous result register.  No uniqueness if 0 */
89585   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
89586   int p4type,             /* The p4 type for pKeyInfo */
89587   int iBreak              /* Jump here if we hit the LIMIT */
89588 ){
89589   Vdbe *v = pParse->pVdbe;
89590   int iContinue;
89591   int addr;
89592
89593   addr = sqlite3VdbeCurrentAddr(v);
89594   iContinue = sqlite3VdbeMakeLabel(v);
89595
89596   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
89597   */
89598   if( regPrev ){
89599     int j1, j2;
89600     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
89601     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
89602                               (char*)pKeyInfo, p4type);
89603     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
89604     sqlite3VdbeJumpHere(v, j1);
89605     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
89606     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
89607   }
89608   if( pParse->db->mallocFailed ) return 0;
89609
89610   /* Suppress the the first OFFSET entries if there is an OFFSET clause
89611   */
89612   codeOffset(v, p, iContinue);
89613
89614   switch( pDest->eDest ){
89615     /* Store the result as data using a unique key.
89616     */
89617     case SRT_Table:
89618     case SRT_EphemTab: {
89619       int r1 = sqlite3GetTempReg(pParse);
89620       int r2 = sqlite3GetTempReg(pParse);
89621       testcase( pDest->eDest==SRT_Table );
89622       testcase( pDest->eDest==SRT_EphemTab );
89623       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
89624       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
89625       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
89626       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89627       sqlite3ReleaseTempReg(pParse, r2);
89628       sqlite3ReleaseTempReg(pParse, r1);
89629       break;
89630     }
89631
89632 #ifndef SQLITE_OMIT_SUBQUERY
89633     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
89634     ** then there should be a single item on the stack.  Write this
89635     ** item into the set table with bogus data.
89636     */
89637     case SRT_Set: {
89638       int r1;
89639       assert( pIn->nMem==1 );
89640       p->affinity = 
89641          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
89642       r1 = sqlite3GetTempReg(pParse);
89643       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
89644       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
89645       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
89646       sqlite3ReleaseTempReg(pParse, r1);
89647       break;
89648     }
89649
89650 #if 0  /* Never occurs on an ORDER BY query */
89651     /* If any row exist in the result set, record that fact and abort.
89652     */
89653     case SRT_Exists: {
89654       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
89655       /* The LIMIT clause will terminate the loop for us */
89656       break;
89657     }
89658 #endif
89659
89660     /* If this is a scalar select that is part of an expression, then
89661     ** store the results in the appropriate memory cell and break out
89662     ** of the scan loop.
89663     */
89664     case SRT_Mem: {
89665       assert( pIn->nMem==1 );
89666       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
89667       /* The LIMIT clause will jump out of the loop for us */
89668       break;
89669     }
89670 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
89671
89672     /* The results are stored in a sequence of registers
89673     ** starting at pDest->iMem.  Then the co-routine yields.
89674     */
89675     case SRT_Coroutine: {
89676       if( pDest->iMem==0 ){
89677         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
89678         pDest->nMem = pIn->nMem;
89679       }
89680       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
89681       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
89682       break;
89683     }
89684
89685     /* If none of the above, then the result destination must be
89686     ** SRT_Output.  This routine is never called with any other
89687     ** destination other than the ones handled above or SRT_Output.
89688     **
89689     ** For SRT_Output, results are stored in a sequence of registers.  
89690     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
89691     ** return the next row of result.
89692     */
89693     default: {
89694       assert( pDest->eDest==SRT_Output );
89695       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
89696       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
89697       break;
89698     }
89699   }
89700
89701   /* Jump to the end of the loop if the LIMIT is reached.
89702   */
89703   if( p->iLimit ){
89704     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
89705   }
89706
89707   /* Generate the subroutine return
89708   */
89709   sqlite3VdbeResolveLabel(v, iContinue);
89710   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
89711
89712   return addr;
89713 }
89714
89715 /*
89716 ** Alternative compound select code generator for cases when there
89717 ** is an ORDER BY clause.
89718 **
89719 ** We assume a query of the following form:
89720 **
89721 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
89722 **
89723 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
89724 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
89725 ** co-routines.  Then run the co-routines in parallel and merge the results
89726 ** into the output.  In addition to the two coroutines (called selectA and
89727 ** selectB) there are 7 subroutines:
89728 **
89729 **    outA:    Move the output of the selectA coroutine into the output
89730 **             of the compound query.
89731 **
89732 **    outB:    Move the output of the selectB coroutine into the output
89733 **             of the compound query.  (Only generated for UNION and
89734 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
89735 **             appears only in B.)
89736 **
89737 **    AltB:    Called when there is data from both coroutines and A<B.
89738 **
89739 **    AeqB:    Called when there is data from both coroutines and A==B.
89740 **
89741 **    AgtB:    Called when there is data from both coroutines and A>B.
89742 **
89743 **    EofA:    Called when data is exhausted from selectA.
89744 **
89745 **    EofB:    Called when data is exhausted from selectB.
89746 **
89747 ** The implementation of the latter five subroutines depend on which 
89748 ** <operator> is used:
89749 **
89750 **
89751 **             UNION ALL         UNION            EXCEPT          INTERSECT
89752 **          -------------  -----------------  --------------  -----------------
89753 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
89754 **
89755 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
89756 **
89757 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
89758 **
89759 **   EofA:   outB, nextB      outB, nextB          halt             halt
89760 **
89761 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
89762 **
89763 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
89764 ** causes an immediate jump to EofA and an EOF on B following nextB causes
89765 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
89766 ** following nextX causes a jump to the end of the select processing.
89767 **
89768 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
89769 ** within the output subroutine.  The regPrev register set holds the previously
89770 ** output value.  A comparison is made against this value and the output
89771 ** is skipped if the next results would be the same as the previous.
89772 **
89773 ** The implementation plan is to implement the two coroutines and seven
89774 ** subroutines first, then put the control logic at the bottom.  Like this:
89775 **
89776 **          goto Init
89777 **     coA: coroutine for left query (A)
89778 **     coB: coroutine for right query (B)
89779 **    outA: output one row of A
89780 **    outB: output one row of B (UNION and UNION ALL only)
89781 **    EofA: ...
89782 **    EofB: ...
89783 **    AltB: ...
89784 **    AeqB: ...
89785 **    AgtB: ...
89786 **    Init: initialize coroutine registers
89787 **          yield coA
89788 **          if eof(A) goto EofA
89789 **          yield coB
89790 **          if eof(B) goto EofB
89791 **    Cmpr: Compare A, B
89792 **          Jump AltB, AeqB, AgtB
89793 **     End: ...
89794 **
89795 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
89796 ** actually called using Gosub and they do not Return.  EofA and EofB loop
89797 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
89798 ** and AgtB jump to either L2 or to one of EofA or EofB.
89799 */
89800 #ifndef SQLITE_OMIT_COMPOUND_SELECT
89801 static int multiSelectOrderBy(
89802   Parse *pParse,        /* Parsing context */
89803   Select *p,            /* The right-most of SELECTs to be coded */
89804   SelectDest *pDest     /* What to do with query results */
89805 ){
89806   int i, j;             /* Loop counters */
89807   Select *pPrior;       /* Another SELECT immediately to our left */
89808   Vdbe *v;              /* Generate code to this VDBE */
89809   SelectDest destA;     /* Destination for coroutine A */
89810   SelectDest destB;     /* Destination for coroutine B */
89811   int regAddrA;         /* Address register for select-A coroutine */
89812   int regEofA;          /* Flag to indicate when select-A is complete */
89813   int regAddrB;         /* Address register for select-B coroutine */
89814   int regEofB;          /* Flag to indicate when select-B is complete */
89815   int addrSelectA;      /* Address of the select-A coroutine */
89816   int addrSelectB;      /* Address of the select-B coroutine */
89817   int regOutA;          /* Address register for the output-A subroutine */
89818   int regOutB;          /* Address register for the output-B subroutine */
89819   int addrOutA;         /* Address of the output-A subroutine */
89820   int addrOutB = 0;     /* Address of the output-B subroutine */
89821   int addrEofA;         /* Address of the select-A-exhausted subroutine */
89822   int addrEofB;         /* Address of the select-B-exhausted subroutine */
89823   int addrAltB;         /* Address of the A<B subroutine */
89824   int addrAeqB;         /* Address of the A==B subroutine */
89825   int addrAgtB;         /* Address of the A>B subroutine */
89826   int regLimitA;        /* Limit register for select-A */
89827   int regLimitB;        /* Limit register for select-A */
89828   int regPrev;          /* A range of registers to hold previous output */
89829   int savedLimit;       /* Saved value of p->iLimit */
89830   int savedOffset;      /* Saved value of p->iOffset */
89831   int labelCmpr;        /* Label for the start of the merge algorithm */
89832   int labelEnd;         /* Label for the end of the overall SELECT stmt */
89833   int j1;               /* Jump instructions that get retargetted */
89834   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
89835   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
89836   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
89837   sqlite3 *db;          /* Database connection */
89838   ExprList *pOrderBy;   /* The ORDER BY clause */
89839   int nOrderBy;         /* Number of terms in the ORDER BY clause */
89840   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
89841 #ifndef SQLITE_OMIT_EXPLAIN
89842   int iSub1;            /* EQP id of left-hand query */
89843   int iSub2;            /* EQP id of right-hand query */
89844 #endif
89845
89846   assert( p->pOrderBy!=0 );
89847   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
89848   db = pParse->db;
89849   v = pParse->pVdbe;
89850   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
89851   labelEnd = sqlite3VdbeMakeLabel(v);
89852   labelCmpr = sqlite3VdbeMakeLabel(v);
89853
89854
89855   /* Patch up the ORDER BY clause
89856   */
89857   op = p->op;  
89858   pPrior = p->pPrior;
89859   assert( pPrior->pOrderBy==0 );
89860   pOrderBy = p->pOrderBy;
89861   assert( pOrderBy );
89862   nOrderBy = pOrderBy->nExpr;
89863
89864   /* For operators other than UNION ALL we have to make sure that
89865   ** the ORDER BY clause covers every term of the result set.  Add
89866   ** terms to the ORDER BY clause as necessary.
89867   */
89868   if( op!=TK_ALL ){
89869     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
89870       struct ExprList_item *pItem;
89871       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
89872         assert( pItem->iCol>0 );
89873         if( pItem->iCol==i ) break;
89874       }
89875       if( j==nOrderBy ){
89876         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
89877         if( pNew==0 ) return SQLITE_NOMEM;
89878         pNew->flags |= EP_IntValue;
89879         pNew->u.iValue = i;
89880         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
89881         pOrderBy->a[nOrderBy++].iCol = (u16)i;
89882       }
89883     }
89884   }
89885
89886   /* Compute the comparison permutation and keyinfo that is used with
89887   ** the permutation used to determine if the next
89888   ** row of results comes from selectA or selectB.  Also add explicit
89889   ** collations to the ORDER BY clause terms so that when the subqueries
89890   ** to the right and the left are evaluated, they use the correct
89891   ** collation.
89892   */
89893   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
89894   if( aPermute ){
89895     struct ExprList_item *pItem;
89896     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
89897       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
89898       aPermute[i] = pItem->iCol - 1;
89899     }
89900     pKeyMerge =
89901       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
89902     if( pKeyMerge ){
89903       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
89904       pKeyMerge->nField = (u16)nOrderBy;
89905       pKeyMerge->enc = ENC(db);
89906       for(i=0; i<nOrderBy; i++){
89907         CollSeq *pColl;
89908         Expr *pTerm = pOrderBy->a[i].pExpr;
89909         if( pTerm->flags & EP_ExpCollate ){
89910           pColl = pTerm->pColl;
89911         }else{
89912           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
89913           pTerm->flags |= EP_ExpCollate;
89914           pTerm->pColl = pColl;
89915         }
89916         pKeyMerge->aColl[i] = pColl;
89917         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
89918       }
89919     }
89920   }else{
89921     pKeyMerge = 0;
89922   }
89923
89924   /* Reattach the ORDER BY clause to the query.
89925   */
89926   p->pOrderBy = pOrderBy;
89927   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
89928
89929   /* Allocate a range of temporary registers and the KeyInfo needed
89930   ** for the logic that removes duplicate result rows when the
89931   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
89932   */
89933   if( op==TK_ALL ){
89934     regPrev = 0;
89935   }else{
89936     int nExpr = p->pEList->nExpr;
89937     assert( nOrderBy>=nExpr || db->mallocFailed );
89938     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
89939     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
89940     pKeyDup = sqlite3DbMallocZero(db,
89941                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
89942     if( pKeyDup ){
89943       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
89944       pKeyDup->nField = (u16)nExpr;
89945       pKeyDup->enc = ENC(db);
89946       for(i=0; i<nExpr; i++){
89947         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
89948         pKeyDup->aSortOrder[i] = 0;
89949       }
89950     }
89951   }
89952  
89953   /* Separate the left and the right query from one another
89954   */
89955   p->pPrior = 0;
89956   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
89957   if( pPrior->pPrior==0 ){
89958     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
89959   }
89960
89961   /* Compute the limit registers */
89962   computeLimitRegisters(pParse, p, labelEnd);
89963   if( p->iLimit && op==TK_ALL ){
89964     regLimitA = ++pParse->nMem;
89965     regLimitB = ++pParse->nMem;
89966     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
89967                                   regLimitA);
89968     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
89969   }else{
89970     regLimitA = regLimitB = 0;
89971   }
89972   sqlite3ExprDelete(db, p->pLimit);
89973   p->pLimit = 0;
89974   sqlite3ExprDelete(db, p->pOffset);
89975   p->pOffset = 0;
89976
89977   regAddrA = ++pParse->nMem;
89978   regEofA = ++pParse->nMem;
89979   regAddrB = ++pParse->nMem;
89980   regEofB = ++pParse->nMem;
89981   regOutA = ++pParse->nMem;
89982   regOutB = ++pParse->nMem;
89983   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
89984   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
89985
89986   /* Jump past the various subroutines and coroutines to the main
89987   ** merge loop
89988   */
89989   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
89990   addrSelectA = sqlite3VdbeCurrentAddr(v);
89991
89992
89993   /* Generate a coroutine to evaluate the SELECT statement to the
89994   ** left of the compound operator - the "A" select.
89995   */
89996   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
89997   pPrior->iLimit = regLimitA;
89998   explainSetInteger(iSub1, pParse->iNextSelectId);
89999   sqlite3Select(pParse, pPrior, &destA);
90000   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
90001   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
90002   VdbeNoopComment((v, "End coroutine for left SELECT"));
90003
90004   /* Generate a coroutine to evaluate the SELECT statement on 
90005   ** the right - the "B" select
90006   */
90007   addrSelectB = sqlite3VdbeCurrentAddr(v);
90008   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
90009   savedLimit = p->iLimit;
90010   savedOffset = p->iOffset;
90011   p->iLimit = regLimitB;
90012   p->iOffset = 0;  
90013   explainSetInteger(iSub2, pParse->iNextSelectId);
90014   sqlite3Select(pParse, p, &destB);
90015   p->iLimit = savedLimit;
90016   p->iOffset = savedOffset;
90017   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
90018   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
90019   VdbeNoopComment((v, "End coroutine for right SELECT"));
90020
90021   /* Generate a subroutine that outputs the current row of the A
90022   ** select as the next output row of the compound select.
90023   */
90024   VdbeNoopComment((v, "Output routine for A"));
90025   addrOutA = generateOutputSubroutine(pParse,
90026                  p, &destA, pDest, regOutA,
90027                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
90028   
90029   /* Generate a subroutine that outputs the current row of the B
90030   ** select as the next output row of the compound select.
90031   */
90032   if( op==TK_ALL || op==TK_UNION ){
90033     VdbeNoopComment((v, "Output routine for B"));
90034     addrOutB = generateOutputSubroutine(pParse,
90035                  p, &destB, pDest, regOutB,
90036                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
90037   }
90038
90039   /* Generate a subroutine to run when the results from select A
90040   ** are exhausted and only data in select B remains.
90041   */
90042   VdbeNoopComment((v, "eof-A subroutine"));
90043   if( op==TK_EXCEPT || op==TK_INTERSECT ){
90044     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
90045   }else{  
90046     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
90047     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
90048     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
90049     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
90050     p->nSelectRow += pPrior->nSelectRow;
90051   }
90052
90053   /* Generate a subroutine to run when the results from select B
90054   ** are exhausted and only data in select A remains.
90055   */
90056   if( op==TK_INTERSECT ){
90057     addrEofB = addrEofA;
90058     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
90059   }else{  
90060     VdbeNoopComment((v, "eof-B subroutine"));
90061     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
90062     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
90063     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
90064     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
90065   }
90066
90067   /* Generate code to handle the case of A<B
90068   */
90069   VdbeNoopComment((v, "A-lt-B subroutine"));
90070   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
90071   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
90072   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
90073   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
90074
90075   /* Generate code to handle the case of A==B
90076   */
90077   if( op==TK_ALL ){
90078     addrAeqB = addrAltB;
90079   }else if( op==TK_INTERSECT ){
90080     addrAeqB = addrAltB;
90081     addrAltB++;
90082   }else{
90083     VdbeNoopComment((v, "A-eq-B subroutine"));
90084     addrAeqB =
90085     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
90086     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
90087     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
90088   }
90089
90090   /* Generate code to handle the case of A>B
90091   */
90092   VdbeNoopComment((v, "A-gt-B subroutine"));
90093   addrAgtB = sqlite3VdbeCurrentAddr(v);
90094   if( op==TK_ALL || op==TK_UNION ){
90095     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
90096   }
90097   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
90098   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
90099   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
90100
90101   /* This code runs once to initialize everything.
90102   */
90103   sqlite3VdbeJumpHere(v, j1);
90104   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
90105   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
90106   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
90107   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
90108   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
90109   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
90110
90111   /* Implement the main merge loop
90112   */
90113   sqlite3VdbeResolveLabel(v, labelCmpr);
90114   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
90115   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
90116                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
90117   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
90118
90119   /* Release temporary registers
90120   */
90121   if( regPrev ){
90122     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
90123   }
90124
90125   /* Jump to the this point in order to terminate the query.
90126   */
90127   sqlite3VdbeResolveLabel(v, labelEnd);
90128
90129   /* Set the number of output columns
90130   */
90131   if( pDest->eDest==SRT_Output ){
90132     Select *pFirst = pPrior;
90133     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
90134     generateColumnNames(pParse, 0, pFirst->pEList);
90135   }
90136
90137   /* Reassembly the compound query so that it will be freed correctly
90138   ** by the calling function */
90139   if( p->pPrior ){
90140     sqlite3SelectDelete(db, p->pPrior);
90141   }
90142   p->pPrior = pPrior;
90143
90144   /*** TBD:  Insert subroutine calls to close cursors on incomplete
90145   **** subqueries ****/
90146   explainComposite(pParse, p->op, iSub1, iSub2, 0);
90147   return SQLITE_OK;
90148 }
90149 #endif
90150
90151 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
90152 /* Forward Declarations */
90153 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
90154 static void substSelect(sqlite3*, Select *, int, ExprList *);
90155
90156 /*
90157 ** Scan through the expression pExpr.  Replace every reference to
90158 ** a column in table number iTable with a copy of the iColumn-th
90159 ** entry in pEList.  (But leave references to the ROWID column 
90160 ** unchanged.)
90161 **
90162 ** This routine is part of the flattening procedure.  A subquery
90163 ** whose result set is defined by pEList appears as entry in the
90164 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
90165 ** FORM clause entry is iTable.  This routine make the necessary 
90166 ** changes to pExpr so that it refers directly to the source table
90167 ** of the subquery rather the result set of the subquery.
90168 */
90169 static Expr *substExpr(
90170   sqlite3 *db,        /* Report malloc errors to this connection */
90171   Expr *pExpr,        /* Expr in which substitution occurs */
90172   int iTable,         /* Table to be substituted */
90173   ExprList *pEList    /* Substitute expressions */
90174 ){
90175   if( pExpr==0 ) return 0;
90176   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
90177     if( pExpr->iColumn<0 ){
90178       pExpr->op = TK_NULL;
90179     }else{
90180       Expr *pNew;
90181       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
90182       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
90183       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
90184       if( pNew && pExpr->pColl ){
90185         pNew->pColl = pExpr->pColl;
90186       }
90187       sqlite3ExprDelete(db, pExpr);
90188       pExpr = pNew;
90189     }
90190   }else{
90191     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
90192     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
90193     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
90194       substSelect(db, pExpr->x.pSelect, iTable, pEList);
90195     }else{
90196       substExprList(db, pExpr->x.pList, iTable, pEList);
90197     }
90198   }
90199   return pExpr;
90200 }
90201 static void substExprList(
90202   sqlite3 *db,         /* Report malloc errors here */
90203   ExprList *pList,     /* List to scan and in which to make substitutes */
90204   int iTable,          /* Table to be substituted */
90205   ExprList *pEList     /* Substitute values */
90206 ){
90207   int i;
90208   if( pList==0 ) return;
90209   for(i=0; i<pList->nExpr; i++){
90210     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
90211   }
90212 }
90213 static void substSelect(
90214   sqlite3 *db,         /* Report malloc errors here */
90215   Select *p,           /* SELECT statement in which to make substitutions */
90216   int iTable,          /* Table to be replaced */
90217   ExprList *pEList     /* Substitute values */
90218 ){
90219   SrcList *pSrc;
90220   struct SrcList_item *pItem;
90221   int i;
90222   if( !p ) return;
90223   substExprList(db, p->pEList, iTable, pEList);
90224   substExprList(db, p->pGroupBy, iTable, pEList);
90225   substExprList(db, p->pOrderBy, iTable, pEList);
90226   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
90227   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
90228   substSelect(db, p->pPrior, iTable, pEList);
90229   pSrc = p->pSrc;
90230   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
90231   if( ALWAYS(pSrc) ){
90232     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
90233       substSelect(db, pItem->pSelect, iTable, pEList);
90234     }
90235   }
90236 }
90237 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
90238
90239 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
90240 /*
90241 ** This routine attempts to flatten subqueries in order to speed
90242 ** execution.  It returns 1 if it makes changes and 0 if no flattening
90243 ** occurs.
90244 **
90245 ** To understand the concept of flattening, consider the following
90246 ** query:
90247 **
90248 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
90249 **
90250 ** The default way of implementing this query is to execute the
90251 ** subquery first and store the results in a temporary table, then
90252 ** run the outer query on that temporary table.  This requires two
90253 ** passes over the data.  Furthermore, because the temporary table
90254 ** has no indices, the WHERE clause on the outer query cannot be
90255 ** optimized.
90256 **
90257 ** This routine attempts to rewrite queries such as the above into
90258 ** a single flat select, like this:
90259 **
90260 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
90261 **
90262 ** The code generated for this simpification gives the same result
90263 ** but only has to scan the data once.  And because indices might 
90264 ** exist on the table t1, a complete scan of the data might be
90265 ** avoided.
90266 **
90267 ** Flattening is only attempted if all of the following are true:
90268 **
90269 **   (1)  The subquery and the outer query do not both use aggregates.
90270 **
90271 **   (2)  The subquery is not an aggregate or the outer query is not a join.
90272 **
90273 **   (3)  The subquery is not the right operand of a left outer join
90274 **        (Originally ticket #306.  Strengthened by ticket #3300)
90275 **
90276 **   (4)  The subquery is not DISTINCT.
90277 **
90278 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
90279 **        sub-queries that were excluded from this optimization. Restriction 
90280 **        (4) has since been expanded to exclude all DISTINCT subqueries.
90281 **
90282 **   (6)  The subquery does not use aggregates or the outer query is not
90283 **        DISTINCT.
90284 **
90285 **   (7)  The subquery has a FROM clause.
90286 **
90287 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
90288 **
90289 **   (9)  The subquery does not use LIMIT or the outer query does not use
90290 **        aggregates.
90291 **
90292 **  (10)  The subquery does not use aggregates or the outer query does not
90293 **        use LIMIT.
90294 **
90295 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
90296 **
90297 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
90298 **        a separate restriction deriving from ticket #350.
90299 **
90300 **  (13)  The subquery and outer query do not both use LIMIT.
90301 **
90302 **  (14)  The subquery does not use OFFSET.
90303 **
90304 **  (15)  The outer query is not part of a compound select or the
90305 **        subquery does not have a LIMIT clause.
90306 **        (See ticket #2339 and ticket [02a8e81d44]).
90307 **
90308 **  (16)  The outer query is not an aggregate or the subquery does
90309 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
90310 **        until we introduced the group_concat() function.  
90311 **
90312 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
90313 **        compound clause made up entirely of non-aggregate queries, and 
90314 **        the parent query:
90315 **
90316 **          * is not itself part of a compound select,
90317 **          * is not an aggregate or DISTINCT query, and
90318 **          * has no other tables or sub-selects in the FROM clause.
90319 **
90320 **        The parent and sub-query may contain WHERE clauses. Subject to
90321 **        rules (11), (13) and (14), they may also contain ORDER BY,
90322 **        LIMIT and OFFSET clauses.
90323 **
90324 **  (18)  If the sub-query is a compound select, then all terms of the
90325 **        ORDER by clause of the parent must be simple references to 
90326 **        columns of the sub-query.
90327 **
90328 **  (19)  The subquery does not use LIMIT or the outer query does not
90329 **        have a WHERE clause.
90330 **
90331 **  (20)  If the sub-query is a compound select, then it must not use
90332 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
90333 **        somewhat by saying that the terms of the ORDER BY clause must
90334 **        appear as unmodified result columns in the outer query.  But
90335 **        have other optimizations in mind to deal with that case.
90336 **
90337 ** In this routine, the "p" parameter is a pointer to the outer query.
90338 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
90339 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
90340 **
90341 ** If flattening is not attempted, this routine is a no-op and returns 0.
90342 ** If flattening is attempted this routine returns 1.
90343 **
90344 ** All of the expression analysis must occur on both the outer query and
90345 ** the subquery before this routine runs.
90346 */
90347 static int flattenSubquery(
90348   Parse *pParse,       /* Parsing context */
90349   Select *p,           /* The parent or outer SELECT statement */
90350   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
90351   int isAgg,           /* True if outer SELECT uses aggregate functions */
90352   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
90353 ){
90354   const char *zSavedAuthContext = pParse->zAuthContext;
90355   Select *pParent;
90356   Select *pSub;       /* The inner query or "subquery" */
90357   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
90358   SrcList *pSrc;      /* The FROM clause of the outer query */
90359   SrcList *pSubSrc;   /* The FROM clause of the subquery */
90360   ExprList *pList;    /* The result set of the outer query */
90361   int iParent;        /* VDBE cursor number of the pSub result set temp table */
90362   int i;              /* Loop counter */
90363   Expr *pWhere;                    /* The WHERE clause */
90364   struct SrcList_item *pSubitem;   /* The subquery */
90365   sqlite3 *db = pParse->db;
90366
90367   /* Check to see if flattening is permitted.  Return 0 if not.
90368   */
90369   assert( p!=0 );
90370   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
90371   if( db->flags & SQLITE_QueryFlattener ) return 0;
90372   pSrc = p->pSrc;
90373   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
90374   pSubitem = &pSrc->a[iFrom];
90375   iParent = pSubitem->iCursor;
90376   pSub = pSubitem->pSelect;
90377   assert( pSub!=0 );
90378   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
90379   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
90380   pSubSrc = pSub->pSrc;
90381   assert( pSubSrc );
90382   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
90383   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
90384   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
90385   ** became arbitrary expressions, we were forced to add restrictions (13)
90386   ** and (14). */
90387   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
90388   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
90389   if( p->pRightmost && pSub->pLimit ){
90390     return 0;                                            /* Restriction (15) */
90391   }
90392   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
90393   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
90394   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
90395      return 0;         /* Restrictions (8)(9) */
90396   }
90397   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
90398      return 0;         /* Restriction (6)  */
90399   }
90400   if( p->pOrderBy && pSub->pOrderBy ){
90401      return 0;                                           /* Restriction (11) */
90402   }
90403   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
90404   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
90405
90406   /* OBSOLETE COMMENT 1:
90407   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
90408   ** not used as the right operand of an outer join.  Examples of why this
90409   ** is not allowed:
90410   **
90411   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
90412   **
90413   ** If we flatten the above, we would get
90414   **
90415   **         (t1 LEFT OUTER JOIN t2) JOIN t3
90416   **
90417   ** which is not at all the same thing.
90418   **
90419   ** OBSOLETE COMMENT 2:
90420   ** Restriction 12:  If the subquery is the right operand of a left outer
90421   ** join, make sure the subquery has no WHERE clause.
90422   ** An examples of why this is not allowed:
90423   **
90424   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
90425   **
90426   ** If we flatten the above, we would get
90427   **
90428   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
90429   **
90430   ** But the t2.x>0 test will always fail on a NULL row of t2, which
90431   ** effectively converts the OUTER JOIN into an INNER JOIN.
90432   **
90433   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
90434   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
90435   ** is fraught with danger.  Best to avoid the whole thing.  If the
90436   ** subquery is the right term of a LEFT JOIN, then do not flatten.
90437   */
90438   if( (pSubitem->jointype & JT_OUTER)!=0 ){
90439     return 0;
90440   }
90441
90442   /* Restriction 17: If the sub-query is a compound SELECT, then it must
90443   ** use only the UNION ALL operator. And none of the simple select queries
90444   ** that make up the compound SELECT are allowed to be aggregate or distinct
90445   ** queries.
90446   */
90447   if( pSub->pPrior ){
90448     if( pSub->pOrderBy ){
90449       return 0;  /* Restriction 20 */
90450     }
90451     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
90452       return 0;
90453     }
90454     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
90455       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
90456       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
90457       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
90458        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
90459        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
90460       ){
90461         return 0;
90462       }
90463     }
90464
90465     /* Restriction 18. */
90466     if( p->pOrderBy ){
90467       int ii;
90468       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
90469         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
90470       }
90471     }
90472   }
90473
90474   /***** If we reach this point, flattening is permitted. *****/
90475
90476   /* Authorize the subquery */
90477   pParse->zAuthContext = pSubitem->zName;
90478   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
90479   pParse->zAuthContext = zSavedAuthContext;
90480
90481   /* If the sub-query is a compound SELECT statement, then (by restrictions
90482   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
90483   ** be of the form:
90484   **
90485   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
90486   **
90487   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
90488   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
90489   ** OFFSET clauses and joins them to the left-hand-side of the original
90490   ** using UNION ALL operators. In this case N is the number of simple
90491   ** select statements in the compound sub-query.
90492   **
90493   ** Example:
90494   **
90495   **     SELECT a+1 FROM (
90496   **        SELECT x FROM tab
90497   **        UNION ALL
90498   **        SELECT y FROM tab
90499   **        UNION ALL
90500   **        SELECT abs(z*2) FROM tab2
90501   **     ) WHERE a!=5 ORDER BY 1
90502   **
90503   ** Transformed into:
90504   **
90505   **     SELECT x+1 FROM tab WHERE x+1!=5
90506   **     UNION ALL
90507   **     SELECT y+1 FROM tab WHERE y+1!=5
90508   **     UNION ALL
90509   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
90510   **     ORDER BY 1
90511   **
90512   ** We call this the "compound-subquery flattening".
90513   */
90514   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
90515     Select *pNew;
90516     ExprList *pOrderBy = p->pOrderBy;
90517     Expr *pLimit = p->pLimit;
90518     Select *pPrior = p->pPrior;
90519     p->pOrderBy = 0;
90520     p->pSrc = 0;
90521     p->pPrior = 0;
90522     p->pLimit = 0;
90523     pNew = sqlite3SelectDup(db, p, 0);
90524     p->pLimit = pLimit;
90525     p->pOrderBy = pOrderBy;
90526     p->pSrc = pSrc;
90527     p->op = TK_ALL;
90528     p->pRightmost = 0;
90529     if( pNew==0 ){
90530       pNew = pPrior;
90531     }else{
90532       pNew->pPrior = pPrior;
90533       pNew->pRightmost = 0;
90534     }
90535     p->pPrior = pNew;
90536     if( db->mallocFailed ) return 1;
90537   }
90538
90539   /* Begin flattening the iFrom-th entry of the FROM clause 
90540   ** in the outer query.
90541   */
90542   pSub = pSub1 = pSubitem->pSelect;
90543
90544   /* Delete the transient table structure associated with the
90545   ** subquery
90546   */
90547   sqlite3DbFree(db, pSubitem->zDatabase);
90548   sqlite3DbFree(db, pSubitem->zName);
90549   sqlite3DbFree(db, pSubitem->zAlias);
90550   pSubitem->zDatabase = 0;
90551   pSubitem->zName = 0;
90552   pSubitem->zAlias = 0;
90553   pSubitem->pSelect = 0;
90554
90555   /* Defer deleting the Table object associated with the
90556   ** subquery until code generation is
90557   ** complete, since there may still exist Expr.pTab entries that
90558   ** refer to the subquery even after flattening.  Ticket #3346.
90559   **
90560   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
90561   */
90562   if( ALWAYS(pSubitem->pTab!=0) ){
90563     Table *pTabToDel = pSubitem->pTab;
90564     if( pTabToDel->nRef==1 ){
90565       Parse *pToplevel = sqlite3ParseToplevel(pParse);
90566       pTabToDel->pNextZombie = pToplevel->pZombieTab;
90567       pToplevel->pZombieTab = pTabToDel;
90568     }else{
90569       pTabToDel->nRef--;
90570     }
90571     pSubitem->pTab = 0;
90572   }
90573
90574   /* The following loop runs once for each term in a compound-subquery
90575   ** flattening (as described above).  If we are doing a different kind
90576   ** of flattening - a flattening other than a compound-subquery flattening -
90577   ** then this loop only runs once.
90578   **
90579   ** This loop moves all of the FROM elements of the subquery into the
90580   ** the FROM clause of the outer query.  Before doing this, remember
90581   ** the cursor number for the original outer query FROM element in
90582   ** iParent.  The iParent cursor will never be used.  Subsequent code
90583   ** will scan expressions looking for iParent references and replace
90584   ** those references with expressions that resolve to the subquery FROM
90585   ** elements we are now copying in.
90586   */
90587   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
90588     int nSubSrc;
90589     u8 jointype = 0;
90590     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
90591     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
90592     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
90593
90594     if( pSrc ){
90595       assert( pParent==p );  /* First time through the loop */
90596       jointype = pSubitem->jointype;
90597     }else{
90598       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
90599       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
90600       if( pSrc==0 ){
90601         assert( db->mallocFailed );
90602         break;
90603       }
90604     }
90605
90606     /* The subquery uses a single slot of the FROM clause of the outer
90607     ** query.  If the subquery has more than one element in its FROM clause,
90608     ** then expand the outer query to make space for it to hold all elements
90609     ** of the subquery.
90610     **
90611     ** Example:
90612     **
90613     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
90614     **
90615     ** The outer query has 3 slots in its FROM clause.  One slot of the
90616     ** outer query (the middle slot) is used by the subquery.  The next
90617     ** block of code will expand the out query to 4 slots.  The middle
90618     ** slot is expanded to two slots in order to make space for the
90619     ** two elements in the FROM clause of the subquery.
90620     */
90621     if( nSubSrc>1 ){
90622       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
90623       if( db->mallocFailed ){
90624         break;
90625       }
90626     }
90627
90628     /* Transfer the FROM clause terms from the subquery into the
90629     ** outer query.
90630     */
90631     for(i=0; i<nSubSrc; i++){
90632       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
90633       pSrc->a[i+iFrom] = pSubSrc->a[i];
90634       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
90635     }
90636     pSrc->a[iFrom].jointype = jointype;
90637   
90638     /* Now begin substituting subquery result set expressions for 
90639     ** references to the iParent in the outer query.
90640     ** 
90641     ** Example:
90642     **
90643     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
90644     **   \                     \_____________ subquery __________/          /
90645     **    \_____________________ outer query ______________________________/
90646     **
90647     ** We look at every expression in the outer query and every place we see
90648     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
90649     */
90650     pList = pParent->pEList;
90651     for(i=0; i<pList->nExpr; i++){
90652       if( pList->a[i].zName==0 ){
90653         const char *zSpan = pList->a[i].zSpan;
90654         if( ALWAYS(zSpan) ){
90655           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
90656         }
90657       }
90658     }
90659     substExprList(db, pParent->pEList, iParent, pSub->pEList);
90660     if( isAgg ){
90661       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
90662       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
90663     }
90664     if( pSub->pOrderBy ){
90665       assert( pParent->pOrderBy==0 );
90666       pParent->pOrderBy = pSub->pOrderBy;
90667       pSub->pOrderBy = 0;
90668     }else if( pParent->pOrderBy ){
90669       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
90670     }
90671     if( pSub->pWhere ){
90672       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
90673     }else{
90674       pWhere = 0;
90675     }
90676     if( subqueryIsAgg ){
90677       assert( pParent->pHaving==0 );
90678       pParent->pHaving = pParent->pWhere;
90679       pParent->pWhere = pWhere;
90680       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
90681       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
90682                                   sqlite3ExprDup(db, pSub->pHaving, 0));
90683       assert( pParent->pGroupBy==0 );
90684       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
90685     }else{
90686       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
90687       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
90688     }
90689   
90690     /* The flattened query is distinct if either the inner or the
90691     ** outer query is distinct. 
90692     */
90693     pParent->selFlags |= pSub->selFlags & SF_Distinct;
90694   
90695     /*
90696     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
90697     **
90698     ** One is tempted to try to add a and b to combine the limits.  But this
90699     ** does not work if either limit is negative.
90700     */
90701     if( pSub->pLimit ){
90702       pParent->pLimit = pSub->pLimit;
90703       pSub->pLimit = 0;
90704     }
90705   }
90706
90707   /* Finially, delete what is left of the subquery and return
90708   ** success.
90709   */
90710   sqlite3SelectDelete(db, pSub1);
90711
90712   return 1;
90713 }
90714 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
90715
90716 /*
90717 ** Analyze the SELECT statement passed as an argument to see if it
90718 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
90719 ** it is, or 0 otherwise. At present, a query is considered to be
90720 ** a min()/max() query if:
90721 **
90722 **   1. There is a single object in the FROM clause.
90723 **
90724 **   2. There is a single expression in the result set, and it is
90725 **      either min(x) or max(x), where x is a column reference.
90726 */
90727 static u8 minMaxQuery(Select *p){
90728   Expr *pExpr;
90729   ExprList *pEList = p->pEList;
90730
90731   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
90732   pExpr = pEList->a[0].pExpr;
90733   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
90734   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
90735   pEList = pExpr->x.pList;
90736   if( pEList==0 || pEList->nExpr!=1 ) return 0;
90737   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
90738   assert( !ExprHasProperty(pExpr, EP_IntValue) );
90739   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
90740     return WHERE_ORDERBY_MIN;
90741   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
90742     return WHERE_ORDERBY_MAX;
90743   }
90744   return WHERE_ORDERBY_NORMAL;
90745 }
90746
90747 /*
90748 ** The select statement passed as the first argument is an aggregate query.
90749 ** The second argment is the associated aggregate-info object. This 
90750 ** function tests if the SELECT is of the form:
90751 **
90752 **   SELECT count(*) FROM <tbl>
90753 **
90754 ** where table is a database table, not a sub-select or view. If the query
90755 ** does match this pattern, then a pointer to the Table object representing
90756 ** <tbl> is returned. Otherwise, 0 is returned.
90757 */
90758 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
90759   Table *pTab;
90760   Expr *pExpr;
90761
90762   assert( !p->pGroupBy );
90763
90764   if( p->pWhere || p->pEList->nExpr!=1 
90765    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
90766   ){
90767     return 0;
90768   }
90769   pTab = p->pSrc->a[0].pTab;
90770   pExpr = p->pEList->a[0].pExpr;
90771   assert( pTab && !pTab->pSelect && pExpr );
90772
90773   if( IsVirtual(pTab) ) return 0;
90774   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
90775   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
90776   if( pExpr->flags&EP_Distinct ) return 0;
90777
90778   return pTab;
90779 }
90780
90781 /*
90782 ** If the source-list item passed as an argument was augmented with an
90783 ** INDEXED BY clause, then try to locate the specified index. If there
90784 ** was such a clause and the named index cannot be found, return 
90785 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
90786 ** pFrom->pIndex and return SQLITE_OK.
90787 */
90788 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
90789   if( pFrom->pTab && pFrom->zIndex ){
90790     Table *pTab = pFrom->pTab;
90791     char *zIndex = pFrom->zIndex;
90792     Index *pIdx;
90793     for(pIdx=pTab->pIndex; 
90794         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
90795         pIdx=pIdx->pNext
90796     );
90797     if( !pIdx ){
90798       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
90799       pParse->checkSchema = 1;
90800       return SQLITE_ERROR;
90801     }
90802     pFrom->pIndex = pIdx;
90803   }
90804   return SQLITE_OK;
90805 }
90806
90807 /*
90808 ** This routine is a Walker callback for "expanding" a SELECT statement.
90809 ** "Expanding" means to do the following:
90810 **
90811 **    (1)  Make sure VDBE cursor numbers have been assigned to every
90812 **         element of the FROM clause.
90813 **
90814 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
90815 **         defines FROM clause.  When views appear in the FROM clause,
90816 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
90817 **         that implements the view.  A copy is made of the view's SELECT
90818 **         statement so that we can freely modify or delete that statement
90819 **         without worrying about messing up the presistent representation
90820 **         of the view.
90821 **
90822 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
90823 **         on joins and the ON and USING clause of joins.
90824 **
90825 **    (4)  Scan the list of columns in the result set (pEList) looking
90826 **         for instances of the "*" operator or the TABLE.* operator.
90827 **         If found, expand each "*" to be every column in every table
90828 **         and TABLE.* to be every column in TABLE.
90829 **
90830 */
90831 static int selectExpander(Walker *pWalker, Select *p){
90832   Parse *pParse = pWalker->pParse;
90833   int i, j, k;
90834   SrcList *pTabList;
90835   ExprList *pEList;
90836   struct SrcList_item *pFrom;
90837   sqlite3 *db = pParse->db;
90838
90839   if( db->mallocFailed  ){
90840     return WRC_Abort;
90841   }
90842   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
90843     return WRC_Prune;
90844   }
90845   p->selFlags |= SF_Expanded;
90846   pTabList = p->pSrc;
90847   pEList = p->pEList;
90848
90849   /* Make sure cursor numbers have been assigned to all entries in
90850   ** the FROM clause of the SELECT statement.
90851   */
90852   sqlite3SrcListAssignCursors(pParse, pTabList);
90853
90854   /* Look up every table named in the FROM clause of the select.  If
90855   ** an entry of the FROM clause is a subquery instead of a table or view,
90856   ** then create a transient table structure to describe the subquery.
90857   */
90858   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
90859     Table *pTab;
90860     if( pFrom->pTab!=0 ){
90861       /* This statement has already been prepared.  There is no need
90862       ** to go further. */
90863       assert( i==0 );
90864       return WRC_Prune;
90865     }
90866     if( pFrom->zName==0 ){
90867 #ifndef SQLITE_OMIT_SUBQUERY
90868       Select *pSel = pFrom->pSelect;
90869       /* A sub-query in the FROM clause of a SELECT */
90870       assert( pSel!=0 );
90871       assert( pFrom->pTab==0 );
90872       sqlite3WalkSelect(pWalker, pSel);
90873       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
90874       if( pTab==0 ) return WRC_Abort;
90875       pTab->nRef = 1;
90876       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
90877       while( pSel->pPrior ){ pSel = pSel->pPrior; }
90878       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
90879       pTab->iPKey = -1;
90880       pTab->nRowEst = 1000000;
90881       pTab->tabFlags |= TF_Ephemeral;
90882 #endif
90883     }else{
90884       /* An ordinary table or view name in the FROM clause */
90885       assert( pFrom->pTab==0 );
90886       pFrom->pTab = pTab = 
90887         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
90888       if( pTab==0 ) return WRC_Abort;
90889       pTab->nRef++;
90890 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
90891       if( pTab->pSelect || IsVirtual(pTab) ){
90892         /* We reach here if the named table is a really a view */
90893         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
90894         assert( pFrom->pSelect==0 );
90895         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
90896         sqlite3WalkSelect(pWalker, pFrom->pSelect);
90897       }
90898 #endif
90899     }
90900
90901     /* Locate the index named by the INDEXED BY clause, if any. */
90902     if( sqlite3IndexedByLookup(pParse, pFrom) ){
90903       return WRC_Abort;
90904     }
90905   }
90906
90907   /* Process NATURAL keywords, and ON and USING clauses of joins.
90908   */
90909   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
90910     return WRC_Abort;
90911   }
90912
90913   /* For every "*" that occurs in the column list, insert the names of
90914   ** all columns in all tables.  And for every TABLE.* insert the names
90915   ** of all columns in TABLE.  The parser inserted a special expression
90916   ** with the TK_ALL operator for each "*" that it found in the column list.
90917   ** The following code just has to locate the TK_ALL expressions and expand
90918   ** each one to the list of all columns in all tables.
90919   **
90920   ** The first loop just checks to see if there are any "*" operators
90921   ** that need expanding.
90922   */
90923   for(k=0; k<pEList->nExpr; k++){
90924     Expr *pE = pEList->a[k].pExpr;
90925     if( pE->op==TK_ALL ) break;
90926     assert( pE->op!=TK_DOT || pE->pRight!=0 );
90927     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
90928     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
90929   }
90930   if( k<pEList->nExpr ){
90931     /*
90932     ** If we get here it means the result set contains one or more "*"
90933     ** operators that need to be expanded.  Loop through each expression
90934     ** in the result set and expand them one by one.
90935     */
90936     struct ExprList_item *a = pEList->a;
90937     ExprList *pNew = 0;
90938     int flags = pParse->db->flags;
90939     int longNames = (flags & SQLITE_FullColNames)!=0
90940                       && (flags & SQLITE_ShortColNames)==0;
90941
90942     for(k=0; k<pEList->nExpr; k++){
90943       Expr *pE = a[k].pExpr;
90944       assert( pE->op!=TK_DOT || pE->pRight!=0 );
90945       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
90946         /* This particular expression does not need to be expanded.
90947         */
90948         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
90949         if( pNew ){
90950           pNew->a[pNew->nExpr-1].zName = a[k].zName;
90951           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
90952           a[k].zName = 0;
90953           a[k].zSpan = 0;
90954         }
90955         a[k].pExpr = 0;
90956       }else{
90957         /* This expression is a "*" or a "TABLE.*" and needs to be
90958         ** expanded. */
90959         int tableSeen = 0;      /* Set to 1 when TABLE matches */
90960         char *zTName;            /* text of name of TABLE */
90961         if( pE->op==TK_DOT ){
90962           assert( pE->pLeft!=0 );
90963           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
90964           zTName = pE->pLeft->u.zToken;
90965         }else{
90966           zTName = 0;
90967         }
90968         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
90969           Table *pTab = pFrom->pTab;
90970           char *zTabName = pFrom->zAlias;
90971           if( zTabName==0 ){
90972             zTabName = pTab->zName;
90973           }
90974           if( db->mallocFailed ) break;
90975           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
90976             continue;
90977           }
90978           tableSeen = 1;
90979           for(j=0; j<pTab->nCol; j++){
90980             Expr *pExpr, *pRight;
90981             char *zName = pTab->aCol[j].zName;
90982             char *zColname;  /* The computed column name */
90983             char *zToFree;   /* Malloced string that needs to be freed */
90984             Token sColname;  /* Computed column name as a token */
90985
90986             /* If a column is marked as 'hidden' (currently only possible
90987             ** for virtual tables), do not include it in the expanded
90988             ** result-set list.
90989             */
90990             if( IsHiddenColumn(&pTab->aCol[j]) ){
90991               assert(IsVirtual(pTab));
90992               continue;
90993             }
90994
90995             if( i>0 && zTName==0 ){
90996               if( (pFrom->jointype & JT_NATURAL)!=0
90997                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
90998               ){
90999                 /* In a NATURAL join, omit the join columns from the 
91000                 ** table to the right of the join */
91001                 continue;
91002               }
91003               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
91004                 /* In a join with a USING clause, omit columns in the
91005                 ** using clause from the table on the right. */
91006                 continue;
91007               }
91008             }
91009             pRight = sqlite3Expr(db, TK_ID, zName);
91010             zColname = zName;
91011             zToFree = 0;
91012             if( longNames || pTabList->nSrc>1 ){
91013               Expr *pLeft;
91014               pLeft = sqlite3Expr(db, TK_ID, zTabName);
91015               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
91016               if( longNames ){
91017                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
91018                 zToFree = zColname;
91019               }
91020             }else{
91021               pExpr = pRight;
91022             }
91023             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
91024             sColname.z = zColname;
91025             sColname.n = sqlite3Strlen30(zColname);
91026             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
91027             sqlite3DbFree(db, zToFree);
91028           }
91029         }
91030         if( !tableSeen ){
91031           if( zTName ){
91032             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
91033           }else{
91034             sqlite3ErrorMsg(pParse, "no tables specified");
91035           }
91036         }
91037       }
91038     }
91039     sqlite3ExprListDelete(db, pEList);
91040     p->pEList = pNew;
91041   }
91042 #if SQLITE_MAX_COLUMN
91043   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
91044     sqlite3ErrorMsg(pParse, "too many columns in result set");
91045   }
91046 #endif
91047   return WRC_Continue;
91048 }
91049
91050 /*
91051 ** No-op routine for the parse-tree walker.
91052 **
91053 ** When this routine is the Walker.xExprCallback then expression trees
91054 ** are walked without any actions being taken at each node.  Presumably,
91055 ** when this routine is used for Walker.xExprCallback then 
91056 ** Walker.xSelectCallback is set to do something useful for every 
91057 ** subquery in the parser tree.
91058 */
91059 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
91060   UNUSED_PARAMETER2(NotUsed, NotUsed2);
91061   return WRC_Continue;
91062 }
91063
91064 /*
91065 ** This routine "expands" a SELECT statement and all of its subqueries.
91066 ** For additional information on what it means to "expand" a SELECT
91067 ** statement, see the comment on the selectExpand worker callback above.
91068 **
91069 ** Expanding a SELECT statement is the first step in processing a
91070 ** SELECT statement.  The SELECT statement must be expanded before
91071 ** name resolution is performed.
91072 **
91073 ** If anything goes wrong, an error message is written into pParse.
91074 ** The calling function can detect the problem by looking at pParse->nErr
91075 ** and/or pParse->db->mallocFailed.
91076 */
91077 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
91078   Walker w;
91079   w.xSelectCallback = selectExpander;
91080   w.xExprCallback = exprWalkNoop;
91081   w.pParse = pParse;
91082   sqlite3WalkSelect(&w, pSelect);
91083 }
91084
91085
91086 #ifndef SQLITE_OMIT_SUBQUERY
91087 /*
91088 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
91089 ** interface.
91090 **
91091 ** For each FROM-clause subquery, add Column.zType and Column.zColl
91092 ** information to the Table structure that represents the result set
91093 ** of that subquery.
91094 **
91095 ** The Table structure that represents the result set was constructed
91096 ** by selectExpander() but the type and collation information was omitted
91097 ** at that point because identifiers had not yet been resolved.  This
91098 ** routine is called after identifier resolution.
91099 */
91100 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
91101   Parse *pParse;
91102   int i;
91103   SrcList *pTabList;
91104   struct SrcList_item *pFrom;
91105
91106   assert( p->selFlags & SF_Resolved );
91107   if( (p->selFlags & SF_HasTypeInfo)==0 ){
91108     p->selFlags |= SF_HasTypeInfo;
91109     pParse = pWalker->pParse;
91110     pTabList = p->pSrc;
91111     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
91112       Table *pTab = pFrom->pTab;
91113       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
91114         /* A sub-query in the FROM clause of a SELECT */
91115         Select *pSel = pFrom->pSelect;
91116         assert( pSel );
91117         while( pSel->pPrior ) pSel = pSel->pPrior;
91118         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
91119       }
91120     }
91121   }
91122   return WRC_Continue;
91123 }
91124 #endif
91125
91126
91127 /*
91128 ** This routine adds datatype and collating sequence information to
91129 ** the Table structures of all FROM-clause subqueries in a
91130 ** SELECT statement.
91131 **
91132 ** Use this routine after name resolution.
91133 */
91134 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
91135 #ifndef SQLITE_OMIT_SUBQUERY
91136   Walker w;
91137   w.xSelectCallback = selectAddSubqueryTypeInfo;
91138   w.xExprCallback = exprWalkNoop;
91139   w.pParse = pParse;
91140   sqlite3WalkSelect(&w, pSelect);
91141 #endif
91142 }
91143
91144
91145 /*
91146 ** This routine sets of a SELECT statement for processing.  The
91147 ** following is accomplished:
91148 **
91149 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
91150 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
91151 **     *  ON and USING clauses are shifted into WHERE statements
91152 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
91153 **     *  Identifiers in expression are matched to tables.
91154 **
91155 ** This routine acts recursively on all subqueries within the SELECT.
91156 */
91157 SQLITE_PRIVATE void sqlite3SelectPrep(
91158   Parse *pParse,         /* The parser context */
91159   Select *p,             /* The SELECT statement being coded. */
91160   NameContext *pOuterNC  /* Name context for container */
91161 ){
91162   sqlite3 *db;
91163   if( NEVER(p==0) ) return;
91164   db = pParse->db;
91165   if( p->selFlags & SF_HasTypeInfo ) return;
91166   sqlite3SelectExpand(pParse, p);
91167   if( pParse->nErr || db->mallocFailed ) return;
91168   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
91169   if( pParse->nErr || db->mallocFailed ) return;
91170   sqlite3SelectAddTypeInfo(pParse, p);
91171 }
91172
91173 /*
91174 ** Reset the aggregate accumulator.
91175 **
91176 ** The aggregate accumulator is a set of memory cells that hold
91177 ** intermediate results while calculating an aggregate.  This
91178 ** routine simply stores NULLs in all of those memory cells.
91179 */
91180 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
91181   Vdbe *v = pParse->pVdbe;
91182   int i;
91183   struct AggInfo_func *pFunc;
91184   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
91185     return;
91186   }
91187   for(i=0; i<pAggInfo->nColumn; i++){
91188     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
91189   }
91190   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
91191     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
91192     if( pFunc->iDistinct>=0 ){
91193       Expr *pE = pFunc->pExpr;
91194       assert( !ExprHasProperty(pE, EP_xIsSelect) );
91195       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
91196         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
91197            "argument");
91198         pFunc->iDistinct = -1;
91199       }else{
91200         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
91201         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
91202                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
91203       }
91204     }
91205   }
91206 }
91207
91208 /*
91209 ** Invoke the OP_AggFinalize opcode for every aggregate function
91210 ** in the AggInfo structure.
91211 */
91212 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
91213   Vdbe *v = pParse->pVdbe;
91214   int i;
91215   struct AggInfo_func *pF;
91216   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
91217     ExprList *pList = pF->pExpr->x.pList;
91218     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
91219     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
91220                       (void*)pF->pFunc, P4_FUNCDEF);
91221   }
91222 }
91223
91224 /*
91225 ** Update the accumulator memory cells for an aggregate based on
91226 ** the current cursor position.
91227 */
91228 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
91229   Vdbe *v = pParse->pVdbe;
91230   int i;
91231   struct AggInfo_func *pF;
91232   struct AggInfo_col *pC;
91233
91234   pAggInfo->directMode = 1;
91235   sqlite3ExprCacheClear(pParse);
91236   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
91237     int nArg;
91238     int addrNext = 0;
91239     int regAgg;
91240     ExprList *pList = pF->pExpr->x.pList;
91241     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
91242     if( pList ){
91243       nArg = pList->nExpr;
91244       regAgg = sqlite3GetTempRange(pParse, nArg);
91245       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
91246     }else{
91247       nArg = 0;
91248       regAgg = 0;
91249     }
91250     if( pF->iDistinct>=0 ){
91251       addrNext = sqlite3VdbeMakeLabel(v);
91252       assert( nArg==1 );
91253       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
91254     }
91255     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
91256       CollSeq *pColl = 0;
91257       struct ExprList_item *pItem;
91258       int j;
91259       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
91260       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
91261         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
91262       }
91263       if( !pColl ){
91264         pColl = pParse->db->pDfltColl;
91265       }
91266       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
91267     }
91268     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
91269                       (void*)pF->pFunc, P4_FUNCDEF);
91270     sqlite3VdbeChangeP5(v, (u8)nArg);
91271     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
91272     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
91273     if( addrNext ){
91274       sqlite3VdbeResolveLabel(v, addrNext);
91275       sqlite3ExprCacheClear(pParse);
91276     }
91277   }
91278
91279   /* Before populating the accumulator registers, clear the column cache.
91280   ** Otherwise, if any of the required column values are already present 
91281   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
91282   ** to pC->iMem. But by the time the value is used, the original register
91283   ** may have been used, invalidating the underlying buffer holding the
91284   ** text or blob value. See ticket [883034dcb5].
91285   **
91286   ** Another solution would be to change the OP_SCopy used to copy cached
91287   ** values to an OP_Copy.
91288   */
91289   sqlite3ExprCacheClear(pParse);
91290   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
91291     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
91292   }
91293   pAggInfo->directMode = 0;
91294   sqlite3ExprCacheClear(pParse);
91295 }
91296
91297 /*
91298 ** Generate code for the SELECT statement given in the p argument.  
91299 **
91300 ** The results are distributed in various ways depending on the
91301 ** contents of the SelectDest structure pointed to by argument pDest
91302 ** as follows:
91303 **
91304 **     pDest->eDest    Result
91305 **     ------------    -------------------------------------------
91306 **     SRT_Output      Generate a row of output (using the OP_ResultRow
91307 **                     opcode) for each row in the result set.
91308 **
91309 **     SRT_Mem         Only valid if the result is a single column.
91310 **                     Store the first column of the first result row
91311 **                     in register pDest->iParm then abandon the rest
91312 **                     of the query.  This destination implies "LIMIT 1".
91313 **
91314 **     SRT_Set         The result must be a single column.  Store each
91315 **                     row of result as the key in table pDest->iParm. 
91316 **                     Apply the affinity pDest->affinity before storing
91317 **                     results.  Used to implement "IN (SELECT ...)".
91318 **
91319 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
91320 **
91321 **     SRT_Except      Remove results from the temporary table pDest->iParm.
91322 **
91323 **     SRT_Table       Store results in temporary table pDest->iParm.
91324 **                     This is like SRT_EphemTab except that the table
91325 **                     is assumed to already be open.
91326 **
91327 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
91328 **                     the result there. The cursor is left open after
91329 **                     returning.  This is like SRT_Table except that
91330 **                     this destination uses OP_OpenEphemeral to create
91331 **                     the table first.
91332 **
91333 **     SRT_Coroutine   Generate a co-routine that returns a new row of
91334 **                     results each time it is invoked.  The entry point
91335 **                     of the co-routine is stored in register pDest->iParm.
91336 **
91337 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
91338 **                     set is not empty.
91339 **
91340 **     SRT_Discard     Throw the results away.  This is used by SELECT
91341 **                     statements within triggers whose only purpose is
91342 **                     the side-effects of functions.
91343 **
91344 ** This routine returns the number of errors.  If any errors are
91345 ** encountered, then an appropriate error message is left in
91346 ** pParse->zErrMsg.
91347 **
91348 ** This routine does NOT free the Select structure passed in.  The
91349 ** calling function needs to do that.
91350 */
91351 SQLITE_PRIVATE int sqlite3Select(
91352   Parse *pParse,         /* The parser context */
91353   Select *p,             /* The SELECT statement being coded. */
91354   SelectDest *pDest      /* What to do with the query results */
91355 ){
91356   int i, j;              /* Loop counters */
91357   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
91358   Vdbe *v;               /* The virtual machine under construction */
91359   int isAgg;             /* True for select lists like "count(*)" */
91360   ExprList *pEList;      /* List of columns to extract. */
91361   SrcList *pTabList;     /* List of tables to select from */
91362   Expr *pWhere;          /* The WHERE clause.  May be NULL */
91363   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
91364   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
91365   Expr *pHaving;         /* The HAVING clause.  May be NULL */
91366   int isDistinct;        /* True if the DISTINCT keyword is present */
91367   int distinct;          /* Table to use for the distinct set */
91368   int rc = 1;            /* Value to return from this function */
91369   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
91370   AggInfo sAggInfo;      /* Information used by aggregate queries */
91371   int iEnd;              /* Address of the end of the query */
91372   sqlite3 *db;           /* The database connection */
91373
91374 #ifndef SQLITE_OMIT_EXPLAIN
91375   int iRestoreSelectId = pParse->iSelectId;
91376   pParse->iSelectId = pParse->iNextSelectId++;
91377 #endif
91378
91379   db = pParse->db;
91380   if( p==0 || db->mallocFailed || pParse->nErr ){
91381     return 1;
91382   }
91383   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
91384   memset(&sAggInfo, 0, sizeof(sAggInfo));
91385
91386   if( IgnorableOrderby(pDest) ){
91387     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
91388            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
91389     /* If ORDER BY makes no difference in the output then neither does
91390     ** DISTINCT so it can be removed too. */
91391     sqlite3ExprListDelete(db, p->pOrderBy);
91392     p->pOrderBy = 0;
91393     p->selFlags &= ~SF_Distinct;
91394   }
91395   sqlite3SelectPrep(pParse, p, 0);
91396   pOrderBy = p->pOrderBy;
91397   pTabList = p->pSrc;
91398   pEList = p->pEList;
91399   if( pParse->nErr || db->mallocFailed ){
91400     goto select_end;
91401   }
91402   isAgg = (p->selFlags & SF_Aggregate)!=0;
91403   assert( pEList!=0 );
91404
91405   /* Begin generating code.
91406   */
91407   v = sqlite3GetVdbe(pParse);
91408   if( v==0 ) goto select_end;
91409
91410   /* If writing to memory or generating a set
91411   ** only a single column may be output.
91412   */
91413 #ifndef SQLITE_OMIT_SUBQUERY
91414   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
91415     goto select_end;
91416   }
91417 #endif
91418
91419   /* Generate code for all sub-queries in the FROM clause
91420   */
91421 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
91422   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
91423     struct SrcList_item *pItem = &pTabList->a[i];
91424     SelectDest dest;
91425     Select *pSub = pItem->pSelect;
91426     int isAggSub;
91427
91428     if( pSub==0 || pItem->isPopulated ) continue;
91429
91430     /* Increment Parse.nHeight by the height of the largest expression
91431     ** tree refered to by this, the parent select. The child select
91432     ** may contain expression trees of at most
91433     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
91434     ** more conservative than necessary, but much easier than enforcing
91435     ** an exact limit.
91436     */
91437     pParse->nHeight += sqlite3SelectExprHeight(p);
91438
91439     /* Check to see if the subquery can be absorbed into the parent. */
91440     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
91441     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
91442       if( isAggSub ){
91443         isAgg = 1;
91444         p->selFlags |= SF_Aggregate;
91445       }
91446       i = -1;
91447     }else{
91448       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
91449       assert( pItem->isPopulated==0 );
91450       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
91451       sqlite3Select(pParse, pSub, &dest);
91452       pItem->isPopulated = 1;
91453       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
91454     }
91455     if( /*pParse->nErr ||*/ db->mallocFailed ){
91456       goto select_end;
91457     }
91458     pParse->nHeight -= sqlite3SelectExprHeight(p);
91459     pTabList = p->pSrc;
91460     if( !IgnorableOrderby(pDest) ){
91461       pOrderBy = p->pOrderBy;
91462     }
91463   }
91464   pEList = p->pEList;
91465 #endif
91466   pWhere = p->pWhere;
91467   pGroupBy = p->pGroupBy;
91468   pHaving = p->pHaving;
91469   isDistinct = (p->selFlags & SF_Distinct)!=0;
91470
91471 #ifndef SQLITE_OMIT_COMPOUND_SELECT
91472   /* If there is are a sequence of queries, do the earlier ones first.
91473   */
91474   if( p->pPrior ){
91475     if( p->pRightmost==0 ){
91476       Select *pLoop, *pRight = 0;
91477       int cnt = 0;
91478       int mxSelect;
91479       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
91480         pLoop->pRightmost = p;
91481         pLoop->pNext = pRight;
91482         pRight = pLoop;
91483       }
91484       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
91485       if( mxSelect && cnt>mxSelect ){
91486         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
91487         goto select_end;
91488       }
91489     }
91490     rc = multiSelect(pParse, p, pDest);
91491     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
91492     return rc;
91493   }
91494 #endif
91495
91496   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
91497   ** GROUP BY might use an index, DISTINCT never does.
91498   */
91499   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
91500   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
91501     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
91502     pGroupBy = p->pGroupBy;
91503     p->selFlags &= ~SF_Distinct;
91504   }
91505
91506   /* If there is both a GROUP BY and an ORDER BY clause and they are
91507   ** identical, then disable the ORDER BY clause since the GROUP BY
91508   ** will cause elements to come out in the correct order.  This is
91509   ** an optimization - the correct answer should result regardless.
91510   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
91511   ** to disable this optimization for testing purposes.
91512   */
91513   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
91514          && (db->flags & SQLITE_GroupByOrder)==0 ){
91515     pOrderBy = 0;
91516   }
91517
91518   /* If there is an ORDER BY clause, then this sorting
91519   ** index might end up being unused if the data can be 
91520   ** extracted in pre-sorted order.  If that is the case, then the
91521   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
91522   ** we figure out that the sorting index is not needed.  The addrSortIndex
91523   ** variable is used to facilitate that change.
91524   */
91525   if( pOrderBy ){
91526     KeyInfo *pKeyInfo;
91527     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
91528     pOrderBy->iECursor = pParse->nTab++;
91529     p->addrOpenEphm[2] = addrSortIndex =
91530       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
91531                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
91532                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
91533   }else{
91534     addrSortIndex = -1;
91535   }
91536
91537   /* If the output is destined for a temporary table, open that table.
91538   */
91539   if( pDest->eDest==SRT_EphemTab ){
91540     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
91541   }
91542
91543   /* Set the limiter.
91544   */
91545   iEnd = sqlite3VdbeMakeLabel(v);
91546   p->nSelectRow = (double)LARGEST_INT64;
91547   computeLimitRegisters(pParse, p, iEnd);
91548
91549   /* Open a virtual index to use for the distinct set.
91550   */
91551   if( p->selFlags & SF_Distinct ){
91552     KeyInfo *pKeyInfo;
91553     assert( isAgg || pGroupBy );
91554     distinct = pParse->nTab++;
91555     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
91556     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
91557                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
91558     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
91559   }else{
91560     distinct = -1;
91561   }
91562
91563   /* Aggregate and non-aggregate queries are handled differently */
91564   if( !isAgg && pGroupBy==0 ){
91565     /* This case is for non-aggregate queries
91566     ** Begin the database scan
91567     */
91568     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
91569     if( pWInfo==0 ) goto select_end;
91570     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
91571
91572     /* If sorting index that was created by a prior OP_OpenEphemeral 
91573     ** instruction ended up not being needed, then change the OP_OpenEphemeral
91574     ** into an OP_Noop.
91575     */
91576     if( addrSortIndex>=0 && pOrderBy==0 ){
91577       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
91578       p->addrOpenEphm[2] = -1;
91579     }
91580
91581     /* Use the standard inner loop
91582     */
91583     assert(!isDistinct);
91584     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
91585                     pWInfo->iContinue, pWInfo->iBreak);
91586
91587     /* End the database scan loop.
91588     */
91589     sqlite3WhereEnd(pWInfo);
91590   }else{
91591     /* This is the processing for aggregate queries */
91592     NameContext sNC;    /* Name context for processing aggregate information */
91593     int iAMem;          /* First Mem address for storing current GROUP BY */
91594     int iBMem;          /* First Mem address for previous GROUP BY */
91595     int iUseFlag;       /* Mem address holding flag indicating that at least
91596                         ** one row of the input to the aggregator has been
91597                         ** processed */
91598     int iAbortFlag;     /* Mem address which causes query abort if positive */
91599     int groupBySort;    /* Rows come from source in GROUP BY order */
91600     int addrEnd;        /* End of processing for this SELECT */
91601
91602     /* Remove any and all aliases between the result set and the
91603     ** GROUP BY clause.
91604     */
91605     if( pGroupBy ){
91606       int k;                        /* Loop counter */
91607       struct ExprList_item *pItem;  /* For looping over expression in a list */
91608
91609       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
91610         pItem->iAlias = 0;
91611       }
91612       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
91613         pItem->iAlias = 0;
91614       }
91615       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
91616     }else{
91617       p->nSelectRow = (double)1;
91618     }
91619
91620  
91621     /* Create a label to jump to when we want to abort the query */
91622     addrEnd = sqlite3VdbeMakeLabel(v);
91623
91624     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
91625     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
91626     ** SELECT statement.
91627     */
91628     memset(&sNC, 0, sizeof(sNC));
91629     sNC.pParse = pParse;
91630     sNC.pSrcList = pTabList;
91631     sNC.pAggInfo = &sAggInfo;
91632     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
91633     sAggInfo.pGroupBy = pGroupBy;
91634     sqlite3ExprAnalyzeAggList(&sNC, pEList);
91635     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
91636     if( pHaving ){
91637       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
91638     }
91639     sAggInfo.nAccumulator = sAggInfo.nColumn;
91640     for(i=0; i<sAggInfo.nFunc; i++){
91641       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
91642       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
91643     }
91644     if( db->mallocFailed ) goto select_end;
91645
91646     /* Processing for aggregates with GROUP BY is very different and
91647     ** much more complex than aggregates without a GROUP BY.
91648     */
91649     if( pGroupBy ){
91650       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
91651       int j1;             /* A-vs-B comparision jump */
91652       int addrOutputRow;  /* Start of subroutine that outputs a result row */
91653       int regOutputRow;   /* Return address register for output subroutine */
91654       int addrSetAbort;   /* Set the abort flag and return */
91655       int addrTopOfLoop;  /* Top of the input loop */
91656       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
91657       int addrReset;      /* Subroutine for resetting the accumulator */
91658       int regReset;       /* Return address register for reset subroutine */
91659
91660       /* If there is a GROUP BY clause we might need a sorting index to
91661       ** implement it.  Allocate that sorting index now.  If it turns out
91662       ** that we do not need it after all, the OpenEphemeral instruction
91663       ** will be converted into a Noop.  
91664       */
91665       sAggInfo.sortingIdx = pParse->nTab++;
91666       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
91667       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
91668           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
91669           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
91670
91671       /* Initialize memory locations used by GROUP BY aggregate processing
91672       */
91673       iUseFlag = ++pParse->nMem;
91674       iAbortFlag = ++pParse->nMem;
91675       regOutputRow = ++pParse->nMem;
91676       addrOutputRow = sqlite3VdbeMakeLabel(v);
91677       regReset = ++pParse->nMem;
91678       addrReset = sqlite3VdbeMakeLabel(v);
91679       iAMem = pParse->nMem + 1;
91680       pParse->nMem += pGroupBy->nExpr;
91681       iBMem = pParse->nMem + 1;
91682       pParse->nMem += pGroupBy->nExpr;
91683       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
91684       VdbeComment((v, "clear abort flag"));
91685       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
91686       VdbeComment((v, "indicate accumulator empty"));
91687
91688       /* Begin a loop that will extract all source rows in GROUP BY order.
91689       ** This might involve two separate loops with an OP_Sort in between, or
91690       ** it might be a single loop that uses an index to extract information
91691       ** in the right order to begin with.
91692       */
91693       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
91694       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
91695       if( pWInfo==0 ) goto select_end;
91696       if( pGroupBy==0 ){
91697         /* The optimizer is able to deliver rows in group by order so
91698         ** we do not have to sort.  The OP_OpenEphemeral table will be
91699         ** cancelled later because we still need to use the pKeyInfo
91700         */
91701         pGroupBy = p->pGroupBy;
91702         groupBySort = 0;
91703       }else{
91704         /* Rows are coming out in undetermined order.  We have to push
91705         ** each row into a sorting index, terminate the first loop,
91706         ** then loop over the sorting index in order to get the output
91707         ** in sorted order
91708         */
91709         int regBase;
91710         int regRecord;
91711         int nCol;
91712         int nGroupBy;
91713
91714         explainTempTable(pParse, 
91715             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
91716
91717         groupBySort = 1;
91718         nGroupBy = pGroupBy->nExpr;
91719         nCol = nGroupBy + 1;
91720         j = nGroupBy+1;
91721         for(i=0; i<sAggInfo.nColumn; i++){
91722           if( sAggInfo.aCol[i].iSorterColumn>=j ){
91723             nCol++;
91724             j++;
91725           }
91726         }
91727         regBase = sqlite3GetTempRange(pParse, nCol);
91728         sqlite3ExprCacheClear(pParse);
91729         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
91730         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
91731         j = nGroupBy+1;
91732         for(i=0; i<sAggInfo.nColumn; i++){
91733           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
91734           if( pCol->iSorterColumn>=j ){
91735             int r1 = j + regBase;
91736             int r2;
91737
91738             r2 = sqlite3ExprCodeGetColumn(pParse, 
91739                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
91740             if( r1!=r2 ){
91741               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
91742             }
91743             j++;
91744           }
91745         }
91746         regRecord = sqlite3GetTempReg(pParse);
91747         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
91748         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
91749         sqlite3ReleaseTempReg(pParse, regRecord);
91750         sqlite3ReleaseTempRange(pParse, regBase, nCol);
91751         sqlite3WhereEnd(pWInfo);
91752         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
91753         VdbeComment((v, "GROUP BY sort"));
91754         sAggInfo.useSortingIdx = 1;
91755         sqlite3ExprCacheClear(pParse);
91756       }
91757
91758       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
91759       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
91760       ** Then compare the current GROUP BY terms against the GROUP BY terms
91761       ** from the previous row currently stored in a0, a1, a2...
91762       */
91763       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
91764       sqlite3ExprCacheClear(pParse);
91765       for(j=0; j<pGroupBy->nExpr; j++){
91766         if( groupBySort ){
91767           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
91768         }else{
91769           sAggInfo.directMode = 1;
91770           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
91771         }
91772       }
91773       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
91774                           (char*)pKeyInfo, P4_KEYINFO);
91775       j1 = sqlite3VdbeCurrentAddr(v);
91776       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
91777
91778       /* Generate code that runs whenever the GROUP BY changes.
91779       ** Changes in the GROUP BY are detected by the previous code
91780       ** block.  If there were no changes, this block is skipped.
91781       **
91782       ** This code copies current group by terms in b0,b1,b2,...
91783       ** over to a0,a1,a2.  It then calls the output subroutine
91784       ** and resets the aggregate accumulator registers in preparation
91785       ** for the next GROUP BY batch.
91786       */
91787       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
91788       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
91789       VdbeComment((v, "output one row"));
91790       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
91791       VdbeComment((v, "check abort flag"));
91792       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
91793       VdbeComment((v, "reset accumulator"));
91794
91795       /* Update the aggregate accumulators based on the content of
91796       ** the current row
91797       */
91798       sqlite3VdbeJumpHere(v, j1);
91799       updateAccumulator(pParse, &sAggInfo);
91800       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
91801       VdbeComment((v, "indicate data in accumulator"));
91802
91803       /* End of the loop
91804       */
91805       if( groupBySort ){
91806         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
91807       }else{
91808         sqlite3WhereEnd(pWInfo);
91809         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
91810       }
91811
91812       /* Output the final row of result
91813       */
91814       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
91815       VdbeComment((v, "output final row"));
91816
91817       /* Jump over the subroutines
91818       */
91819       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
91820
91821       /* Generate a subroutine that outputs a single row of the result
91822       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
91823       ** is less than or equal to zero, the subroutine is a no-op.  If
91824       ** the processing calls for the query to abort, this subroutine
91825       ** increments the iAbortFlag memory location before returning in
91826       ** order to signal the caller to abort.
91827       */
91828       addrSetAbort = sqlite3VdbeCurrentAddr(v);
91829       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
91830       VdbeComment((v, "set abort flag"));
91831       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
91832       sqlite3VdbeResolveLabel(v, addrOutputRow);
91833       addrOutputRow = sqlite3VdbeCurrentAddr(v);
91834       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
91835       VdbeComment((v, "Groupby result generator entry point"));
91836       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
91837       finalizeAggFunctions(pParse, &sAggInfo);
91838       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
91839       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
91840                       distinct, pDest,
91841                       addrOutputRow+1, addrSetAbort);
91842       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
91843       VdbeComment((v, "end groupby result generator"));
91844
91845       /* Generate a subroutine that will reset the group-by accumulator
91846       */
91847       sqlite3VdbeResolveLabel(v, addrReset);
91848       resetAccumulator(pParse, &sAggInfo);
91849       sqlite3VdbeAddOp1(v, OP_Return, regReset);
91850      
91851     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
91852     else {
91853       ExprList *pDel = 0;
91854 #ifndef SQLITE_OMIT_BTREECOUNT
91855       Table *pTab;
91856       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
91857         /* If isSimpleCount() returns a pointer to a Table structure, then
91858         ** the SQL statement is of the form:
91859         **
91860         **   SELECT count(*) FROM <tbl>
91861         **
91862         ** where the Table structure returned represents table <tbl>.
91863         **
91864         ** This statement is so common that it is optimized specially. The
91865         ** OP_Count instruction is executed either on the intkey table that
91866         ** contains the data for table <tbl> or on one of its indexes. It
91867         ** is better to execute the op on an index, as indexes are almost
91868         ** always spread across less pages than their corresponding tables.
91869         */
91870         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91871         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
91872         Index *pIdx;                         /* Iterator variable */
91873         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
91874         Index *pBest = 0;                    /* Best index found so far */
91875         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
91876
91877         sqlite3CodeVerifySchema(pParse, iDb);
91878         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91879
91880         /* Search for the index that has the least amount of columns. If
91881         ** there is such an index, and it has less columns than the table
91882         ** does, then we can assume that it consumes less space on disk and
91883         ** will therefore be cheaper to scan to determine the query result.
91884         ** In this case set iRoot to the root page number of the index b-tree
91885         ** and pKeyInfo to the KeyInfo structure required to navigate the
91886         ** index.
91887         **
91888         ** In practice the KeyInfo structure will not be used. It is only 
91889         ** passed to keep OP_OpenRead happy.
91890         */
91891         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91892           if( !pBest || pIdx->nColumn<pBest->nColumn ){
91893             pBest = pIdx;
91894           }
91895         }
91896         if( pBest && pBest->nColumn<pTab->nCol ){
91897           iRoot = pBest->tnum;
91898           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
91899         }
91900
91901         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
91902         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
91903         if( pKeyInfo ){
91904           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
91905         }
91906         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
91907         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
91908       }else
91909 #endif /* SQLITE_OMIT_BTREECOUNT */
91910       {
91911         /* Check if the query is of one of the following forms:
91912         **
91913         **   SELECT min(x) FROM ...
91914         **   SELECT max(x) FROM ...
91915         **
91916         ** If it is, then ask the code in where.c to attempt to sort results
91917         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
91918         ** If where.c is able to produce results sorted in this order, then
91919         ** add vdbe code to break out of the processing loop after the 
91920         ** first iteration (since the first iteration of the loop is 
91921         ** guaranteed to operate on the row with the minimum or maximum 
91922         ** value of x, the only row required).
91923         **
91924         ** A special flag must be passed to sqlite3WhereBegin() to slightly
91925         ** modify behaviour as follows:
91926         **
91927         **   + If the query is a "SELECT min(x)", then the loop coded by
91928         **     where.c should not iterate over any values with a NULL value
91929         **     for x.
91930         **
91931         **   + The optimizer code in where.c (the thing that decides which
91932         **     index or indices to use) should place a different priority on 
91933         **     satisfying the 'ORDER BY' clause than it does in other cases.
91934         **     Refer to code and comments in where.c for details.
91935         */
91936         ExprList *pMinMax = 0;
91937         u8 flag = minMaxQuery(p);
91938         if( flag ){
91939           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
91940           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
91941           pDel = pMinMax;
91942           if( pMinMax && !db->mallocFailed ){
91943             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
91944             pMinMax->a[0].pExpr->op = TK_COLUMN;
91945           }
91946         }
91947   
91948         /* This case runs if the aggregate has no GROUP BY clause.  The
91949         ** processing is much simpler since there is only a single row
91950         ** of output.
91951         */
91952         resetAccumulator(pParse, &sAggInfo);
91953         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
91954         if( pWInfo==0 ){
91955           sqlite3ExprListDelete(db, pDel);
91956           goto select_end;
91957         }
91958         updateAccumulator(pParse, &sAggInfo);
91959         if( !pMinMax && flag ){
91960           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
91961           VdbeComment((v, "%s() by index",
91962                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
91963         }
91964         sqlite3WhereEnd(pWInfo);
91965         finalizeAggFunctions(pParse, &sAggInfo);
91966       }
91967
91968       pOrderBy = 0;
91969       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
91970       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
91971                       pDest, addrEnd, addrEnd);
91972       sqlite3ExprListDelete(db, pDel);
91973     }
91974     sqlite3VdbeResolveLabel(v, addrEnd);
91975     
91976   } /* endif aggregate query */
91977
91978   if( distinct>=0 ){
91979     explainTempTable(pParse, "DISTINCT");
91980   }
91981
91982   /* If there is an ORDER BY clause, then we need to sort the results
91983   ** and send them to the callback one by one.
91984   */
91985   if( pOrderBy ){
91986     explainTempTable(pParse, "ORDER BY");
91987     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
91988   }
91989
91990   /* Jump here to skip this query
91991   */
91992   sqlite3VdbeResolveLabel(v, iEnd);
91993
91994   /* The SELECT was successfully coded.   Set the return code to 0
91995   ** to indicate no errors.
91996   */
91997   rc = 0;
91998
91999   /* Control jumps to here if an error is encountered above, or upon
92000   ** successful coding of the SELECT.
92001   */
92002 select_end:
92003   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
92004
92005   /* Identify column names if results of the SELECT are to be output.
92006   */
92007   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
92008     generateColumnNames(pParse, pTabList, pEList);
92009   }
92010
92011   sqlite3DbFree(db, sAggInfo.aCol);
92012   sqlite3DbFree(db, sAggInfo.aFunc);
92013   return rc;
92014 }
92015
92016 #if defined(SQLITE_DEBUG)
92017 /*
92018 *******************************************************************************
92019 ** The following code is used for testing and debugging only.  The code
92020 ** that follows does not appear in normal builds.
92021 **
92022 ** These routines are used to print out the content of all or part of a 
92023 ** parse structures such as Select or Expr.  Such printouts are useful
92024 ** for helping to understand what is happening inside the code generator
92025 ** during the execution of complex SELECT statements.
92026 **
92027 ** These routine are not called anywhere from within the normal
92028 ** code base.  Then are intended to be called from within the debugger
92029 ** or from temporary "printf" statements inserted for debugging.
92030 */
92031 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
92032   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
92033     sqlite3DebugPrintf("(%s", p->u.zToken);
92034   }else{
92035     sqlite3DebugPrintf("(%d", p->op);
92036   }
92037   if( p->pLeft ){
92038     sqlite3DebugPrintf(" ");
92039     sqlite3PrintExpr(p->pLeft);
92040   }
92041   if( p->pRight ){
92042     sqlite3DebugPrintf(" ");
92043     sqlite3PrintExpr(p->pRight);
92044   }
92045   sqlite3DebugPrintf(")");
92046 }
92047 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
92048   int i;
92049   for(i=0; i<pList->nExpr; i++){
92050     sqlite3PrintExpr(pList->a[i].pExpr);
92051     if( i<pList->nExpr-1 ){
92052       sqlite3DebugPrintf(", ");
92053     }
92054   }
92055 }
92056 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
92057   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
92058   sqlite3PrintExprList(p->pEList);
92059   sqlite3DebugPrintf("\n");
92060   if( p->pSrc ){
92061     char *zPrefix;
92062     int i;
92063     zPrefix = "FROM";
92064     for(i=0; i<p->pSrc->nSrc; i++){
92065       struct SrcList_item *pItem = &p->pSrc->a[i];
92066       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
92067       zPrefix = "";
92068       if( pItem->pSelect ){
92069         sqlite3DebugPrintf("(\n");
92070         sqlite3PrintSelect(pItem->pSelect, indent+10);
92071         sqlite3DebugPrintf("%*s)", indent+8, "");
92072       }else if( pItem->zName ){
92073         sqlite3DebugPrintf("%s", pItem->zName);
92074       }
92075       if( pItem->pTab ){
92076         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
92077       }
92078       if( pItem->zAlias ){
92079         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
92080       }
92081       if( i<p->pSrc->nSrc-1 ){
92082         sqlite3DebugPrintf(",");
92083       }
92084       sqlite3DebugPrintf("\n");
92085     }
92086   }
92087   if( p->pWhere ){
92088     sqlite3DebugPrintf("%*s WHERE ", indent, "");
92089     sqlite3PrintExpr(p->pWhere);
92090     sqlite3DebugPrintf("\n");
92091   }
92092   if( p->pGroupBy ){
92093     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
92094     sqlite3PrintExprList(p->pGroupBy);
92095     sqlite3DebugPrintf("\n");
92096   }
92097   if( p->pHaving ){
92098     sqlite3DebugPrintf("%*s HAVING ", indent, "");
92099     sqlite3PrintExpr(p->pHaving);
92100     sqlite3DebugPrintf("\n");
92101   }
92102   if( p->pOrderBy ){
92103     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
92104     sqlite3PrintExprList(p->pOrderBy);
92105     sqlite3DebugPrintf("\n");
92106   }
92107 }
92108 /* End of the structure debug printing code
92109 *****************************************************************************/
92110 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
92111
92112 /************** End of select.c **********************************************/
92113 /************** Begin file table.c *******************************************/
92114 /*
92115 ** 2001 September 15
92116 **
92117 ** The author disclaims copyright to this source code.  In place of
92118 ** a legal notice, here is a blessing:
92119 **
92120 **    May you do good and not evil.
92121 **    May you find forgiveness for yourself and forgive others.
92122 **    May you share freely, never taking more than you give.
92123 **
92124 *************************************************************************
92125 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
92126 ** interface routines.  These are just wrappers around the main
92127 ** interface routine of sqlite3_exec().
92128 **
92129 ** These routines are in a separate files so that they will not be linked
92130 ** if they are not used.
92131 */
92132
92133 #ifndef SQLITE_OMIT_GET_TABLE
92134
92135 /*
92136 ** This structure is used to pass data from sqlite3_get_table() through
92137 ** to the callback function is uses to build the result.
92138 */
92139 typedef struct TabResult {
92140   char **azResult;   /* Accumulated output */
92141   char *zErrMsg;     /* Error message text, if an error occurs */
92142   int nAlloc;        /* Slots allocated for azResult[] */
92143   int nRow;          /* Number of rows in the result */
92144   int nColumn;       /* Number of columns in the result */
92145   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
92146   int rc;            /* Return code from sqlite3_exec() */
92147 } TabResult;
92148
92149 /*
92150 ** This routine is called once for each row in the result table.  Its job
92151 ** is to fill in the TabResult structure appropriately, allocating new
92152 ** memory as necessary.
92153 */
92154 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
92155   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
92156   int need;                         /* Slots needed in p->azResult[] */
92157   int i;                            /* Loop counter */
92158   char *z;                          /* A single column of result */
92159
92160   /* Make sure there is enough space in p->azResult to hold everything
92161   ** we need to remember from this invocation of the callback.
92162   */
92163   if( p->nRow==0 && argv!=0 ){
92164     need = nCol*2;
92165   }else{
92166     need = nCol;
92167   }
92168   if( p->nData + need > p->nAlloc ){
92169     char **azNew;
92170     p->nAlloc = p->nAlloc*2 + need;
92171     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
92172     if( azNew==0 ) goto malloc_failed;
92173     p->azResult = azNew;
92174   }
92175
92176   /* If this is the first row, then generate an extra row containing
92177   ** the names of all columns.
92178   */
92179   if( p->nRow==0 ){
92180     p->nColumn = nCol;
92181     for(i=0; i<nCol; i++){
92182       z = sqlite3_mprintf("%s", colv[i]);
92183       if( z==0 ) goto malloc_failed;
92184       p->azResult[p->nData++] = z;
92185     }
92186   }else if( p->nColumn!=nCol ){
92187     sqlite3_free(p->zErrMsg);
92188     p->zErrMsg = sqlite3_mprintf(
92189        "sqlite3_get_table() called with two or more incompatible queries"
92190     );
92191     p->rc = SQLITE_ERROR;
92192     return 1;
92193   }
92194
92195   /* Copy over the row data
92196   */
92197   if( argv!=0 ){
92198     for(i=0; i<nCol; i++){
92199       if( argv[i]==0 ){
92200         z = 0;
92201       }else{
92202         int n = sqlite3Strlen30(argv[i])+1;
92203         z = sqlite3_malloc( n );
92204         if( z==0 ) goto malloc_failed;
92205         memcpy(z, argv[i], n);
92206       }
92207       p->azResult[p->nData++] = z;
92208     }
92209     p->nRow++;
92210   }
92211   return 0;
92212
92213 malloc_failed:
92214   p->rc = SQLITE_NOMEM;
92215   return 1;
92216 }
92217
92218 /*
92219 ** Query the database.  But instead of invoking a callback for each row,
92220 ** malloc() for space to hold the result and return the entire results
92221 ** at the conclusion of the call.
92222 **
92223 ** The result that is written to ***pazResult is held in memory obtained
92224 ** from malloc().  But the caller cannot free this memory directly.  
92225 ** Instead, the entire table should be passed to sqlite3_free_table() when
92226 ** the calling procedure is finished using it.
92227 */
92228 SQLITE_API int sqlite3_get_table(
92229   sqlite3 *db,                /* The database on which the SQL executes */
92230   const char *zSql,           /* The SQL to be executed */
92231   char ***pazResult,          /* Write the result table here */
92232   int *pnRow,                 /* Write the number of rows in the result here */
92233   int *pnColumn,              /* Write the number of columns of result here */
92234   char **pzErrMsg             /* Write error messages here */
92235 ){
92236   int rc;
92237   TabResult res;
92238
92239   *pazResult = 0;
92240   if( pnColumn ) *pnColumn = 0;
92241   if( pnRow ) *pnRow = 0;
92242   if( pzErrMsg ) *pzErrMsg = 0;
92243   res.zErrMsg = 0;
92244   res.nRow = 0;
92245   res.nColumn = 0;
92246   res.nData = 1;
92247   res.nAlloc = 20;
92248   res.rc = SQLITE_OK;
92249   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
92250   if( res.azResult==0 ){
92251      db->errCode = SQLITE_NOMEM;
92252      return SQLITE_NOMEM;
92253   }
92254   res.azResult[0] = 0;
92255   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
92256   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
92257   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
92258   if( (rc&0xff)==SQLITE_ABORT ){
92259     sqlite3_free_table(&res.azResult[1]);
92260     if( res.zErrMsg ){
92261       if( pzErrMsg ){
92262         sqlite3_free(*pzErrMsg);
92263         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
92264       }
92265       sqlite3_free(res.zErrMsg);
92266     }
92267     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
92268     return res.rc;
92269   }
92270   sqlite3_free(res.zErrMsg);
92271   if( rc!=SQLITE_OK ){
92272     sqlite3_free_table(&res.azResult[1]);
92273     return rc;
92274   }
92275   if( res.nAlloc>res.nData ){
92276     char **azNew;
92277     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
92278     if( azNew==0 ){
92279       sqlite3_free_table(&res.azResult[1]);
92280       db->errCode = SQLITE_NOMEM;
92281       return SQLITE_NOMEM;
92282     }
92283     res.azResult = azNew;
92284   }
92285   *pazResult = &res.azResult[1];
92286   if( pnColumn ) *pnColumn = res.nColumn;
92287   if( pnRow ) *pnRow = res.nRow;
92288   return rc;
92289 }
92290
92291 /*
92292 ** This routine frees the space the sqlite3_get_table() malloced.
92293 */
92294 SQLITE_API void sqlite3_free_table(
92295   char **azResult            /* Result returned from from sqlite3_get_table() */
92296 ){
92297   if( azResult ){
92298     int i, n;
92299     azResult--;
92300     assert( azResult!=0 );
92301     n = SQLITE_PTR_TO_INT(azResult[0]);
92302     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
92303     sqlite3_free(azResult);
92304   }
92305 }
92306
92307 #endif /* SQLITE_OMIT_GET_TABLE */
92308
92309 /************** End of table.c ***********************************************/
92310 /************** Begin file trigger.c *****************************************/
92311 /*
92312 **
92313 ** The author disclaims copyright to this source code.  In place of
92314 ** a legal notice, here is a blessing:
92315 **
92316 **    May you do good and not evil.
92317 **    May you find forgiveness for yourself and forgive others.
92318 **    May you share freely, never taking more than you give.
92319 **
92320 *************************************************************************
92321 ** This file contains the implementation for TRIGGERs
92322 */
92323
92324 #ifndef SQLITE_OMIT_TRIGGER
92325 /*
92326 ** Delete a linked list of TriggerStep structures.
92327 */
92328 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
92329   while( pTriggerStep ){
92330     TriggerStep * pTmp = pTriggerStep;
92331     pTriggerStep = pTriggerStep->pNext;
92332
92333     sqlite3ExprDelete(db, pTmp->pWhere);
92334     sqlite3ExprListDelete(db, pTmp->pExprList);
92335     sqlite3SelectDelete(db, pTmp->pSelect);
92336     sqlite3IdListDelete(db, pTmp->pIdList);
92337
92338     sqlite3DbFree(db, pTmp);
92339   }
92340 }
92341
92342 /*
92343 ** Given table pTab, return a list of all the triggers attached to 
92344 ** the table. The list is connected by Trigger.pNext pointers.
92345 **
92346 ** All of the triggers on pTab that are in the same database as pTab
92347 ** are already attached to pTab->pTrigger.  But there might be additional
92348 ** triggers on pTab in the TEMP schema.  This routine prepends all
92349 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
92350 ** and returns the combined list.
92351 **
92352 ** To state it another way:  This routine returns a list of all triggers
92353 ** that fire off of pTab.  The list will include any TEMP triggers on
92354 ** pTab as well as the triggers lised in pTab->pTrigger.
92355 */
92356 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
92357   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
92358   Trigger *pList = 0;                  /* List of triggers to return */
92359
92360   if( pParse->disableTriggers ){
92361     return 0;
92362   }
92363
92364   if( pTmpSchema!=pTab->pSchema ){
92365     HashElem *p;
92366     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
92367       Trigger *pTrig = (Trigger *)sqliteHashData(p);
92368       if( pTrig->pTabSchema==pTab->pSchema
92369        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
92370       ){
92371         pTrig->pNext = (pList ? pList : pTab->pTrigger);
92372         pList = pTrig;
92373       }
92374     }
92375   }
92376
92377   return (pList ? pList : pTab->pTrigger);
92378 }
92379
92380 /*
92381 ** This is called by the parser when it sees a CREATE TRIGGER statement
92382 ** up to the point of the BEGIN before the trigger actions.  A Trigger
92383 ** structure is generated based on the information available and stored
92384 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
92385 ** sqlite3FinishTrigger() function is called to complete the trigger
92386 ** construction process.
92387 */
92388 SQLITE_PRIVATE void sqlite3BeginTrigger(
92389   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
92390   Token *pName1,      /* The name of the trigger */
92391   Token *pName2,      /* The name of the trigger */
92392   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
92393   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
92394   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
92395   SrcList *pTableName,/* The name of the table/view the trigger applies to */
92396   Expr *pWhen,        /* WHEN clause */
92397   int isTemp,         /* True if the TEMPORARY keyword is present */
92398   int noErr           /* Suppress errors if the trigger already exists */
92399 ){
92400   Trigger *pTrigger = 0;  /* The new trigger */
92401   Table *pTab;            /* Table that the trigger fires off of */
92402   char *zName = 0;        /* Name of the trigger */
92403   sqlite3 *db = pParse->db;  /* The database connection */
92404   int iDb;                /* The database to store the trigger in */
92405   Token *pName;           /* The unqualified db name */
92406   DbFixer sFix;           /* State vector for the DB fixer */
92407   int iTabDb;             /* Index of the database holding pTab */
92408
92409   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
92410   assert( pName2!=0 );
92411   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
92412   assert( op>0 && op<0xff );
92413   if( isTemp ){
92414     /* If TEMP was specified, then the trigger name may not be qualified. */
92415     if( pName2->n>0 ){
92416       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
92417       goto trigger_cleanup;
92418     }
92419     iDb = 1;
92420     pName = pName1;
92421   }else{
92422     /* Figure out the db that the the trigger will be created in */
92423     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
92424     if( iDb<0 ){
92425       goto trigger_cleanup;
92426     }
92427   }
92428
92429   /* If the trigger name was unqualified, and the table is a temp table,
92430   ** then set iDb to 1 to create the trigger in the temporary database.
92431   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
92432   ** exist, the error is caught by the block below.
92433   */
92434   if( !pTableName || db->mallocFailed ){
92435     goto trigger_cleanup;
92436   }
92437   pTab = sqlite3SrcListLookup(pParse, pTableName);
92438   if( db->init.busy==0 && pName2->n==0 && pTab
92439         && pTab->pSchema==db->aDb[1].pSchema ){
92440     iDb = 1;
92441   }
92442
92443   /* Ensure the table name matches database name and that the table exists */
92444   if( db->mallocFailed ) goto trigger_cleanup;
92445   assert( pTableName->nSrc==1 );
92446   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
92447       sqlite3FixSrcList(&sFix, pTableName) ){
92448     goto trigger_cleanup;
92449   }
92450   pTab = sqlite3SrcListLookup(pParse, pTableName);
92451   if( !pTab ){
92452     /* The table does not exist. */
92453     if( db->init.iDb==1 ){
92454       /* Ticket #3810.
92455       ** Normally, whenever a table is dropped, all associated triggers are
92456       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
92457       ** and the table is dropped by a different database connection, the
92458       ** trigger is not visible to the database connection that does the
92459       ** drop so the trigger cannot be dropped.  This results in an
92460       ** "orphaned trigger" - a trigger whose associated table is missing.
92461       */
92462       db->init.orphanTrigger = 1;
92463     }
92464     goto trigger_cleanup;
92465   }
92466   if( IsVirtual(pTab) ){
92467     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
92468     goto trigger_cleanup;
92469   }
92470
92471   /* Check that the trigger name is not reserved and that no trigger of the
92472   ** specified name exists */
92473   zName = sqlite3NameFromToken(db, pName);
92474   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
92475     goto trigger_cleanup;
92476   }
92477   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
92478                       zName, sqlite3Strlen30(zName)) ){
92479     if( !noErr ){
92480       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
92481     }
92482     goto trigger_cleanup;
92483   }
92484
92485   /* Do not create a trigger on a system table */
92486   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
92487     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
92488     pParse->nErr++;
92489     goto trigger_cleanup;
92490   }
92491
92492   /* INSTEAD of triggers are only for views and views only support INSTEAD
92493   ** of triggers.
92494   */
92495   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
92496     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
92497         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
92498     goto trigger_cleanup;
92499   }
92500   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
92501     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
92502         " trigger on table: %S", pTableName, 0);
92503     goto trigger_cleanup;
92504   }
92505   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
92506
92507 #ifndef SQLITE_OMIT_AUTHORIZATION
92508   {
92509     int code = SQLITE_CREATE_TRIGGER;
92510     const char *zDb = db->aDb[iTabDb].zName;
92511     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
92512     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
92513     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
92514       goto trigger_cleanup;
92515     }
92516     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
92517       goto trigger_cleanup;
92518     }
92519   }
92520 #endif
92521
92522   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
92523   ** cannot appear on views.  So we might as well translate every
92524   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
92525   ** elsewhere.
92526   */
92527   if (tr_tm == TK_INSTEAD){
92528     tr_tm = TK_BEFORE;
92529   }
92530
92531   /* Build the Trigger object */
92532   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
92533   if( pTrigger==0 ) goto trigger_cleanup;
92534   pTrigger->zName = zName;
92535   zName = 0;
92536   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
92537   pTrigger->pSchema = db->aDb[iDb].pSchema;
92538   pTrigger->pTabSchema = pTab->pSchema;
92539   pTrigger->op = (u8)op;
92540   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
92541   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
92542   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
92543   assert( pParse->pNewTrigger==0 );
92544   pParse->pNewTrigger = pTrigger;
92545
92546 trigger_cleanup:
92547   sqlite3DbFree(db, zName);
92548   sqlite3SrcListDelete(db, pTableName);
92549   sqlite3IdListDelete(db, pColumns);
92550   sqlite3ExprDelete(db, pWhen);
92551   if( !pParse->pNewTrigger ){
92552     sqlite3DeleteTrigger(db, pTrigger);
92553   }else{
92554     assert( pParse->pNewTrigger==pTrigger );
92555   }
92556 }
92557
92558 /*
92559 ** This routine is called after all of the trigger actions have been parsed
92560 ** in order to complete the process of building the trigger.
92561 */
92562 SQLITE_PRIVATE void sqlite3FinishTrigger(
92563   Parse *pParse,          /* Parser context */
92564   TriggerStep *pStepList, /* The triggered program */
92565   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
92566 ){
92567   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
92568   char *zName;                            /* Name of trigger */
92569   sqlite3 *db = pParse->db;               /* The database */
92570   DbFixer sFix;                           /* Fixer object */
92571   int iDb;                                /* Database containing the trigger */
92572   Token nameToken;                        /* Trigger name for error reporting */
92573
92574   pTrig = pParse->pNewTrigger;
92575   pParse->pNewTrigger = 0;
92576   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
92577   zName = pTrig->zName;
92578   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
92579   pTrig->step_list = pStepList;
92580   while( pStepList ){
92581     pStepList->pTrig = pTrig;
92582     pStepList = pStepList->pNext;
92583   }
92584   nameToken.z = pTrig->zName;
92585   nameToken.n = sqlite3Strlen30(nameToken.z);
92586   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
92587           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
92588     goto triggerfinish_cleanup;
92589   }
92590
92591   /* if we are not initializing,
92592   ** build the sqlite_master entry
92593   */
92594   if( !db->init.busy ){
92595     Vdbe *v;
92596     char *z;
92597
92598     /* Make an entry in the sqlite_master table */
92599     v = sqlite3GetVdbe(pParse);
92600     if( v==0 ) goto triggerfinish_cleanup;
92601     sqlite3BeginWriteOperation(pParse, 0, iDb);
92602     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
92603     sqlite3NestedParse(pParse,
92604        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
92605        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
92606        pTrig->table, z);
92607     sqlite3DbFree(db, z);
92608     sqlite3ChangeCookie(pParse, iDb);
92609     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
92610         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
92611     );
92612   }
92613
92614   if( db->init.busy ){
92615     Trigger *pLink = pTrig;
92616     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
92617     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
92618     if( pTrig ){
92619       db->mallocFailed = 1;
92620     }else if( pLink->pSchema==pLink->pTabSchema ){
92621       Table *pTab;
92622       int n = sqlite3Strlen30(pLink->table);
92623       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
92624       assert( pTab!=0 );
92625       pLink->pNext = pTab->pTrigger;
92626       pTab->pTrigger = pLink;
92627     }
92628   }
92629
92630 triggerfinish_cleanup:
92631   sqlite3DeleteTrigger(db, pTrig);
92632   assert( !pParse->pNewTrigger );
92633   sqlite3DeleteTriggerStep(db, pStepList);
92634 }
92635
92636 /*
92637 ** Turn a SELECT statement (that the pSelect parameter points to) into
92638 ** a trigger step.  Return a pointer to a TriggerStep structure.
92639 **
92640 ** The parser calls this routine when it finds a SELECT statement in
92641 ** body of a TRIGGER.  
92642 */
92643 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
92644   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
92645   if( pTriggerStep==0 ) {
92646     sqlite3SelectDelete(db, pSelect);
92647     return 0;
92648   }
92649   pTriggerStep->op = TK_SELECT;
92650   pTriggerStep->pSelect = pSelect;
92651   pTriggerStep->orconf = OE_Default;
92652   return pTriggerStep;
92653 }
92654
92655 /*
92656 ** Allocate space to hold a new trigger step.  The allocated space
92657 ** holds both the TriggerStep object and the TriggerStep.target.z string.
92658 **
92659 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
92660 */
92661 static TriggerStep *triggerStepAllocate(
92662   sqlite3 *db,                /* Database connection */
92663   u8 op,                      /* Trigger opcode */
92664   Token *pName                /* The target name */
92665 ){
92666   TriggerStep *pTriggerStep;
92667
92668   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
92669   if( pTriggerStep ){
92670     char *z = (char*)&pTriggerStep[1];
92671     memcpy(z, pName->z, pName->n);
92672     pTriggerStep->target.z = z;
92673     pTriggerStep->target.n = pName->n;
92674     pTriggerStep->op = op;
92675   }
92676   return pTriggerStep;
92677 }
92678
92679 /*
92680 ** Build a trigger step out of an INSERT statement.  Return a pointer
92681 ** to the new trigger step.
92682 **
92683 ** The parser calls this routine when it sees an INSERT inside the
92684 ** body of a trigger.
92685 */
92686 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
92687   sqlite3 *db,        /* The database connection */
92688   Token *pTableName,  /* Name of the table into which we insert */
92689   IdList *pColumn,    /* List of columns in pTableName to insert into */
92690   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
92691   Select *pSelect,    /* A SELECT statement that supplies values */
92692   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
92693 ){
92694   TriggerStep *pTriggerStep;
92695
92696   assert(pEList == 0 || pSelect == 0);
92697   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
92698
92699   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
92700   if( pTriggerStep ){
92701     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
92702     pTriggerStep->pIdList = pColumn;
92703     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
92704     pTriggerStep->orconf = orconf;
92705   }else{
92706     sqlite3IdListDelete(db, pColumn);
92707   }
92708   sqlite3ExprListDelete(db, pEList);
92709   sqlite3SelectDelete(db, pSelect);
92710
92711   return pTriggerStep;
92712 }
92713
92714 /*
92715 ** Construct a trigger step that implements an UPDATE statement and return
92716 ** a pointer to that trigger step.  The parser calls this routine when it
92717 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
92718 */
92719 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
92720   sqlite3 *db,         /* The database connection */
92721   Token *pTableName,   /* Name of the table to be updated */
92722   ExprList *pEList,    /* The SET clause: list of column and new values */
92723   Expr *pWhere,        /* The WHERE clause */
92724   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
92725 ){
92726   TriggerStep *pTriggerStep;
92727
92728   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
92729   if( pTriggerStep ){
92730     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
92731     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
92732     pTriggerStep->orconf = orconf;
92733   }
92734   sqlite3ExprListDelete(db, pEList);
92735   sqlite3ExprDelete(db, pWhere);
92736   return pTriggerStep;
92737 }
92738
92739 /*
92740 ** Construct a trigger step that implements a DELETE statement and return
92741 ** a pointer to that trigger step.  The parser calls this routine when it
92742 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
92743 */
92744 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
92745   sqlite3 *db,            /* Database connection */
92746   Token *pTableName,      /* The table from which rows are deleted */
92747   Expr *pWhere            /* The WHERE clause */
92748 ){
92749   TriggerStep *pTriggerStep;
92750
92751   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
92752   if( pTriggerStep ){
92753     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
92754     pTriggerStep->orconf = OE_Default;
92755   }
92756   sqlite3ExprDelete(db, pWhere);
92757   return pTriggerStep;
92758 }
92759
92760 /* 
92761 ** Recursively delete a Trigger structure
92762 */
92763 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
92764   if( pTrigger==0 ) return;
92765   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
92766   sqlite3DbFree(db, pTrigger->zName);
92767   sqlite3DbFree(db, pTrigger->table);
92768   sqlite3ExprDelete(db, pTrigger->pWhen);
92769   sqlite3IdListDelete(db, pTrigger->pColumns);
92770   sqlite3DbFree(db, pTrigger);
92771 }
92772
92773 /*
92774 ** This function is called to drop a trigger from the database schema. 
92775 **
92776 ** This may be called directly from the parser and therefore identifies
92777 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
92778 ** same job as this routine except it takes a pointer to the trigger
92779 ** instead of the trigger name.
92780 **/
92781 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
92782   Trigger *pTrigger = 0;
92783   int i;
92784   const char *zDb;
92785   const char *zName;
92786   int nName;
92787   sqlite3 *db = pParse->db;
92788
92789   if( db->mallocFailed ) goto drop_trigger_cleanup;
92790   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
92791     goto drop_trigger_cleanup;
92792   }
92793
92794   assert( pName->nSrc==1 );
92795   zDb = pName->a[0].zDatabase;
92796   zName = pName->a[0].zName;
92797   nName = sqlite3Strlen30(zName);
92798   for(i=OMIT_TEMPDB; i<db->nDb; i++){
92799     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
92800     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
92801     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
92802     if( pTrigger ) break;
92803   }
92804   if( !pTrigger ){
92805     if( !noErr ){
92806       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
92807     }
92808     pParse->checkSchema = 1;
92809     goto drop_trigger_cleanup;
92810   }
92811   sqlite3DropTriggerPtr(pParse, pTrigger);
92812
92813 drop_trigger_cleanup:
92814   sqlite3SrcListDelete(db, pName);
92815 }
92816
92817 /*
92818 ** Return a pointer to the Table structure for the table that a trigger
92819 ** is set on.
92820 */
92821 static Table *tableOfTrigger(Trigger *pTrigger){
92822   int n = sqlite3Strlen30(pTrigger->table);
92823   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
92824 }
92825
92826
92827 /*
92828 ** Drop a trigger given a pointer to that trigger. 
92829 */
92830 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
92831   Table   *pTable;
92832   Vdbe *v;
92833   sqlite3 *db = pParse->db;
92834   int iDb;
92835
92836   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
92837   assert( iDb>=0 && iDb<db->nDb );
92838   pTable = tableOfTrigger(pTrigger);
92839   assert( pTable );
92840   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
92841 #ifndef SQLITE_OMIT_AUTHORIZATION
92842   {
92843     int code = SQLITE_DROP_TRIGGER;
92844     const char *zDb = db->aDb[iDb].zName;
92845     const char *zTab = SCHEMA_TABLE(iDb);
92846     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
92847     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
92848       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
92849       return;
92850     }
92851   }
92852 #endif
92853
92854   /* Generate code to destroy the database record of the trigger.
92855   */
92856   assert( pTable!=0 );
92857   if( (v = sqlite3GetVdbe(pParse))!=0 ){
92858     int base;
92859     static const VdbeOpList dropTrigger[] = {
92860       { OP_Rewind,     0, ADDR(9),  0},
92861       { OP_String8,    0, 1,        0}, /* 1 */
92862       { OP_Column,     0, 1,        2},
92863       { OP_Ne,         2, ADDR(8),  1},
92864       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
92865       { OP_Column,     0, 0,        2},
92866       { OP_Ne,         2, ADDR(8),  1},
92867       { OP_Delete,     0, 0,        0},
92868       { OP_Next,       0, ADDR(1),  0}, /* 8 */
92869     };
92870
92871     sqlite3BeginWriteOperation(pParse, 0, iDb);
92872     sqlite3OpenMasterTable(pParse, iDb);
92873     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
92874     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
92875     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
92876     sqlite3ChangeCookie(pParse, iDb);
92877     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
92878     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
92879     if( pParse->nMem<3 ){
92880       pParse->nMem = 3;
92881     }
92882   }
92883 }
92884
92885 /*
92886 ** Remove a trigger from the hash tables of the sqlite* pointer.
92887 */
92888 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
92889   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
92890   Trigger *pTrigger;
92891   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
92892   if( ALWAYS(pTrigger) ){
92893     if( pTrigger->pSchema==pTrigger->pTabSchema ){
92894       Table *pTab = tableOfTrigger(pTrigger);
92895       Trigger **pp;
92896       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
92897       *pp = (*pp)->pNext;
92898     }
92899     sqlite3DeleteTrigger(db, pTrigger);
92900     db->flags |= SQLITE_InternChanges;
92901   }
92902 }
92903
92904 /*
92905 ** pEList is the SET clause of an UPDATE statement.  Each entry
92906 ** in pEList is of the format <id>=<expr>.  If any of the entries
92907 ** in pEList have an <id> which matches an identifier in pIdList,
92908 ** then return TRUE.  If pIdList==NULL, then it is considered a
92909 ** wildcard that matches anything.  Likewise if pEList==NULL then
92910 ** it matches anything so always return true.  Return false only
92911 ** if there is no match.
92912 */
92913 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
92914   int e;
92915   if( pIdList==0 || NEVER(pEList==0) ) return 1;
92916   for(e=0; e<pEList->nExpr; e++){
92917     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
92918   }
92919   return 0; 
92920 }
92921
92922 /*
92923 ** Return a list of all triggers on table pTab if there exists at least
92924 ** one trigger that must be fired when an operation of type 'op' is 
92925 ** performed on the table, and, if that operation is an UPDATE, if at
92926 ** least one of the columns in pChanges is being modified.
92927 */
92928 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
92929   Parse *pParse,          /* Parse context */
92930   Table *pTab,            /* The table the contains the triggers */
92931   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
92932   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
92933   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
92934 ){
92935   int mask = 0;
92936   Trigger *pList = sqlite3TriggerList(pParse, pTab);
92937   Trigger *p;
92938   assert( pList==0 || IsVirtual(pTab)==0 );
92939   for(p=pList; p; p=p->pNext){
92940     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
92941       mask |= p->tr_tm;
92942     }
92943   }
92944   if( pMask ){
92945     *pMask = mask;
92946   }
92947   return (mask ? pList : 0);
92948 }
92949
92950 /*
92951 ** Convert the pStep->target token into a SrcList and return a pointer
92952 ** to that SrcList.
92953 **
92954 ** This routine adds a specific database name, if needed, to the target when
92955 ** forming the SrcList.  This prevents a trigger in one database from
92956 ** referring to a target in another database.  An exception is when the
92957 ** trigger is in TEMP in which case it can refer to any other database it
92958 ** wants.
92959 */
92960 static SrcList *targetSrcList(
92961   Parse *pParse,       /* The parsing context */
92962   TriggerStep *pStep   /* The trigger containing the target token */
92963 ){
92964   int iDb;             /* Index of the database to use */
92965   SrcList *pSrc;       /* SrcList to be returned */
92966
92967   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
92968   if( pSrc ){
92969     assert( pSrc->nSrc>0 );
92970     assert( pSrc->a!=0 );
92971     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
92972     if( iDb==0 || iDb>=2 ){
92973       sqlite3 *db = pParse->db;
92974       assert( iDb<pParse->db->nDb );
92975       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
92976     }
92977   }
92978   return pSrc;
92979 }
92980
92981 /*
92982 ** Generate VDBE code for the statements inside the body of a single 
92983 ** trigger.
92984 */
92985 static int codeTriggerProgram(
92986   Parse *pParse,            /* The parser context */
92987   TriggerStep *pStepList,   /* List of statements inside the trigger body */
92988   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
92989 ){
92990   TriggerStep *pStep;
92991   Vdbe *v = pParse->pVdbe;
92992   sqlite3 *db = pParse->db;
92993
92994   assert( pParse->pTriggerTab && pParse->pToplevel );
92995   assert( pStepList );
92996   assert( v!=0 );
92997   for(pStep=pStepList; pStep; pStep=pStep->pNext){
92998     /* Figure out the ON CONFLICT policy that will be used for this step
92999     ** of the trigger program. If the statement that caused this trigger
93000     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
93001     ** the ON CONFLICT policy that was specified as part of the trigger
93002     ** step statement. Example:
93003     **
93004     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
93005     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
93006     **   END;
93007     **
93008     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
93009     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
93010     */
93011     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
93012
93013     switch( pStep->op ){
93014       case TK_UPDATE: {
93015         sqlite3Update(pParse, 
93016           targetSrcList(pParse, pStep),
93017           sqlite3ExprListDup(db, pStep->pExprList, 0), 
93018           sqlite3ExprDup(db, pStep->pWhere, 0), 
93019           pParse->eOrconf
93020         );
93021         break;
93022       }
93023       case TK_INSERT: {
93024         sqlite3Insert(pParse, 
93025           targetSrcList(pParse, pStep),
93026           sqlite3ExprListDup(db, pStep->pExprList, 0), 
93027           sqlite3SelectDup(db, pStep->pSelect, 0), 
93028           sqlite3IdListDup(db, pStep->pIdList), 
93029           pParse->eOrconf
93030         );
93031         break;
93032       }
93033       case TK_DELETE: {
93034         sqlite3DeleteFrom(pParse, 
93035           targetSrcList(pParse, pStep),
93036           sqlite3ExprDup(db, pStep->pWhere, 0)
93037         );
93038         break;
93039       }
93040       default: assert( pStep->op==TK_SELECT ); {
93041         SelectDest sDest;
93042         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
93043         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
93044         sqlite3Select(pParse, pSelect, &sDest);
93045         sqlite3SelectDelete(db, pSelect);
93046         break;
93047       }
93048     } 
93049     if( pStep->op!=TK_SELECT ){
93050       sqlite3VdbeAddOp0(v, OP_ResetCount);
93051     }
93052   }
93053
93054   return 0;
93055 }
93056
93057 #ifdef SQLITE_DEBUG
93058 /*
93059 ** This function is used to add VdbeComment() annotations to a VDBE
93060 ** program. It is not used in production code, only for debugging.
93061 */
93062 static const char *onErrorText(int onError){
93063   switch( onError ){
93064     case OE_Abort:    return "abort";
93065     case OE_Rollback: return "rollback";
93066     case OE_Fail:     return "fail";
93067     case OE_Replace:  return "replace";
93068     case OE_Ignore:   return "ignore";
93069     case OE_Default:  return "default";
93070   }
93071   return "n/a";
93072 }
93073 #endif
93074
93075 /*
93076 ** Parse context structure pFrom has just been used to create a sub-vdbe
93077 ** (trigger program). If an error has occurred, transfer error information
93078 ** from pFrom to pTo.
93079 */
93080 static void transferParseError(Parse *pTo, Parse *pFrom){
93081   assert( pFrom->zErrMsg==0 || pFrom->nErr );
93082   assert( pTo->zErrMsg==0 || pTo->nErr );
93083   if( pTo->nErr==0 ){
93084     pTo->zErrMsg = pFrom->zErrMsg;
93085     pTo->nErr = pFrom->nErr;
93086   }else{
93087     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
93088   }
93089 }
93090
93091 /*
93092 ** Create and populate a new TriggerPrg object with a sub-program 
93093 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
93094 */
93095 static TriggerPrg *codeRowTrigger(
93096   Parse *pParse,       /* Current parse context */
93097   Trigger *pTrigger,   /* Trigger to code */
93098   Table *pTab,         /* The table pTrigger is attached to */
93099   int orconf           /* ON CONFLICT policy to code trigger program with */
93100 ){
93101   Parse *pTop = sqlite3ParseToplevel(pParse);
93102   sqlite3 *db = pParse->db;   /* Database handle */
93103   TriggerPrg *pPrg;           /* Value to return */
93104   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
93105   Vdbe *v;                    /* Temporary VM */
93106   NameContext sNC;            /* Name context for sub-vdbe */
93107   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
93108   Parse *pSubParse;           /* Parse context for sub-vdbe */
93109   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
93110
93111   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
93112   assert( pTop->pVdbe );
93113
93114   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
93115   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
93116   ** list of the top-level Parse object sooner rather than later.  */
93117   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
93118   if( !pPrg ) return 0;
93119   pPrg->pNext = pTop->pTriggerPrg;
93120   pTop->pTriggerPrg = pPrg;
93121   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
93122   if( !pProgram ) return 0;
93123   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
93124   pPrg->pTrigger = pTrigger;
93125   pPrg->orconf = orconf;
93126   pPrg->aColmask[0] = 0xffffffff;
93127   pPrg->aColmask[1] = 0xffffffff;
93128
93129   /* Allocate and populate a new Parse context to use for coding the 
93130   ** trigger sub-program.  */
93131   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
93132   if( !pSubParse ) return 0;
93133   memset(&sNC, 0, sizeof(sNC));
93134   sNC.pParse = pSubParse;
93135   pSubParse->db = db;
93136   pSubParse->pTriggerTab = pTab;
93137   pSubParse->pToplevel = pTop;
93138   pSubParse->zAuthContext = pTrigger->zName;
93139   pSubParse->eTriggerOp = pTrigger->op;
93140   pSubParse->nQueryLoop = pParse->nQueryLoop;
93141
93142   v = sqlite3GetVdbe(pSubParse);
93143   if( v ){
93144     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
93145       pTrigger->zName, onErrorText(orconf),
93146       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
93147         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
93148         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
93149         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
93150       pTab->zName
93151     ));
93152 #ifndef SQLITE_OMIT_TRACE
93153     sqlite3VdbeChangeP4(v, -1, 
93154       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
93155     );
93156 #endif
93157
93158     /* If one was specified, code the WHEN clause. If it evaluates to false
93159     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
93160     ** OP_Halt inserted at the end of the program.  */
93161     if( pTrigger->pWhen ){
93162       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
93163       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
93164        && db->mallocFailed==0 
93165       ){
93166         iEndTrigger = sqlite3VdbeMakeLabel(v);
93167         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
93168       }
93169       sqlite3ExprDelete(db, pWhen);
93170     }
93171
93172     /* Code the trigger program into the sub-vdbe. */
93173     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
93174
93175     /* Insert an OP_Halt at the end of the sub-program. */
93176     if( iEndTrigger ){
93177       sqlite3VdbeResolveLabel(v, iEndTrigger);
93178     }
93179     sqlite3VdbeAddOp0(v, OP_Halt);
93180     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
93181
93182     transferParseError(pParse, pSubParse);
93183     if( db->mallocFailed==0 ){
93184       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
93185     }
93186     pProgram->nMem = pSubParse->nMem;
93187     pProgram->nCsr = pSubParse->nTab;
93188     pProgram->token = (void *)pTrigger;
93189     pPrg->aColmask[0] = pSubParse->oldmask;
93190     pPrg->aColmask[1] = pSubParse->newmask;
93191     sqlite3VdbeDelete(v);
93192   }
93193
93194   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
93195   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
93196   sqlite3StackFree(db, pSubParse);
93197
93198   return pPrg;
93199 }
93200     
93201 /*
93202 ** Return a pointer to a TriggerPrg object containing the sub-program for
93203 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
93204 ** TriggerPrg object exists, a new object is allocated and populated before
93205 ** being returned.
93206 */
93207 static TriggerPrg *getRowTrigger(
93208   Parse *pParse,       /* Current parse context */
93209   Trigger *pTrigger,   /* Trigger to code */
93210   Table *pTab,         /* The table trigger pTrigger is attached to */
93211   int orconf           /* ON CONFLICT algorithm. */
93212 ){
93213   Parse *pRoot = sqlite3ParseToplevel(pParse);
93214   TriggerPrg *pPrg;
93215
93216   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
93217
93218   /* It may be that this trigger has already been coded (or is in the
93219   ** process of being coded). If this is the case, then an entry with
93220   ** a matching TriggerPrg.pTrigger field will be present somewhere
93221   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
93222   for(pPrg=pRoot->pTriggerPrg; 
93223       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
93224       pPrg=pPrg->pNext
93225   );
93226
93227   /* If an existing TriggerPrg could not be located, create a new one. */
93228   if( !pPrg ){
93229     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
93230   }
93231
93232   return pPrg;
93233 }
93234
93235 /*
93236 ** Generate code for the trigger program associated with trigger p on 
93237 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
93238 ** function are the same as those described in the header function for
93239 ** sqlite3CodeRowTrigger()
93240 */
93241 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
93242   Parse *pParse,       /* Parse context */
93243   Trigger *p,          /* Trigger to code */
93244   Table *pTab,         /* The table to code triggers from */
93245   int reg,             /* Reg array containing OLD.* and NEW.* values */
93246   int orconf,          /* ON CONFLICT policy */
93247   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
93248 ){
93249   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
93250   TriggerPrg *pPrg;
93251   pPrg = getRowTrigger(pParse, p, pTab, orconf);
93252   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
93253
93254   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
93255   ** is a pointer to the sub-vdbe containing the trigger program.  */
93256   if( pPrg ){
93257     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
93258
93259     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
93260     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
93261     VdbeComment(
93262         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
93263
93264     /* Set the P5 operand of the OP_Program instruction to non-zero if
93265     ** recursive invocation of this trigger program is disallowed. Recursive
93266     ** invocation is disallowed if (a) the sub-program is really a trigger,
93267     ** not a foreign key action, and (b) the flag to enable recursive triggers
93268     ** is clear.  */
93269     sqlite3VdbeChangeP5(v, (u8)bRecursive);
93270   }
93271 }
93272
93273 /*
93274 ** This is called to code the required FOR EACH ROW triggers for an operation
93275 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
93276 ** is given by the op paramater. The tr_tm parameter determines whether the
93277 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
93278 ** parameter pChanges is passed the list of columns being modified.
93279 **
93280 ** If there are no triggers that fire at the specified time for the specified
93281 ** operation on pTab, this function is a no-op.
93282 **
93283 ** The reg argument is the address of the first in an array of registers 
93284 ** that contain the values substituted for the new.* and old.* references
93285 ** in the trigger program. If N is the number of columns in table pTab
93286 ** (a copy of pTab->nCol), then registers are populated as follows:
93287 **
93288 **   Register       Contains
93289 **   ------------------------------------------------------
93290 **   reg+0          OLD.rowid
93291 **   reg+1          OLD.* value of left-most column of pTab
93292 **   ...            ...
93293 **   reg+N          OLD.* value of right-most column of pTab
93294 **   reg+N+1        NEW.rowid
93295 **   reg+N+2        OLD.* value of left-most column of pTab
93296 **   ...            ...
93297 **   reg+N+N+1      NEW.* value of right-most column of pTab
93298 **
93299 ** For ON DELETE triggers, the registers containing the NEW.* values will
93300 ** never be accessed by the trigger program, so they are not allocated or 
93301 ** populated by the caller (there is no data to populate them with anyway). 
93302 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
93303 ** are never accessed, and so are not allocated by the caller. So, for an
93304 ** ON INSERT trigger, the value passed to this function as parameter reg
93305 ** is not a readable register, although registers (reg+N) through 
93306 ** (reg+N+N+1) are.
93307 **
93308 ** Parameter orconf is the default conflict resolution algorithm for the
93309 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
93310 ** is the instruction that control should jump to if a trigger program
93311 ** raises an IGNORE exception.
93312 */
93313 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
93314   Parse *pParse,       /* Parse context */
93315   Trigger *pTrigger,   /* List of triggers on table pTab */
93316   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
93317   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
93318   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
93319   Table *pTab,         /* The table to code triggers from */
93320   int reg,             /* The first in an array of registers (see above) */
93321   int orconf,          /* ON CONFLICT policy */
93322   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
93323 ){
93324   Trigger *p;          /* Used to iterate through pTrigger list */
93325
93326   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
93327   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
93328   assert( (op==TK_UPDATE)==(pChanges!=0) );
93329
93330   for(p=pTrigger; p; p=p->pNext){
93331
93332     /* Sanity checking:  The schema for the trigger and for the table are
93333     ** always defined.  The trigger must be in the same schema as the table
93334     ** or else it must be a TEMP trigger. */
93335     assert( p->pSchema!=0 );
93336     assert( p->pTabSchema!=0 );
93337     assert( p->pSchema==p->pTabSchema 
93338          || p->pSchema==pParse->db->aDb[1].pSchema );
93339
93340     /* Determine whether we should code this trigger */
93341     if( p->op==op 
93342      && p->tr_tm==tr_tm 
93343      && checkColumnOverlap(p->pColumns, pChanges)
93344     ){
93345       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
93346     }
93347   }
93348 }
93349
93350 /*
93351 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
93352 ** This function returns a 32-bit bitmask indicating which columns of the 
93353 ** old.* or new.* tables actually are used by triggers. This information 
93354 ** may be used by the caller, for example, to avoid having to load the entire
93355 ** old.* record into memory when executing an UPDATE or DELETE command.
93356 **
93357 ** Bit 0 of the returned mask is set if the left-most column of the
93358 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
93359 ** the second leftmost column value is required, and so on. If there
93360 ** are more than 32 columns in the table, and at least one of the columns
93361 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
93362 **
93363 ** It is not possible to determine if the old.rowid or new.rowid column is 
93364 ** accessed by triggers. The caller must always assume that it is.
93365 **
93366 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
93367 ** applies to the old.* table. If 1, the new.* table.
93368 **
93369 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
93370 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
93371 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
93372 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
93373 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
93374 */
93375 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
93376   Parse *pParse,       /* Parse context */
93377   Trigger *pTrigger,   /* List of triggers on table pTab */
93378   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
93379   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
93380   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
93381   Table *pTab,         /* The table to code triggers from */
93382   int orconf           /* Default ON CONFLICT policy for trigger steps */
93383 ){
93384   const int op = pChanges ? TK_UPDATE : TK_DELETE;
93385   u32 mask = 0;
93386   Trigger *p;
93387
93388   assert( isNew==1 || isNew==0 );
93389   for(p=pTrigger; p; p=p->pNext){
93390     if( p->op==op && (tr_tm&p->tr_tm)
93391      && checkColumnOverlap(p->pColumns,pChanges)
93392     ){
93393       TriggerPrg *pPrg;
93394       pPrg = getRowTrigger(pParse, p, pTab, orconf);
93395       if( pPrg ){
93396         mask |= pPrg->aColmask[isNew];
93397       }
93398     }
93399   }
93400
93401   return mask;
93402 }
93403
93404 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
93405
93406 /************** End of trigger.c *********************************************/
93407 /************** Begin file update.c ******************************************/
93408 /*
93409 ** 2001 September 15
93410 **
93411 ** The author disclaims copyright to this source code.  In place of
93412 ** a legal notice, here is a blessing:
93413 **
93414 **    May you do good and not evil.
93415 **    May you find forgiveness for yourself and forgive others.
93416 **    May you share freely, never taking more than you give.
93417 **
93418 *************************************************************************
93419 ** This file contains C code routines that are called by the parser
93420 ** to handle UPDATE statements.
93421 */
93422
93423 #ifndef SQLITE_OMIT_VIRTUALTABLE
93424 /* Forward declaration */
93425 static void updateVirtualTable(
93426   Parse *pParse,       /* The parsing context */
93427   SrcList *pSrc,       /* The virtual table to be modified */
93428   Table *pTab,         /* The virtual table */
93429   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
93430   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
93431   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
93432   Expr *pWhere         /* WHERE clause of the UPDATE statement */
93433 );
93434 #endif /* SQLITE_OMIT_VIRTUALTABLE */
93435
93436 /*
93437 ** The most recently coded instruction was an OP_Column to retrieve the
93438 ** i-th column of table pTab. This routine sets the P4 parameter of the 
93439 ** OP_Column to the default value, if any.
93440 **
93441 ** The default value of a column is specified by a DEFAULT clause in the 
93442 ** column definition. This was either supplied by the user when the table
93443 ** was created, or added later to the table definition by an ALTER TABLE
93444 ** command. If the latter, then the row-records in the table btree on disk
93445 ** may not contain a value for the column and the default value, taken
93446 ** from the P4 parameter of the OP_Column instruction, is returned instead.
93447 ** If the former, then all row-records are guaranteed to include a value
93448 ** for the column and the P4 value is not required.
93449 **
93450 ** Column definitions created by an ALTER TABLE command may only have 
93451 ** literal default values specified: a number, null or a string. (If a more
93452 ** complicated default expression value was provided, it is evaluated 
93453 ** when the ALTER TABLE is executed and one of the literal values written
93454 ** into the sqlite_master table.)
93455 **
93456 ** Therefore, the P4 parameter is only required if the default value for
93457 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
93458 ** function is capable of transforming these types of expressions into
93459 ** sqlite3_value objects.
93460 **
93461 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
93462 ** on register iReg. This is used when an equivalent integer value is 
93463 ** stored in place of an 8-byte floating point value in order to save 
93464 ** space.
93465 */
93466 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
93467   assert( pTab!=0 );
93468   if( !pTab->pSelect ){
93469     sqlite3_value *pValue;
93470     u8 enc = ENC(sqlite3VdbeDb(v));
93471     Column *pCol = &pTab->aCol[i];
93472     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
93473     assert( i<pTab->nCol );
93474     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
93475                          pCol->affinity, &pValue);
93476     if( pValue ){
93477       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
93478     }
93479 #ifndef SQLITE_OMIT_FLOATING_POINT
93480     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
93481       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
93482     }
93483 #endif
93484   }
93485 }
93486
93487 /*
93488 ** Process an UPDATE statement.
93489 **
93490 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
93491 **          \_______/ \________/     \______/       \________________/
93492 *            onError   pTabList      pChanges             pWhere
93493 */
93494 SQLITE_PRIVATE void sqlite3Update(
93495   Parse *pParse,         /* The parser context */
93496   SrcList *pTabList,     /* The table in which we should change things */
93497   ExprList *pChanges,    /* Things to be changed */
93498   Expr *pWhere,          /* The WHERE clause.  May be null */
93499   int onError            /* How to handle constraint errors */
93500 ){
93501   int i, j;              /* Loop counters */
93502   Table *pTab;           /* The table to be updated */
93503   int addr = 0;          /* VDBE instruction address of the start of the loop */
93504   WhereInfo *pWInfo;     /* Information about the WHERE clause */
93505   Vdbe *v;               /* The virtual database engine */
93506   Index *pIdx;           /* For looping over indices */
93507   int nIdx;              /* Number of indices that need updating */
93508   int iCur;              /* VDBE Cursor number of pTab */
93509   sqlite3 *db;           /* The database structure */
93510   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
93511   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
93512                          ** an expression for the i-th column of the table.
93513                          ** aXRef[i]==-1 if the i-th column is not changed. */
93514   int chngRowid;         /* True if the record number is being changed */
93515   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
93516   int openAll = 0;       /* True if all indices need to be opened */
93517   AuthContext sContext;  /* The authorization context */
93518   NameContext sNC;       /* The name-context to resolve expressions in */
93519   int iDb;               /* Database containing the table being updated */
93520   int okOnePass;         /* True for one-pass algorithm without the FIFO */
93521   int hasFK;             /* True if foreign key processing is required */
93522
93523 #ifndef SQLITE_OMIT_TRIGGER
93524   int isView;            /* True when updating a view (INSTEAD OF trigger) */
93525   Trigger *pTrigger;     /* List of triggers on pTab, if required */
93526   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
93527 #endif
93528   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
93529
93530   /* Register Allocations */
93531   int regRowCount = 0;   /* A count of rows changed */
93532   int regOldRowid;       /* The old rowid */
93533   int regNewRowid;       /* The new rowid */
93534   int regNew;
93535   int regOld = 0;
93536   int regRowSet = 0;     /* Rowset of rows to be updated */
93537   int regRec;            /* Register used for new table record to insert */
93538
93539   memset(&sContext, 0, sizeof(sContext));
93540   db = pParse->db;
93541   if( pParse->nErr || db->mallocFailed ){
93542     goto update_cleanup;
93543   }
93544   assert( pTabList->nSrc==1 );
93545
93546   /* Locate the table which we want to update. 
93547   */
93548   pTab = sqlite3SrcListLookup(pParse, pTabList);
93549   if( pTab==0 ) goto update_cleanup;
93550   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
93551
93552   /* Figure out if we have any triggers and if the table being
93553   ** updated is a view.
93554   */
93555 #ifndef SQLITE_OMIT_TRIGGER
93556   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
93557   isView = pTab->pSelect!=0;
93558   assert( pTrigger || tmask==0 );
93559 #else
93560 # define pTrigger 0
93561 # define isView 0
93562 # define tmask 0
93563 #endif
93564 #ifdef SQLITE_OMIT_VIEW
93565 # undef isView
93566 # define isView 0
93567 #endif
93568
93569   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
93570     goto update_cleanup;
93571   }
93572   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
93573     goto update_cleanup;
93574   }
93575   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
93576   if( aXRef==0 ) goto update_cleanup;
93577   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
93578
93579   /* Allocate a cursors for the main database table and for all indices.
93580   ** The index cursors might not be used, but if they are used they
93581   ** need to occur right after the database cursor.  So go ahead and
93582   ** allocate enough space, just in case.
93583   */
93584   pTabList->a[0].iCursor = iCur = pParse->nTab++;
93585   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93586     pParse->nTab++;
93587   }
93588
93589   /* Initialize the name-context */
93590   memset(&sNC, 0, sizeof(sNC));
93591   sNC.pParse = pParse;
93592   sNC.pSrcList = pTabList;
93593
93594   /* Resolve the column names in all the expressions of the
93595   ** of the UPDATE statement.  Also find the column index
93596   ** for each column to be updated in the pChanges array.  For each
93597   ** column to be updated, make sure we have authorization to change
93598   ** that column.
93599   */
93600   chngRowid = 0;
93601   for(i=0; i<pChanges->nExpr; i++){
93602     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
93603       goto update_cleanup;
93604     }
93605     for(j=0; j<pTab->nCol; j++){
93606       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
93607         if( j==pTab->iPKey ){
93608           chngRowid = 1;
93609           pRowidExpr = pChanges->a[i].pExpr;
93610         }
93611         aXRef[j] = i;
93612         break;
93613       }
93614     }
93615     if( j>=pTab->nCol ){
93616       if( sqlite3IsRowid(pChanges->a[i].zName) ){
93617         chngRowid = 1;
93618         pRowidExpr = pChanges->a[i].pExpr;
93619       }else{
93620         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
93621         pParse->checkSchema = 1;
93622         goto update_cleanup;
93623       }
93624     }
93625 #ifndef SQLITE_OMIT_AUTHORIZATION
93626     {
93627       int rc;
93628       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
93629                            pTab->aCol[j].zName, db->aDb[iDb].zName);
93630       if( rc==SQLITE_DENY ){
93631         goto update_cleanup;
93632       }else if( rc==SQLITE_IGNORE ){
93633         aXRef[j] = -1;
93634       }
93635     }
93636 #endif
93637   }
93638
93639   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
93640
93641   /* Allocate memory for the array aRegIdx[].  There is one entry in the
93642   ** array for each index associated with table being updated.  Fill in
93643   ** the value with a register number for indices that are to be used
93644   ** and with zero for unused indices.
93645   */
93646   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
93647   if( nIdx>0 ){
93648     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
93649     if( aRegIdx==0 ) goto update_cleanup;
93650   }
93651   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93652     int reg;
93653     if( chngRowid ){
93654       reg = ++pParse->nMem;
93655     }else{
93656       reg = 0;
93657       for(i=0; i<pIdx->nColumn; i++){
93658         if( aXRef[pIdx->aiColumn[i]]>=0 ){
93659           reg = ++pParse->nMem;
93660           break;
93661         }
93662       }
93663     }
93664     aRegIdx[j] = reg;
93665   }
93666
93667   /* Begin generating code. */
93668   v = sqlite3GetVdbe(pParse);
93669   if( v==0 ) goto update_cleanup;
93670   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
93671   sqlite3BeginWriteOperation(pParse, 1, iDb);
93672
93673 #ifndef SQLITE_OMIT_VIRTUALTABLE
93674   /* Virtual tables must be handled separately */
93675   if( IsVirtual(pTab) ){
93676     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
93677                        pWhere);
93678     pWhere = 0;
93679     pTabList = 0;
93680     goto update_cleanup;
93681   }
93682 #endif
93683
93684   /* Allocate required registers. */
93685   regOldRowid = regNewRowid = ++pParse->nMem;
93686   if( pTrigger || hasFK ){
93687     regOld = pParse->nMem + 1;
93688     pParse->nMem += pTab->nCol;
93689   }
93690   if( chngRowid || pTrigger || hasFK ){
93691     regNewRowid = ++pParse->nMem;
93692   }
93693   regNew = pParse->nMem + 1;
93694   pParse->nMem += pTab->nCol;
93695   regRec = ++pParse->nMem;
93696
93697   /* Start the view context. */
93698   if( isView ){
93699     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
93700   }
93701
93702   /* If we are trying to update a view, realize that view into
93703   ** a ephemeral table.
93704   */
93705 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
93706   if( isView ){
93707     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
93708   }
93709 #endif
93710
93711   /* Resolve the column names in all the expressions in the
93712   ** WHERE clause.
93713   */
93714   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
93715     goto update_cleanup;
93716   }
93717
93718   /* Begin the database scan
93719   */
93720   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
93721   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
93722   if( pWInfo==0 ) goto update_cleanup;
93723   okOnePass = pWInfo->okOnePass;
93724
93725   /* Remember the rowid of every item to be updated.
93726   */
93727   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
93728   if( !okOnePass ){
93729     regRowSet = ++pParse->nMem;
93730     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
93731   }
93732
93733   /* End the database scan loop.
93734   */
93735   sqlite3WhereEnd(pWInfo);
93736
93737   /* Initialize the count of updated rows
93738   */
93739   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
93740     regRowCount = ++pParse->nMem;
93741     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
93742   }
93743
93744   if( !isView ){
93745     /* 
93746     ** Open every index that needs updating.  Note that if any
93747     ** index could potentially invoke a REPLACE conflict resolution 
93748     ** action, then we need to open all indices because we might need
93749     ** to be deleting some records.
93750     */
93751     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
93752     if( onError==OE_Replace ){
93753       openAll = 1;
93754     }else{
93755       openAll = 0;
93756       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93757         if( pIdx->onError==OE_Replace ){
93758           openAll = 1;
93759           break;
93760         }
93761       }
93762     }
93763     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
93764       if( openAll || aRegIdx[i]>0 ){
93765         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
93766         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
93767                        (char*)pKey, P4_KEYINFO_HANDOFF);
93768         assert( pParse->nTab>iCur+i+1 );
93769       }
93770     }
93771   }
93772
93773   /* Top of the update loop */
93774   if( okOnePass ){
93775     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
93776     addr = sqlite3VdbeAddOp0(v, OP_Goto);
93777     sqlite3VdbeJumpHere(v, a1);
93778   }else{
93779     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
93780   }
93781
93782   /* Make cursor iCur point to the record that is being updated. If
93783   ** this record does not exist for some reason (deleted by a trigger,
93784   ** for example, then jump to the next iteration of the RowSet loop.  */
93785   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
93786
93787   /* If the record number will change, set register regNewRowid to
93788   ** contain the new value. If the record number is not being modified,
93789   ** then regNewRowid is the same register as regOldRowid, which is
93790   ** already populated.  */
93791   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
93792   if( chngRowid ){
93793     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
93794     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
93795   }
93796
93797   /* If there are triggers on this table, populate an array of registers 
93798   ** with the required old.* column data.  */
93799   if( hasFK || pTrigger ){
93800     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
93801     oldmask |= sqlite3TriggerColmask(pParse, 
93802         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
93803     );
93804     for(i=0; i<pTab->nCol; i++){
93805       if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
93806         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
93807       }else{
93808         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
93809       }
93810     }
93811     if( chngRowid==0 ){
93812       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
93813     }
93814   }
93815
93816   /* Populate the array of registers beginning at regNew with the new
93817   ** row data. This array is used to check constaints, create the new
93818   ** table and index records, and as the values for any new.* references
93819   ** made by triggers.
93820   **
93821   ** If there are one or more BEFORE triggers, then do not populate the
93822   ** registers associated with columns that are (a) not modified by
93823   ** this UPDATE statement and (b) not accessed by new.* references. The
93824   ** values for registers not modified by the UPDATE must be reloaded from 
93825   ** the database after the BEFORE triggers are fired anyway (as the trigger 
93826   ** may have modified them). So not loading those that are not going to
93827   ** be used eliminates some redundant opcodes.
93828   */
93829   newmask = sqlite3TriggerColmask(
93830       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
93831   );
93832   for(i=0; i<pTab->nCol; i++){
93833     if( i==pTab->iPKey ){
93834       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
93835     }else{
93836       j = aXRef[i];
93837       if( j>=0 ){
93838         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
93839       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
93840         /* This branch loads the value of a column that will not be changed 
93841         ** into a register. This is done if there are no BEFORE triggers, or
93842         ** if there are one or more BEFORE triggers that use this value via
93843         ** a new.* reference in a trigger program.
93844         */
93845         testcase( i==31 );
93846         testcase( i==32 );
93847         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
93848         sqlite3ColumnDefault(v, pTab, i, regNew+i);
93849       }
93850     }
93851   }
93852
93853   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
93854   ** verified. One could argue that this is wrong.
93855   */
93856   if( tmask&TRIGGER_BEFORE ){
93857     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
93858     sqlite3TableAffinityStr(v, pTab);
93859     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
93860         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
93861
93862     /* The row-trigger may have deleted the row being updated. In this
93863     ** case, jump to the next row. No updates or AFTER triggers are 
93864     ** required. This behaviour - what happens when the row being updated
93865     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
93866     ** documentation.
93867     */
93868     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
93869
93870     /* If it did not delete it, the row-trigger may still have modified 
93871     ** some of the columns of the row being updated. Load the values for 
93872     ** all columns not modified by the update statement into their 
93873     ** registers in case this has happened.
93874     */
93875     for(i=0; i<pTab->nCol; i++){
93876       if( aXRef[i]<0 && i!=pTab->iPKey ){
93877         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
93878         sqlite3ColumnDefault(v, pTab, i, regNew+i);
93879       }
93880     }
93881   }
93882
93883   if( !isView ){
93884     int j1;                       /* Address of jump instruction */
93885
93886     /* Do constraint checks. */
93887     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
93888         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
93889
93890     /* Do FK constraint checks. */
93891     if( hasFK ){
93892       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
93893     }
93894
93895     /* Delete the index entries associated with the current record.  */
93896     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
93897     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
93898   
93899     /* If changing the record number, delete the old record.  */
93900     if( hasFK || chngRowid ){
93901       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
93902     }
93903     sqlite3VdbeJumpHere(v, j1);
93904
93905     if( hasFK ){
93906       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
93907     }
93908   
93909     /* Insert the new index entries and the new record. */
93910     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
93911
93912     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
93913     ** handle rows (possibly in other tables) that refer via a foreign key
93914     ** to the row just updated. */ 
93915     if( hasFK ){
93916       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
93917     }
93918   }
93919
93920   /* Increment the row counter 
93921   */
93922   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
93923     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
93924   }
93925
93926   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
93927       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
93928
93929   /* Repeat the above with the next record to be updated, until
93930   ** all record selected by the WHERE clause have been updated.
93931   */
93932   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
93933   sqlite3VdbeJumpHere(v, addr);
93934
93935   /* Close all tables */
93936   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
93937     if( openAll || aRegIdx[i]>0 ){
93938       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
93939     }
93940   }
93941   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
93942
93943   /* Update the sqlite_sequence table by storing the content of the
93944   ** maximum rowid counter values recorded while inserting into
93945   ** autoincrement tables.
93946   */
93947   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
93948     sqlite3AutoincrementEnd(pParse);
93949   }
93950
93951   /*
93952   ** Return the number of rows that were changed. If this routine is 
93953   ** generating code because of a call to sqlite3NestedParse(), do not
93954   ** invoke the callback function.
93955   */
93956   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
93957     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
93958     sqlite3VdbeSetNumCols(v, 1);
93959     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
93960   }
93961
93962 update_cleanup:
93963   sqlite3AuthContextPop(&sContext);
93964   sqlite3DbFree(db, aRegIdx);
93965   sqlite3DbFree(db, aXRef);
93966   sqlite3SrcListDelete(db, pTabList);
93967   sqlite3ExprListDelete(db, pChanges);
93968   sqlite3ExprDelete(db, pWhere);
93969   return;
93970 }
93971 /* Make sure "isView" and other macros defined above are undefined. Otherwise
93972 ** thely may interfere with compilation of other functions in this file
93973 ** (or in another file, if this file becomes part of the amalgamation).  */
93974 #ifdef isView
93975  #undef isView
93976 #endif
93977 #ifdef pTrigger
93978  #undef pTrigger
93979 #endif
93980
93981 #ifndef SQLITE_OMIT_VIRTUALTABLE
93982 /*
93983 ** Generate code for an UPDATE of a virtual table.
93984 **
93985 ** The strategy is that we create an ephemerial table that contains
93986 ** for each row to be changed:
93987 **
93988 **   (A)  The original rowid of that row.
93989 **   (B)  The revised rowid for the row. (note1)
93990 **   (C)  The content of every column in the row.
93991 **
93992 ** Then we loop over this ephemeral table and for each row in
93993 ** the ephermeral table call VUpdate.
93994 **
93995 ** When finished, drop the ephemeral table.
93996 **
93997 ** (note1) Actually, if we know in advance that (A) is always the same
93998 ** as (B) we only store (A), then duplicate (A) when pulling
93999 ** it out of the ephemeral table before calling VUpdate.
94000 */
94001 static void updateVirtualTable(
94002   Parse *pParse,       /* The parsing context */
94003   SrcList *pSrc,       /* The virtual table to be modified */
94004   Table *pTab,         /* The virtual table */
94005   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
94006   Expr *pRowid,        /* Expression used to recompute the rowid */
94007   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
94008   Expr *pWhere         /* WHERE clause of the UPDATE statement */
94009 ){
94010   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
94011   ExprList *pEList = 0;     /* The result set of the SELECT statement */
94012   Select *pSelect = 0;      /* The SELECT statement */
94013   Expr *pExpr;              /* Temporary expression */
94014   int ephemTab;             /* Table holding the result of the SELECT */
94015   int i;                    /* Loop counter */
94016   int addr;                 /* Address of top of loop */
94017   int iReg;                 /* First register in set passed to OP_VUpdate */
94018   sqlite3 *db = pParse->db; /* Database connection */
94019   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
94020   SelectDest dest;
94021
94022   /* Construct the SELECT statement that will find the new values for
94023   ** all updated rows. 
94024   */
94025   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
94026   if( pRowid ){
94027     pEList = sqlite3ExprListAppend(pParse, pEList,
94028                                    sqlite3ExprDup(db, pRowid, 0));
94029   }
94030   assert( pTab->iPKey<0 );
94031   for(i=0; i<pTab->nCol; i++){
94032     if( aXRef[i]>=0 ){
94033       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
94034     }else{
94035       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
94036     }
94037     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
94038   }
94039   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
94040   
94041   /* Create the ephemeral table into which the update results will
94042   ** be stored.
94043   */
94044   assert( v );
94045   ephemTab = pParse->nTab++;
94046   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
94047   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
94048
94049   /* fill the ephemeral table 
94050   */
94051   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
94052   sqlite3Select(pParse, pSelect, &dest);
94053
94054   /* Generate code to scan the ephemeral table and call VUpdate. */
94055   iReg = ++pParse->nMem;
94056   pParse->nMem += pTab->nCol+1;
94057   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
94058   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
94059   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
94060   for(i=0; i<pTab->nCol; i++){
94061     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
94062   }
94063   sqlite3VtabMakeWritable(pParse, pTab);
94064   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
94065   sqlite3MayAbort(pParse);
94066   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
94067   sqlite3VdbeJumpHere(v, addr);
94068   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
94069
94070   /* Cleanup */
94071   sqlite3SelectDelete(db, pSelect);  
94072 }
94073 #endif /* SQLITE_OMIT_VIRTUALTABLE */
94074
94075 /************** End of update.c **********************************************/
94076 /************** Begin file vacuum.c ******************************************/
94077 /*
94078 ** 2003 April 6
94079 **
94080 ** The author disclaims copyright to this source code.  In place of
94081 ** a legal notice, here is a blessing:
94082 **
94083 **    May you do good and not evil.
94084 **    May you find forgiveness for yourself and forgive others.
94085 **    May you share freely, never taking more than you give.
94086 **
94087 *************************************************************************
94088 ** This file contains code used to implement the VACUUM command.
94089 **
94090 ** Most of the code in this file may be omitted by defining the
94091 ** SQLITE_OMIT_VACUUM macro.
94092 */
94093
94094 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
94095 /*
94096 ** Finalize a prepared statement.  If there was an error, store the
94097 ** text of the error message in *pzErrMsg.  Return the result code.
94098 */
94099 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
94100   int rc;
94101   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
94102   if( rc ){
94103     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
94104   }
94105   return rc;
94106 }
94107
94108 /*
94109 ** Execute zSql on database db. Return an error code.
94110 */
94111 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
94112   sqlite3_stmt *pStmt;
94113   VVA_ONLY( int rc; )
94114   if( !zSql ){
94115     return SQLITE_NOMEM;
94116   }
94117   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
94118     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
94119     return sqlite3_errcode(db);
94120   }
94121   VVA_ONLY( rc = ) sqlite3_step(pStmt);
94122   assert( rc!=SQLITE_ROW );
94123   return vacuumFinalize(db, pStmt, pzErrMsg);
94124 }
94125
94126 /*
94127 ** Execute zSql on database db. The statement returns exactly
94128 ** one column. Execute this as SQL on the same database.
94129 */
94130 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
94131   sqlite3_stmt *pStmt;
94132   int rc;
94133
94134   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
94135   if( rc!=SQLITE_OK ) return rc;
94136
94137   while( SQLITE_ROW==sqlite3_step(pStmt) ){
94138     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
94139     if( rc!=SQLITE_OK ){
94140       vacuumFinalize(db, pStmt, pzErrMsg);
94141       return rc;
94142     }
94143   }
94144
94145   return vacuumFinalize(db, pStmt, pzErrMsg);
94146 }
94147
94148 /*
94149 ** The non-standard VACUUM command is used to clean up the database,
94150 ** collapse free space, etc.  It is modelled after the VACUUM command
94151 ** in PostgreSQL.
94152 **
94153 ** In version 1.0.x of SQLite, the VACUUM command would call
94154 ** gdbm_reorganize() on all the database tables.  But beginning
94155 ** with 2.0.0, SQLite no longer uses GDBM so this command has
94156 ** become a no-op.
94157 */
94158 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
94159   Vdbe *v = sqlite3GetVdbe(pParse);
94160   if( v ){
94161     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
94162   }
94163   return;
94164 }
94165
94166 /*
94167 ** This routine implements the OP_Vacuum opcode of the VDBE.
94168 */
94169 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
94170   int rc = SQLITE_OK;     /* Return code from service routines */
94171   Btree *pMain;           /* The database being vacuumed */
94172   Btree *pTemp;           /* The temporary database we vacuum into */
94173   char *zSql = 0;         /* SQL statements */
94174   int saved_flags;        /* Saved value of the db->flags */
94175   int saved_nChange;      /* Saved value of db->nChange */
94176   int saved_nTotalChange; /* Saved value of db->nTotalChange */
94177   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
94178   Db *pDb = 0;            /* Database to detach at end of vacuum */
94179   int isMemDb;            /* True if vacuuming a :memory: database */
94180   int nRes;               /* Bytes of reserved space at the end of each page */
94181   int nDb;                /* Number of attached databases */
94182
94183   if( !db->autoCommit ){
94184     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
94185     return SQLITE_ERROR;
94186   }
94187   if( db->activeVdbeCnt>1 ){
94188     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
94189     return SQLITE_ERROR;
94190   }
94191
94192   /* Save the current value of the database flags so that it can be 
94193   ** restored before returning. Then set the writable-schema flag, and
94194   ** disable CHECK and foreign key constraints.  */
94195   saved_flags = db->flags;
94196   saved_nChange = db->nChange;
94197   saved_nTotalChange = db->nTotalChange;
94198   saved_xTrace = db->xTrace;
94199   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
94200   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
94201   db->xTrace = 0;
94202
94203   pMain = db->aDb[0].pBt;
94204   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
94205
94206   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
94207   ** can be set to 'off' for this file, as it is not recovered if a crash
94208   ** occurs anyway. The integrity of the database is maintained by a
94209   ** (possibly synchronous) transaction opened on the main database before
94210   ** sqlite3BtreeCopyFile() is called.
94211   **
94212   ** An optimisation would be to use a non-journaled pager.
94213   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
94214   ** that actually made the VACUUM run slower.  Very little journalling
94215   ** actually occurs when doing a vacuum since the vacuum_db is initially
94216   ** empty.  Only the journal header is written.  Apparently it takes more
94217   ** time to parse and run the PRAGMA to turn journalling off than it does
94218   ** to write the journal header file.
94219   */
94220   nDb = db->nDb;
94221   if( sqlite3TempInMemory(db) ){
94222     zSql = "ATTACH ':memory:' AS vacuum_db;";
94223   }else{
94224     zSql = "ATTACH '' AS vacuum_db;";
94225   }
94226   rc = execSql(db, pzErrMsg, zSql);
94227   if( db->nDb>nDb ){
94228     pDb = &db->aDb[db->nDb-1];
94229     assert( strcmp(pDb->zName,"vacuum_db")==0 );
94230   }
94231   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94232   pTemp = db->aDb[db->nDb-1].pBt;
94233
94234   /* The call to execSql() to attach the temp database has left the file
94235   ** locked (as there was more than one active statement when the transaction
94236   ** to read the schema was concluded. Unlock it here so that this doesn't
94237   ** cause problems for the call to BtreeSetPageSize() below.  */
94238   sqlite3BtreeCommit(pTemp);
94239
94240   nRes = sqlite3BtreeGetReserve(pMain);
94241
94242   /* A VACUUM cannot change the pagesize of an encrypted database. */
94243 #ifdef SQLITE_HAS_CODEC
94244   if( db->nextPagesize ){
94245     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
94246     int nKey;
94247     char *zKey;
94248     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
94249     if( nKey ) db->nextPagesize = 0;
94250   }
94251 #endif
94252
94253   /* Do not attempt to change the page size for a WAL database */
94254   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
94255                                                ==PAGER_JOURNALMODE_WAL ){
94256     db->nextPagesize = 0;
94257   }
94258
94259   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
94260    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
94261    || NEVER(db->mallocFailed)
94262   ){
94263     rc = SQLITE_NOMEM;
94264     goto end_of_vacuum;
94265   }
94266   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
94267   if( rc!=SQLITE_OK ){
94268     goto end_of_vacuum;
94269   }
94270
94271 #ifndef SQLITE_OMIT_AUTOVACUUM
94272   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
94273                                            sqlite3BtreeGetAutoVacuum(pMain));
94274 #endif
94275
94276   /* Begin a transaction */
94277   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
94278   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94279
94280   /* Query the schema of the main database. Create a mirror schema
94281   ** in the temporary database.
94282   */
94283   rc = execExecSql(db, pzErrMsg,
94284       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
94285       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
94286       "   AND rootpage>0"
94287   );
94288   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94289   rc = execExecSql(db, pzErrMsg,
94290       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
94291       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
94292   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94293   rc = execExecSql(db, pzErrMsg,
94294       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
94295       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
94296   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94297
94298   /* Loop through the tables in the main database. For each, do
94299   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
94300   ** the contents to the temporary database.
94301   */
94302   rc = execExecSql(db, pzErrMsg,
94303       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
94304       "|| ' SELECT * FROM main.' || quote(name) || ';'"
94305       "FROM main.sqlite_master "
94306       "WHERE type = 'table' AND name!='sqlite_sequence' "
94307       "  AND rootpage>0"
94308   );
94309   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94310
94311   /* Copy over the sequence table
94312   */
94313   rc = execExecSql(db, pzErrMsg,
94314       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
94315       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
94316   );
94317   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94318   rc = execExecSql(db, pzErrMsg,
94319       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
94320       "|| ' SELECT * FROM main.' || quote(name) || ';' "
94321       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
94322   );
94323   if( rc!=SQLITE_OK ) goto end_of_vacuum;
94324
94325
94326   /* Copy the triggers, views, and virtual tables from the main database
94327   ** over to the temporary database.  None of these objects has any
94328   ** associated storage, so all we have to do is copy their entries
94329   ** from the SQLITE_MASTER table.
94330   */
94331   rc = execSql(db, pzErrMsg,
94332       "INSERT INTO vacuum_db.sqlite_master "
94333       "  SELECT type, name, tbl_name, rootpage, sql"
94334       "    FROM main.sqlite_master"
94335       "   WHERE type='view' OR type='trigger'"
94336       "      OR (type='table' AND rootpage=0)"
94337   );
94338   if( rc ) goto end_of_vacuum;
94339
94340   /* At this point, unless the main db was completely empty, there is now a
94341   ** transaction open on the vacuum database, but not on the main database.
94342   ** Open a btree level transaction on the main database. This allows a
94343   ** call to sqlite3BtreeCopyFile(). The main database btree level
94344   ** transaction is then committed, so the SQL level never knows it was
94345   ** opened for writing. This way, the SQL transaction used to create the
94346   ** temporary database never needs to be committed.
94347   */
94348   {
94349     u32 meta;
94350     int i;
94351
94352     /* This array determines which meta meta values are preserved in the
94353     ** vacuum.  Even entries are the meta value number and odd entries
94354     ** are an increment to apply to the meta value after the vacuum.
94355     ** The increment is used to increase the schema cookie so that other
94356     ** connections to the same database will know to reread the schema.
94357     */
94358     static const unsigned char aCopy[] = {
94359        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
94360        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
94361        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
94362        BTREE_USER_VERSION,       0,  /* Preserve the user version */
94363     };
94364
94365     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
94366     assert( 1==sqlite3BtreeIsInTrans(pMain) );
94367
94368     /* Copy Btree meta values */
94369     for(i=0; i<ArraySize(aCopy); i+=2){
94370       /* GetMeta() and UpdateMeta() cannot fail in this context because
94371       ** we already have page 1 loaded into cache and marked dirty. */
94372       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
94373       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
94374       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
94375     }
94376
94377     rc = sqlite3BtreeCopyFile(pMain, pTemp);
94378     if( rc!=SQLITE_OK ) goto end_of_vacuum;
94379     rc = sqlite3BtreeCommit(pTemp);
94380     if( rc!=SQLITE_OK ) goto end_of_vacuum;
94381 #ifndef SQLITE_OMIT_AUTOVACUUM
94382     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
94383 #endif
94384   }
94385
94386   assert( rc==SQLITE_OK );
94387   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
94388
94389 end_of_vacuum:
94390   /* Restore the original value of db->flags */
94391   db->flags = saved_flags;
94392   db->nChange = saved_nChange;
94393   db->nTotalChange = saved_nTotalChange;
94394   db->xTrace = saved_xTrace;
94395   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
94396
94397   /* Currently there is an SQL level transaction open on the vacuum
94398   ** database. No locks are held on any other files (since the main file
94399   ** was committed at the btree level). So it safe to end the transaction
94400   ** by manually setting the autoCommit flag to true and detaching the
94401   ** vacuum database. The vacuum_db journal file is deleted when the pager
94402   ** is closed by the DETACH.
94403   */
94404   db->autoCommit = 1;
94405
94406   if( pDb ){
94407     sqlite3BtreeClose(pDb->pBt);
94408     pDb->pBt = 0;
94409     pDb->pSchema = 0;
94410   }
94411
94412   sqlite3ResetInternalSchema(db, 0);
94413
94414   return rc;
94415 }
94416 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
94417
94418 /************** End of vacuum.c **********************************************/
94419 /************** Begin file vtab.c ********************************************/
94420 /*
94421 ** 2006 June 10
94422 **
94423 ** The author disclaims copyright to this source code.  In place of
94424 ** a legal notice, here is a blessing:
94425 **
94426 **    May you do good and not evil.
94427 **    May you find forgiveness for yourself and forgive others.
94428 **    May you share freely, never taking more than you give.
94429 **
94430 *************************************************************************
94431 ** This file contains code used to help implement virtual tables.
94432 */
94433 #ifndef SQLITE_OMIT_VIRTUALTABLE
94434
94435 /*
94436 ** The actual function that does the work of creating a new module.
94437 ** This function implements the sqlite3_create_module() and
94438 ** sqlite3_create_module_v2() interfaces.
94439 */
94440 static int createModule(
94441   sqlite3 *db,                    /* Database in which module is registered */
94442   const char *zName,              /* Name assigned to this module */
94443   const sqlite3_module *pModule,  /* The definition of the module */
94444   void *pAux,                     /* Context pointer for xCreate/xConnect */
94445   void (*xDestroy)(void *)        /* Module destructor function */
94446 ){
94447   int rc, nName;
94448   Module *pMod;
94449
94450   sqlite3_mutex_enter(db->mutex);
94451   nName = sqlite3Strlen30(zName);
94452   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
94453   if( pMod ){
94454     Module *pDel;
94455     char *zCopy = (char *)(&pMod[1]);
94456     memcpy(zCopy, zName, nName+1);
94457     pMod->zName = zCopy;
94458     pMod->pModule = pModule;
94459     pMod->pAux = pAux;
94460     pMod->xDestroy = xDestroy;
94461     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
94462     if( pDel && pDel->xDestroy ){
94463       pDel->xDestroy(pDel->pAux);
94464     }
94465     sqlite3DbFree(db, pDel);
94466     if( pDel==pMod ){
94467       db->mallocFailed = 1;
94468     }
94469     sqlite3ResetInternalSchema(db, 0);
94470   }else if( xDestroy ){
94471     xDestroy(pAux);
94472   }
94473   rc = sqlite3ApiExit(db, SQLITE_OK);
94474   sqlite3_mutex_leave(db->mutex);
94475   return rc;
94476 }
94477
94478
94479 /*
94480 ** External API function used to create a new virtual-table module.
94481 */
94482 SQLITE_API int sqlite3_create_module(
94483   sqlite3 *db,                    /* Database in which module is registered */
94484   const char *zName,              /* Name assigned to this module */
94485   const sqlite3_module *pModule,  /* The definition of the module */
94486   void *pAux                      /* Context pointer for xCreate/xConnect */
94487 ){
94488   return createModule(db, zName, pModule, pAux, 0);
94489 }
94490
94491 /*
94492 ** External API function used to create a new virtual-table module.
94493 */
94494 SQLITE_API int sqlite3_create_module_v2(
94495   sqlite3 *db,                    /* Database in which module is registered */
94496   const char *zName,              /* Name assigned to this module */
94497   const sqlite3_module *pModule,  /* The definition of the module */
94498   void *pAux,                     /* Context pointer for xCreate/xConnect */
94499   void (*xDestroy)(void *)        /* Module destructor function */
94500 ){
94501   return createModule(db, zName, pModule, pAux, xDestroy);
94502 }
94503
94504 /*
94505 ** Lock the virtual table so that it cannot be disconnected.
94506 ** Locks nest.  Every lock should have a corresponding unlock.
94507 ** If an unlock is omitted, resources leaks will occur.  
94508 **
94509 ** If a disconnect is attempted while a virtual table is locked,
94510 ** the disconnect is deferred until all locks have been removed.
94511 */
94512 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
94513   pVTab->nRef++;
94514 }
94515
94516
94517 /*
94518 ** pTab is a pointer to a Table structure representing a virtual-table.
94519 ** Return a pointer to the VTable object used by connection db to access 
94520 ** this virtual-table, if one has been created, or NULL otherwise.
94521 */
94522 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
94523   VTable *pVtab;
94524   assert( IsVirtual(pTab) );
94525   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
94526   return pVtab;
94527 }
94528
94529 /*
94530 ** Decrement the ref-count on a virtual table object. When the ref-count
94531 ** reaches zero, call the xDisconnect() method to delete the object.
94532 */
94533 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
94534   sqlite3 *db = pVTab->db;
94535
94536   assert( db );
94537   assert( pVTab->nRef>0 );
94538   assert( sqlite3SafetyCheckOk(db) );
94539
94540   pVTab->nRef--;
94541   if( pVTab->nRef==0 ){
94542     sqlite3_vtab *p = pVTab->pVtab;
94543     if( p ){
94544       p->pModule->xDisconnect(p);
94545     }
94546     sqlite3DbFree(db, pVTab);
94547   }
94548 }
94549
94550 /*
94551 ** Table p is a virtual table. This function moves all elements in the
94552 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
94553 ** database connections to be disconnected at the next opportunity. 
94554 ** Except, if argument db is not NULL, then the entry associated with
94555 ** connection db is left in the p->pVTable list.
94556 */
94557 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
94558   VTable *pRet = 0;
94559   VTable *pVTable = p->pVTable;
94560   p->pVTable = 0;
94561
94562   /* Assert that the mutex (if any) associated with the BtShared database 
94563   ** that contains table p is held by the caller. See header comments 
94564   ** above function sqlite3VtabUnlockList() for an explanation of why
94565   ** this makes it safe to access the sqlite3.pDisconnect list of any
94566   ** database connection that may have an entry in the p->pVTable list.  */
94567   assert( db==0 ||
94568     sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt) 
94569   );
94570
94571   while( pVTable ){
94572     sqlite3 *db2 = pVTable->db;
94573     VTable *pNext = pVTable->pNext;
94574     assert( db2 );
94575     if( db2==db ){
94576       pRet = pVTable;
94577       p->pVTable = pRet;
94578       pRet->pNext = 0;
94579     }else{
94580       pVTable->pNext = db2->pDisconnect;
94581       db2->pDisconnect = pVTable;
94582     }
94583     pVTable = pNext;
94584   }
94585
94586   assert( !db || pRet );
94587   return pRet;
94588 }
94589
94590
94591 /*
94592 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
94593 **
94594 ** This function may only be called when the mutexes associated with all
94595 ** shared b-tree databases opened using connection db are held by the 
94596 ** caller. This is done to protect the sqlite3.pDisconnect list. The
94597 ** sqlite3.pDisconnect list is accessed only as follows:
94598 **
94599 **   1) By this function. In this case, all BtShared mutexes and the mutex
94600 **      associated with the database handle itself must be held.
94601 **
94602 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
94603 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
94604 **      associated with the database the virtual table is stored in is held
94605 **      or, if the virtual table is stored in a non-sharable database, then
94606 **      the database handle mutex is held.
94607 **
94608 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
94609 ** by multiple threads. It is thread-safe.
94610 */
94611 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
94612   VTable *p = db->pDisconnect;
94613   db->pDisconnect = 0;
94614
94615   assert( sqlite3BtreeHoldsAllMutexes(db) );
94616   assert( sqlite3_mutex_held(db->mutex) );
94617
94618   if( p ){
94619     sqlite3ExpirePreparedStatements(db);
94620     do {
94621       VTable *pNext = p->pNext;
94622       sqlite3VtabUnlock(p);
94623       p = pNext;
94624     }while( p );
94625   }
94626 }
94627
94628 /*
94629 ** Clear any and all virtual-table information from the Table record.
94630 ** This routine is called, for example, just before deleting the Table
94631 ** record.
94632 **
94633 ** Since it is a virtual-table, the Table structure contains a pointer
94634 ** to the head of a linked list of VTable structures. Each VTable 
94635 ** structure is associated with a single sqlite3* user of the schema.
94636 ** The reference count of the VTable structure associated with database 
94637 ** connection db is decremented immediately (which may lead to the 
94638 ** structure being xDisconnected and free). Any other VTable structures
94639 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
94640 ** database connection.
94641 */
94642 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
94643   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
94644   if( p->azModuleArg ){
94645     int i;
94646     for(i=0; i<p->nModuleArg; i++){
94647       sqlite3DbFree(db, p->azModuleArg[i]);
94648     }
94649     sqlite3DbFree(db, p->azModuleArg);
94650   }
94651 }
94652
94653 /*
94654 ** Add a new module argument to pTable->azModuleArg[].
94655 ** The string is not copied - the pointer is stored.  The
94656 ** string will be freed automatically when the table is
94657 ** deleted.
94658 */
94659 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
94660   int i = pTable->nModuleArg++;
94661   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
94662   char **azModuleArg;
94663   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
94664   if( azModuleArg==0 ){
94665     int j;
94666     for(j=0; j<i; j++){
94667       sqlite3DbFree(db, pTable->azModuleArg[j]);
94668     }
94669     sqlite3DbFree(db, zArg);
94670     sqlite3DbFree(db, pTable->azModuleArg);
94671     pTable->nModuleArg = 0;
94672   }else{
94673     azModuleArg[i] = zArg;
94674     azModuleArg[i+1] = 0;
94675   }
94676   pTable->azModuleArg = azModuleArg;
94677 }
94678
94679 /*
94680 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
94681 ** statement.  The module name has been parsed, but the optional list
94682 ** of parameters that follow the module name are still pending.
94683 */
94684 SQLITE_PRIVATE void sqlite3VtabBeginParse(
94685   Parse *pParse,        /* Parsing context */
94686   Token *pName1,        /* Name of new table, or database name */
94687   Token *pName2,        /* Name of new table or NULL */
94688   Token *pModuleName    /* Name of the module for the virtual table */
94689 ){
94690   int iDb;              /* The database the table is being created in */
94691   Table *pTable;        /* The new virtual table */
94692   sqlite3 *db;          /* Database connection */
94693
94694   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
94695   pTable = pParse->pNewTable;
94696   if( pTable==0 ) return;
94697   assert( 0==pTable->pIndex );
94698
94699   db = pParse->db;
94700   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
94701   assert( iDb>=0 );
94702
94703   pTable->tabFlags |= TF_Virtual;
94704   pTable->nModuleArg = 0;
94705   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
94706   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
94707   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
94708   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
94709
94710 #ifndef SQLITE_OMIT_AUTHORIZATION
94711   /* Creating a virtual table invokes the authorization callback twice.
94712   ** The first invocation, to obtain permission to INSERT a row into the
94713   ** sqlite_master table, has already been made by sqlite3StartTable().
94714   ** The second call, to obtain permission to create the table, is made now.
94715   */
94716   if( pTable->azModuleArg ){
94717     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
94718             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
94719   }
94720 #endif
94721 }
94722
94723 /*
94724 ** This routine takes the module argument that has been accumulating
94725 ** in pParse->zArg[] and appends it to the list of arguments on the
94726 ** virtual table currently under construction in pParse->pTable.
94727 */
94728 static void addArgumentToVtab(Parse *pParse){
94729   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
94730     const char *z = (const char*)pParse->sArg.z;
94731     int n = pParse->sArg.n;
94732     sqlite3 *db = pParse->db;
94733     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
94734   }
94735 }
94736
94737 /*
94738 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
94739 ** has been completely parsed.
94740 */
94741 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
94742   Table *pTab = pParse->pNewTable;  /* The table being constructed */
94743   sqlite3 *db = pParse->db;         /* The database connection */
94744
94745   if( pTab==0 ) return;
94746   addArgumentToVtab(pParse);
94747   pParse->sArg.z = 0;
94748   if( pTab->nModuleArg<1 ) return;
94749   
94750   /* If the CREATE VIRTUAL TABLE statement is being entered for the
94751   ** first time (in other words if the virtual table is actually being
94752   ** created now instead of just being read out of sqlite_master) then
94753   ** do additional initialization work and store the statement text
94754   ** in the sqlite_master table.
94755   */
94756   if( !db->init.busy ){
94757     char *zStmt;
94758     char *zWhere;
94759     int iDb;
94760     Vdbe *v;
94761
94762     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
94763     if( pEnd ){
94764       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
94765     }
94766     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
94767
94768     /* A slot for the record has already been allocated in the 
94769     ** SQLITE_MASTER table.  We just need to update that slot with all
94770     ** the information we've collected.  
94771     **
94772     ** The VM register number pParse->regRowid holds the rowid of an
94773     ** entry in the sqlite_master table tht was created for this vtab
94774     ** by sqlite3StartTable().
94775     */
94776     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94777     sqlite3NestedParse(pParse,
94778       "UPDATE %Q.%s "
94779          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
94780        "WHERE rowid=#%d",
94781       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
94782       pTab->zName,
94783       pTab->zName,
94784       zStmt,
94785       pParse->regRowid
94786     );
94787     sqlite3DbFree(db, zStmt);
94788     v = sqlite3GetVdbe(pParse);
94789     sqlite3ChangeCookie(pParse, iDb);
94790
94791     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
94792     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
94793     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
94794     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
94795                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
94796   }
94797
94798   /* If we are rereading the sqlite_master table create the in-memory
94799   ** record of the table. The xConnect() method is not called until
94800   ** the first time the virtual table is used in an SQL statement. This
94801   ** allows a schema that contains virtual tables to be loaded before
94802   ** the required virtual table implementations are registered.  */
94803   else {
94804     Table *pOld;
94805     Schema *pSchema = pTab->pSchema;
94806     const char *zName = pTab->zName;
94807     int nName = sqlite3Strlen30(zName);
94808     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
94809     if( pOld ){
94810       db->mallocFailed = 1;
94811       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
94812       return;
94813     }
94814     pParse->pNewTable = 0;
94815   }
94816 }
94817
94818 /*
94819 ** The parser calls this routine when it sees the first token
94820 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
94821 */
94822 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
94823   addArgumentToVtab(pParse);
94824   pParse->sArg.z = 0;
94825   pParse->sArg.n = 0;
94826 }
94827
94828 /*
94829 ** The parser calls this routine for each token after the first token
94830 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
94831 */
94832 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
94833   Token *pArg = &pParse->sArg;
94834   if( pArg->z==0 ){
94835     pArg->z = p->z;
94836     pArg->n = p->n;
94837   }else{
94838     assert(pArg->z < p->z);
94839     pArg->n = (int)(&p->z[p->n] - pArg->z);
94840   }
94841 }
94842
94843 /*
94844 ** Invoke a virtual table constructor (either xCreate or xConnect). The
94845 ** pointer to the function to invoke is passed as the fourth parameter
94846 ** to this procedure.
94847 */
94848 static int vtabCallConstructor(
94849   sqlite3 *db, 
94850   Table *pTab,
94851   Module *pMod,
94852   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
94853   char **pzErr
94854 ){
94855   VTable *pVTable;
94856   int rc;
94857   const char *const*azArg = (const char *const*)pTab->azModuleArg;
94858   int nArg = pTab->nModuleArg;
94859   char *zErr = 0;
94860   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
94861
94862   if( !zModuleName ){
94863     return SQLITE_NOMEM;
94864   }
94865
94866   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
94867   if( !pVTable ){
94868     sqlite3DbFree(db, zModuleName);
94869     return SQLITE_NOMEM;
94870   }
94871   pVTable->db = db;
94872   pVTable->pMod = pMod;
94873
94874   assert( !db->pVTab );
94875   assert( xConstruct );
94876   db->pVTab = pTab;
94877
94878   /* Invoke the virtual table constructor */
94879   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
94880   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
94881
94882   if( SQLITE_OK!=rc ){
94883     if( zErr==0 ){
94884       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
94885     }else {
94886       *pzErr = sqlite3MPrintf(db, "%s", zErr);
94887       sqlite3_free(zErr);
94888     }
94889     sqlite3DbFree(db, pVTable);
94890   }else if( ALWAYS(pVTable->pVtab) ){
94891     /* Justification of ALWAYS():  A correct vtab constructor must allocate
94892     ** the sqlite3_vtab object if successful.  */
94893     pVTable->pVtab->pModule = pMod->pModule;
94894     pVTable->nRef = 1;
94895     if( db->pVTab ){
94896       const char *zFormat = "vtable constructor did not declare schema: %s";
94897       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
94898       sqlite3VtabUnlock(pVTable);
94899       rc = SQLITE_ERROR;
94900     }else{
94901       int iCol;
94902       /* If everything went according to plan, link the new VTable structure
94903       ** into the linked list headed by pTab->pVTable. Then loop through the 
94904       ** columns of the table to see if any of them contain the token "hidden".
94905       ** If so, set the Column.isHidden flag and remove the token from
94906       ** the type string.  */
94907       pVTable->pNext = pTab->pVTable;
94908       pTab->pVTable = pVTable;
94909
94910       for(iCol=0; iCol<pTab->nCol; iCol++){
94911         char *zType = pTab->aCol[iCol].zType;
94912         int nType;
94913         int i = 0;
94914         if( !zType ) continue;
94915         nType = sqlite3Strlen30(zType);
94916         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
94917           for(i=0; i<nType; i++){
94918             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
94919              && (zType[i+7]=='\0' || zType[i+7]==' ')
94920             ){
94921               i++;
94922               break;
94923             }
94924           }
94925         }
94926         if( i<nType ){
94927           int j;
94928           int nDel = 6 + (zType[i+6] ? 1 : 0);
94929           for(j=i; (j+nDel)<=nType; j++){
94930             zType[j] = zType[j+nDel];
94931           }
94932           if( zType[i]=='\0' && i>0 ){
94933             assert(zType[i-1]==' ');
94934             zType[i-1] = '\0';
94935           }
94936           pTab->aCol[iCol].isHidden = 1;
94937         }
94938       }
94939     }
94940   }
94941
94942   sqlite3DbFree(db, zModuleName);
94943   db->pVTab = 0;
94944   return rc;
94945 }
94946
94947 /*
94948 ** This function is invoked by the parser to call the xConnect() method
94949 ** of the virtual table pTab. If an error occurs, an error code is returned 
94950 ** and an error left in pParse.
94951 **
94952 ** This call is a no-op if table pTab is not a virtual table.
94953 */
94954 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
94955   sqlite3 *db = pParse->db;
94956   const char *zMod;
94957   Module *pMod;
94958   int rc;
94959
94960   assert( pTab );
94961   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
94962     return SQLITE_OK;
94963   }
94964
94965   /* Locate the required virtual table module */
94966   zMod = pTab->azModuleArg[0];
94967   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
94968
94969   if( !pMod ){
94970     const char *zModule = pTab->azModuleArg[0];
94971     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
94972     rc = SQLITE_ERROR;
94973   }else{
94974     char *zErr = 0;
94975     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
94976     if( rc!=SQLITE_OK ){
94977       sqlite3ErrorMsg(pParse, "%s", zErr);
94978     }
94979     sqlite3DbFree(db, zErr);
94980   }
94981
94982   return rc;
94983 }
94984
94985 /*
94986 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
94987 */
94988 static int addToVTrans(sqlite3 *db, VTable *pVTab){
94989   const int ARRAY_INCR = 5;
94990
94991   /* Grow the sqlite3.aVTrans array if required */
94992   if( (db->nVTrans%ARRAY_INCR)==0 ){
94993     VTable **aVTrans;
94994     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
94995     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
94996     if( !aVTrans ){
94997       return SQLITE_NOMEM;
94998     }
94999     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
95000     db->aVTrans = aVTrans;
95001   }
95002
95003   /* Add pVtab to the end of sqlite3.aVTrans */
95004   db->aVTrans[db->nVTrans++] = pVTab;
95005   sqlite3VtabLock(pVTab);
95006   return SQLITE_OK;
95007 }
95008
95009 /*
95010 ** This function is invoked by the vdbe to call the xCreate method
95011 ** of the virtual table named zTab in database iDb. 
95012 **
95013 ** If an error occurs, *pzErr is set to point an an English language
95014 ** description of the error and an SQLITE_XXX error code is returned.
95015 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
95016 */
95017 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
95018   int rc = SQLITE_OK;
95019   Table *pTab;
95020   Module *pMod;
95021   const char *zMod;
95022
95023   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
95024   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
95025
95026   /* Locate the required virtual table module */
95027   zMod = pTab->azModuleArg[0];
95028   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
95029
95030   /* If the module has been registered and includes a Create method, 
95031   ** invoke it now. If the module has not been registered, return an 
95032   ** error. Otherwise, do nothing.
95033   */
95034   if( !pMod ){
95035     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
95036     rc = SQLITE_ERROR;
95037   }else{
95038     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
95039   }
95040
95041   /* Justification of ALWAYS():  The xConstructor method is required to
95042   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
95043   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
95044       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
95045   }
95046
95047   return rc;
95048 }
95049
95050 /*
95051 ** This function is used to set the schema of a virtual table.  It is only
95052 ** valid to call this function from within the xCreate() or xConnect() of a
95053 ** virtual table module.
95054 */
95055 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
95056   Parse *pParse;
95057
95058   int rc = SQLITE_OK;
95059   Table *pTab;
95060   char *zErr = 0;
95061
95062   sqlite3_mutex_enter(db->mutex);
95063   pTab = db->pVTab;
95064   if( !pTab ){
95065     sqlite3Error(db, SQLITE_MISUSE, 0);
95066     sqlite3_mutex_leave(db->mutex);
95067     return SQLITE_MISUSE_BKPT;
95068   }
95069   assert( (pTab->tabFlags & TF_Virtual)!=0 );
95070
95071   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
95072   if( pParse==0 ){
95073     rc = SQLITE_NOMEM;
95074   }else{
95075     pParse->declareVtab = 1;
95076     pParse->db = db;
95077     pParse->nQueryLoop = 1;
95078   
95079     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
95080      && pParse->pNewTable
95081      && !db->mallocFailed
95082      && !pParse->pNewTable->pSelect
95083      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
95084     ){
95085       if( !pTab->aCol ){
95086         pTab->aCol = pParse->pNewTable->aCol;
95087         pTab->nCol = pParse->pNewTable->nCol;
95088         pParse->pNewTable->nCol = 0;
95089         pParse->pNewTable->aCol = 0;
95090       }
95091       db->pVTab = 0;
95092     }else{
95093       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
95094       sqlite3DbFree(db, zErr);
95095       rc = SQLITE_ERROR;
95096     }
95097     pParse->declareVtab = 0;
95098   
95099     if( pParse->pVdbe ){
95100       sqlite3VdbeFinalize(pParse->pVdbe);
95101     }
95102     sqlite3DeleteTable(db, pParse->pNewTable);
95103     sqlite3StackFree(db, pParse);
95104   }
95105
95106   assert( (rc&0xff)==rc );
95107   rc = sqlite3ApiExit(db, rc);
95108   sqlite3_mutex_leave(db->mutex);
95109   return rc;
95110 }
95111
95112 /*
95113 ** This function is invoked by the vdbe to call the xDestroy method
95114 ** of the virtual table named zTab in database iDb. This occurs
95115 ** when a DROP TABLE is mentioned.
95116 **
95117 ** This call is a no-op if zTab is not a virtual table.
95118 */
95119 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
95120   int rc = SQLITE_OK;
95121   Table *pTab;
95122
95123   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
95124   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
95125     VTable *p = vtabDisconnectAll(db, pTab);
95126
95127     assert( rc==SQLITE_OK );
95128     rc = p->pMod->pModule->xDestroy(p->pVtab);
95129
95130     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
95131     if( rc==SQLITE_OK ){
95132       assert( pTab->pVTable==p && p->pNext==0 );
95133       p->pVtab = 0;
95134       pTab->pVTable = 0;
95135       sqlite3VtabUnlock(p);
95136     }
95137   }
95138
95139   return rc;
95140 }
95141
95142 /*
95143 ** This function invokes either the xRollback or xCommit method
95144 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
95145 ** called is identified by the second argument, "offset", which is
95146 ** the offset of the method to call in the sqlite3_module structure.
95147 **
95148 ** The array is cleared after invoking the callbacks. 
95149 */
95150 static void callFinaliser(sqlite3 *db, int offset){
95151   int i;
95152   if( db->aVTrans ){
95153     for(i=0; i<db->nVTrans; i++){
95154       VTable *pVTab = db->aVTrans[i];
95155       sqlite3_vtab *p = pVTab->pVtab;
95156       if( p ){
95157         int (*x)(sqlite3_vtab *);
95158         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
95159         if( x ) x(p);
95160       }
95161       sqlite3VtabUnlock(pVTab);
95162     }
95163     sqlite3DbFree(db, db->aVTrans);
95164     db->nVTrans = 0;
95165     db->aVTrans = 0;
95166   }
95167 }
95168
95169 /*
95170 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
95171 ** array. Return the error code for the first error that occurs, or
95172 ** SQLITE_OK if all xSync operations are successful.
95173 **
95174 ** Set *pzErrmsg to point to a buffer that should be released using 
95175 ** sqlite3DbFree() containing an error message, if one is available.
95176 */
95177 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
95178   int i;
95179   int rc = SQLITE_OK;
95180   VTable **aVTrans = db->aVTrans;
95181
95182   db->aVTrans = 0;
95183   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
95184     int (*x)(sqlite3_vtab *);
95185     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
95186     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
95187       rc = x(pVtab);
95188       sqlite3DbFree(db, *pzErrmsg);
95189       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
95190       sqlite3_free(pVtab->zErrMsg);
95191     }
95192   }
95193   db->aVTrans = aVTrans;
95194   return rc;
95195 }
95196
95197 /*
95198 ** Invoke the xRollback method of all virtual tables in the 
95199 ** sqlite3.aVTrans array. Then clear the array itself.
95200 */
95201 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
95202   callFinaliser(db, offsetof(sqlite3_module,xRollback));
95203   return SQLITE_OK;
95204 }
95205
95206 /*
95207 ** Invoke the xCommit method of all virtual tables in the 
95208 ** sqlite3.aVTrans array. Then clear the array itself.
95209 */
95210 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
95211   callFinaliser(db, offsetof(sqlite3_module,xCommit));
95212   return SQLITE_OK;
95213 }
95214
95215 /*
95216 ** If the virtual table pVtab supports the transaction interface
95217 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
95218 ** not currently open, invoke the xBegin method now.
95219 **
95220 ** If the xBegin call is successful, place the sqlite3_vtab pointer
95221 ** in the sqlite3.aVTrans array.
95222 */
95223 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
95224   int rc = SQLITE_OK;
95225   const sqlite3_module *pModule;
95226
95227   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
95228   ** than zero, then this function is being called from within a
95229   ** virtual module xSync() callback. It is illegal to write to 
95230   ** virtual module tables in this case, so return SQLITE_LOCKED.
95231   */
95232   if( sqlite3VtabInSync(db) ){
95233     return SQLITE_LOCKED;
95234   }
95235   if( !pVTab ){
95236     return SQLITE_OK;
95237   } 
95238   pModule = pVTab->pVtab->pModule;
95239
95240   if( pModule->xBegin ){
95241     int i;
95242
95243
95244     /* If pVtab is already in the aVTrans array, return early */
95245     for(i=0; i<db->nVTrans; i++){
95246       if( db->aVTrans[i]==pVTab ){
95247         return SQLITE_OK;
95248       }
95249     }
95250
95251     /* Invoke the xBegin method */
95252     rc = pModule->xBegin(pVTab->pVtab);
95253     if( rc==SQLITE_OK ){
95254       rc = addToVTrans(db, pVTab);
95255     }
95256   }
95257   return rc;
95258 }
95259
95260 /*
95261 ** The first parameter (pDef) is a function implementation.  The
95262 ** second parameter (pExpr) is the first argument to this function.
95263 ** If pExpr is a column in a virtual table, then let the virtual
95264 ** table implementation have an opportunity to overload the function.
95265 **
95266 ** This routine is used to allow virtual table implementations to
95267 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
95268 **
95269 ** Return either the pDef argument (indicating no change) or a 
95270 ** new FuncDef structure that is marked as ephemeral using the
95271 ** SQLITE_FUNC_EPHEM flag.
95272 */
95273 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
95274   sqlite3 *db,    /* Database connection for reporting malloc problems */
95275   FuncDef *pDef,  /* Function to possibly overload */
95276   int nArg,       /* Number of arguments to the function */
95277   Expr *pExpr     /* First argument to the function */
95278 ){
95279   Table *pTab;
95280   sqlite3_vtab *pVtab;
95281   sqlite3_module *pMod;
95282   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
95283   void *pArg = 0;
95284   FuncDef *pNew;
95285   int rc = 0;
95286   char *zLowerName;
95287   unsigned char *z;
95288
95289
95290   /* Check to see the left operand is a column in a virtual table */
95291   if( NEVER(pExpr==0) ) return pDef;
95292   if( pExpr->op!=TK_COLUMN ) return pDef;
95293   pTab = pExpr->pTab;
95294   if( NEVER(pTab==0) ) return pDef;
95295   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
95296   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
95297   assert( pVtab!=0 );
95298   assert( pVtab->pModule!=0 );
95299   pMod = (sqlite3_module *)pVtab->pModule;
95300   if( pMod->xFindFunction==0 ) return pDef;
95301  
95302   /* Call the xFindFunction method on the virtual table implementation
95303   ** to see if the implementation wants to overload this function 
95304   */
95305   zLowerName = sqlite3DbStrDup(db, pDef->zName);
95306   if( zLowerName ){
95307     for(z=(unsigned char*)zLowerName; *z; z++){
95308       *z = sqlite3UpperToLower[*z];
95309     }
95310     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
95311     sqlite3DbFree(db, zLowerName);
95312   }
95313   if( rc==0 ){
95314     return pDef;
95315   }
95316
95317   /* Create a new ephemeral function definition for the overloaded
95318   ** function */
95319   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
95320                              + sqlite3Strlen30(pDef->zName) + 1);
95321   if( pNew==0 ){
95322     return pDef;
95323   }
95324   *pNew = *pDef;
95325   pNew->zName = (char *)&pNew[1];
95326   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
95327   pNew->xFunc = xFunc;
95328   pNew->pUserData = pArg;
95329   pNew->flags |= SQLITE_FUNC_EPHEM;
95330   return pNew;
95331 }
95332
95333 /*
95334 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
95335 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
95336 ** array if it is missing.  If pTab is already in the array, this routine
95337 ** is a no-op.
95338 */
95339 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
95340   Parse *pToplevel = sqlite3ParseToplevel(pParse);
95341   int i, n;
95342   Table **apVtabLock;
95343
95344   assert( IsVirtual(pTab) );
95345   for(i=0; i<pToplevel->nVtabLock; i++){
95346     if( pTab==pToplevel->apVtabLock[i] ) return;
95347   }
95348   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
95349   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
95350   if( apVtabLock ){
95351     pToplevel->apVtabLock = apVtabLock;
95352     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
95353   }else{
95354     pToplevel->db->mallocFailed = 1;
95355   }
95356 }
95357
95358 #endif /* SQLITE_OMIT_VIRTUALTABLE */
95359
95360 /************** End of vtab.c ************************************************/
95361 /************** Begin file where.c *******************************************/
95362 /*
95363 ** 2001 September 15
95364 **
95365 ** The author disclaims copyright to this source code.  In place of
95366 ** a legal notice, here is a blessing:
95367 **
95368 **    May you do good and not evil.
95369 **    May you find forgiveness for yourself and forgive others.
95370 **    May you share freely, never taking more than you give.
95371 **
95372 *************************************************************************
95373 ** This module contains C code that generates VDBE code used to process
95374 ** the WHERE clause of SQL statements.  This module is responsible for
95375 ** generating the code that loops through a table looking for applicable
95376 ** rows.  Indices are selected and used to speed the search when doing
95377 ** so is applicable.  Because this module is responsible for selecting
95378 ** indices, you might also think of this module as the "query optimizer".
95379 */
95380
95381 /*
95382 ** Trace output macros
95383 */
95384 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
95385 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
95386 #endif
95387 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
95388 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
95389 #else
95390 # define WHERETRACE(X)
95391 #endif
95392
95393 /* Forward reference
95394 */
95395 typedef struct WhereClause WhereClause;
95396 typedef struct WhereMaskSet WhereMaskSet;
95397 typedef struct WhereOrInfo WhereOrInfo;
95398 typedef struct WhereAndInfo WhereAndInfo;
95399 typedef struct WhereCost WhereCost;
95400
95401 /*
95402 ** The query generator uses an array of instances of this structure to
95403 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
95404 ** clause subexpression is separated from the others by AND operators,
95405 ** usually, or sometimes subexpressions separated by OR.
95406 **
95407 ** All WhereTerms are collected into a single WhereClause structure.  
95408 ** The following identity holds:
95409 **
95410 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
95411 **
95412 ** When a term is of the form:
95413 **
95414 **              X <op> <expr>
95415 **
95416 ** where X is a column name and <op> is one of certain operators,
95417 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
95418 ** cursor number and column number for X.  WhereTerm.eOperator records
95419 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
95420 ** use of a bitmask encoding for the operator allows us to search
95421 ** quickly for terms that match any of several different operators.
95422 **
95423 ** A WhereTerm might also be two or more subterms connected by OR:
95424 **
95425 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
95426 **
95427 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
95428 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
95429 ** is collected about the
95430 **
95431 ** If a term in the WHERE clause does not match either of the two previous
95432 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
95433 ** to the original subexpression content and wtFlags is set up appropriately
95434 ** but no other fields in the WhereTerm object are meaningful.
95435 **
95436 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
95437 ** but they do so indirectly.  A single WhereMaskSet structure translates
95438 ** cursor number into bits and the translated bit is stored in the prereq
95439 ** fields.  The translation is used in order to maximize the number of
95440 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
95441 ** spread out over the non-negative integers.  For example, the cursor
95442 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
95443 ** translates these sparse cursor numbers into consecutive integers
95444 ** beginning with 0 in order to make the best possible use of the available
95445 ** bits in the Bitmask.  So, in the example above, the cursor numbers
95446 ** would be mapped into integers 0 through 7.
95447 **
95448 ** The number of terms in a join is limited by the number of bits
95449 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
95450 ** is only able to process joins with 64 or fewer tables.
95451 */
95452 typedef struct WhereTerm WhereTerm;
95453 struct WhereTerm {
95454   Expr *pExpr;            /* Pointer to the subexpression that is this term */
95455   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
95456   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
95457   union {
95458     int leftColumn;         /* Column number of X in "X <op> <expr>" */
95459     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
95460     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
95461   } u;
95462   u16 eOperator;          /* A WO_xx value describing <op> */
95463   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
95464   u8 nChild;              /* Number of children that must disable us */
95465   WhereClause *pWC;       /* The clause this term is part of */
95466   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
95467   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
95468 };
95469
95470 /*
95471 ** Allowed values of WhereTerm.wtFlags
95472 */
95473 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
95474 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
95475 #define TERM_CODED      0x04   /* This term is already coded */
95476 #define TERM_COPIED     0x08   /* Has a child */
95477 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
95478 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
95479 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
95480
95481 /*
95482 ** An instance of the following structure holds all information about a
95483 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
95484 */
95485 struct WhereClause {
95486   Parse *pParse;           /* The parser context */
95487   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
95488   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
95489   u8 op;                   /* Split operator.  TK_AND or TK_OR */
95490   int nTerm;               /* Number of terms */
95491   int nSlot;               /* Number of entries in a[] */
95492   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
95493 #if defined(SQLITE_SMALL_STACK)
95494   WhereTerm aStatic[1];    /* Initial static space for a[] */
95495 #else
95496   WhereTerm aStatic[8];    /* Initial static space for a[] */
95497 #endif
95498 };
95499
95500 /*
95501 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
95502 ** a dynamically allocated instance of the following structure.
95503 */
95504 struct WhereOrInfo {
95505   WhereClause wc;          /* Decomposition into subterms */
95506   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
95507 };
95508
95509 /*
95510 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
95511 ** a dynamically allocated instance of the following structure.
95512 */
95513 struct WhereAndInfo {
95514   WhereClause wc;          /* The subexpression broken out */
95515 };
95516
95517 /*
95518 ** An instance of the following structure keeps track of a mapping
95519 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
95520 **
95521 ** The VDBE cursor numbers are small integers contained in 
95522 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
95523 ** clause, the cursor numbers might not begin with 0 and they might
95524 ** contain gaps in the numbering sequence.  But we want to make maximum
95525 ** use of the bits in our bitmasks.  This structure provides a mapping
95526 ** from the sparse cursor numbers into consecutive integers beginning
95527 ** with 0.
95528 **
95529 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
95530 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
95531 **
95532 ** For example, if the WHERE clause expression used these VDBE
95533 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
95534 ** would map those cursor numbers into bits 0 through 5.
95535 **
95536 ** Note that the mapping is not necessarily ordered.  In the example
95537 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
95538 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
95539 ** does not really matter.  What is important is that sparse cursor
95540 ** numbers all get mapped into bit numbers that begin with 0 and contain
95541 ** no gaps.
95542 */
95543 struct WhereMaskSet {
95544   int n;                        /* Number of assigned cursor values */
95545   int ix[BMS];                  /* Cursor assigned to each bit */
95546 };
95547
95548 /*
95549 ** A WhereCost object records a lookup strategy and the estimated
95550 ** cost of pursuing that strategy.
95551 */
95552 struct WhereCost {
95553   WherePlan plan;    /* The lookup strategy */
95554   double rCost;      /* Overall cost of pursuing this search strategy */
95555   Bitmask used;      /* Bitmask of cursors used by this plan */
95556 };
95557
95558 /*
95559 ** Bitmasks for the operators that indices are able to exploit.  An
95560 ** OR-ed combination of these values can be used when searching for
95561 ** terms in the where clause.
95562 */
95563 #define WO_IN     0x001
95564 #define WO_EQ     0x002
95565 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
95566 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
95567 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
95568 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
95569 #define WO_MATCH  0x040
95570 #define WO_ISNULL 0x080
95571 #define WO_OR     0x100       /* Two or more OR-connected terms */
95572 #define WO_AND    0x200       /* Two or more AND-connected terms */
95573
95574 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
95575 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
95576
95577 /*
95578 ** Value for wsFlags returned by bestIndex() and stored in
95579 ** WhereLevel.wsFlags.  These flags determine which search
95580 ** strategies are appropriate.
95581 **
95582 ** The least significant 12 bits is reserved as a mask for WO_ values above.
95583 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
95584 ** But if the table is the right table of a left join, WhereLevel.wsFlags
95585 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
95586 ** the "op" parameter to findTerm when we are resolving equality constraints.
95587 ** ISNULL constraints will then not be used on the right table of a left
95588 ** join.  Tickets #2177 and #2189.
95589 */
95590 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
95591 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
95592 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
95593 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
95594 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
95595 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
95596 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
95597 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
95598 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
95599 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
95600 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
95601 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
95602 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
95603 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
95604 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
95605 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
95606 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
95607 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
95608 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
95609
95610 /*
95611 ** Initialize a preallocated WhereClause structure.
95612 */
95613 static void whereClauseInit(
95614   WhereClause *pWC,        /* The WhereClause to be initialized */
95615   Parse *pParse,           /* The parsing context */
95616   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
95617 ){
95618   pWC->pParse = pParse;
95619   pWC->pMaskSet = pMaskSet;
95620   pWC->nTerm = 0;
95621   pWC->nSlot = ArraySize(pWC->aStatic);
95622   pWC->a = pWC->aStatic;
95623   pWC->vmask = 0;
95624 }
95625
95626 /* Forward reference */
95627 static void whereClauseClear(WhereClause*);
95628
95629 /*
95630 ** Deallocate all memory associated with a WhereOrInfo object.
95631 */
95632 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
95633   whereClauseClear(&p->wc);
95634   sqlite3DbFree(db, p);
95635 }
95636
95637 /*
95638 ** Deallocate all memory associated with a WhereAndInfo object.
95639 */
95640 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
95641   whereClauseClear(&p->wc);
95642   sqlite3DbFree(db, p);
95643 }
95644
95645 /*
95646 ** Deallocate a WhereClause structure.  The WhereClause structure
95647 ** itself is not freed.  This routine is the inverse of whereClauseInit().
95648 */
95649 static void whereClauseClear(WhereClause *pWC){
95650   int i;
95651   WhereTerm *a;
95652   sqlite3 *db = pWC->pParse->db;
95653   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
95654     if( a->wtFlags & TERM_DYNAMIC ){
95655       sqlite3ExprDelete(db, a->pExpr);
95656     }
95657     if( a->wtFlags & TERM_ORINFO ){
95658       whereOrInfoDelete(db, a->u.pOrInfo);
95659     }else if( a->wtFlags & TERM_ANDINFO ){
95660       whereAndInfoDelete(db, a->u.pAndInfo);
95661     }
95662   }
95663   if( pWC->a!=pWC->aStatic ){
95664     sqlite3DbFree(db, pWC->a);
95665   }
95666 }
95667
95668 /*
95669 ** Add a single new WhereTerm entry to the WhereClause object pWC.
95670 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
95671 ** The index in pWC->a[] of the new WhereTerm is returned on success.
95672 ** 0 is returned if the new WhereTerm could not be added due to a memory
95673 ** allocation error.  The memory allocation failure will be recorded in
95674 ** the db->mallocFailed flag so that higher-level functions can detect it.
95675 **
95676 ** This routine will increase the size of the pWC->a[] array as necessary.
95677 **
95678 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
95679 ** for freeing the expression p is assumed by the WhereClause object pWC.
95680 ** This is true even if this routine fails to allocate a new WhereTerm.
95681 **
95682 ** WARNING:  This routine might reallocate the space used to store
95683 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
95684 ** calling this routine.  Such pointers may be reinitialized by referencing
95685 ** the pWC->a[] array.
95686 */
95687 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
95688   WhereTerm *pTerm;
95689   int idx;
95690   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
95691   if( pWC->nTerm>=pWC->nSlot ){
95692     WhereTerm *pOld = pWC->a;
95693     sqlite3 *db = pWC->pParse->db;
95694     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
95695     if( pWC->a==0 ){
95696       if( wtFlags & TERM_DYNAMIC ){
95697         sqlite3ExprDelete(db, p);
95698       }
95699       pWC->a = pOld;
95700       return 0;
95701     }
95702     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
95703     if( pOld!=pWC->aStatic ){
95704       sqlite3DbFree(db, pOld);
95705     }
95706     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
95707   }
95708   pTerm = &pWC->a[idx = pWC->nTerm++];
95709   pTerm->pExpr = p;
95710   pTerm->wtFlags = wtFlags;
95711   pTerm->pWC = pWC;
95712   pTerm->iParent = -1;
95713   return idx;
95714 }
95715
95716 /*
95717 ** This routine identifies subexpressions in the WHERE clause where
95718 ** each subexpression is separated by the AND operator or some other
95719 ** operator specified in the op parameter.  The WhereClause structure
95720 ** is filled with pointers to subexpressions.  For example:
95721 **
95722 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
95723 **           \________/     \_______________/     \________________/
95724 **            slot[0]            slot[1]               slot[2]
95725 **
95726 ** The original WHERE clause in pExpr is unaltered.  All this routine
95727 ** does is make slot[] entries point to substructure within pExpr.
95728 **
95729 ** In the previous sentence and in the diagram, "slot[]" refers to
95730 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
95731 ** all terms of the WHERE clause.
95732 */
95733 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
95734   pWC->op = (u8)op;
95735   if( pExpr==0 ) return;
95736   if( pExpr->op!=op ){
95737     whereClauseInsert(pWC, pExpr, 0);
95738   }else{
95739     whereSplit(pWC, pExpr->pLeft, op);
95740     whereSplit(pWC, pExpr->pRight, op);
95741   }
95742 }
95743
95744 /*
95745 ** Initialize an expression mask set (a WhereMaskSet object)
95746 */
95747 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
95748
95749 /*
95750 ** Return the bitmask for the given cursor number.  Return 0 if
95751 ** iCursor is not in the set.
95752 */
95753 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
95754   int i;
95755   assert( pMaskSet->n<=sizeof(Bitmask)*8 );
95756   for(i=0; i<pMaskSet->n; i++){
95757     if( pMaskSet->ix[i]==iCursor ){
95758       return ((Bitmask)1)<<i;
95759     }
95760   }
95761   return 0;
95762 }
95763
95764 /*
95765 ** Create a new mask for cursor iCursor.
95766 **
95767 ** There is one cursor per table in the FROM clause.  The number of
95768 ** tables in the FROM clause is limited by a test early in the
95769 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
95770 ** array will never overflow.
95771 */
95772 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
95773   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
95774   pMaskSet->ix[pMaskSet->n++] = iCursor;
95775 }
95776
95777 /*
95778 ** This routine walks (recursively) an expression tree and generates
95779 ** a bitmask indicating which tables are used in that expression
95780 ** tree.
95781 **
95782 ** In order for this routine to work, the calling function must have
95783 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
95784 ** the header comment on that routine for additional information.
95785 ** The sqlite3ResolveExprNames() routines looks for column names and
95786 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
95787 ** the VDBE cursor number of the table.  This routine just has to
95788 ** translate the cursor numbers into bitmask values and OR all
95789 ** the bitmasks together.
95790 */
95791 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
95792 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
95793 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
95794   Bitmask mask = 0;
95795   if( p==0 ) return 0;
95796   if( p->op==TK_COLUMN ){
95797     mask = getMask(pMaskSet, p->iTable);
95798     return mask;
95799   }
95800   mask = exprTableUsage(pMaskSet, p->pRight);
95801   mask |= exprTableUsage(pMaskSet, p->pLeft);
95802   if( ExprHasProperty(p, EP_xIsSelect) ){
95803     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
95804   }else{
95805     mask |= exprListTableUsage(pMaskSet, p->x.pList);
95806   }
95807   return mask;
95808 }
95809 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
95810   int i;
95811   Bitmask mask = 0;
95812   if( pList ){
95813     for(i=0; i<pList->nExpr; i++){
95814       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
95815     }
95816   }
95817   return mask;
95818 }
95819 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
95820   Bitmask mask = 0;
95821   while( pS ){
95822     mask |= exprListTableUsage(pMaskSet, pS->pEList);
95823     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
95824     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
95825     mask |= exprTableUsage(pMaskSet, pS->pWhere);
95826     mask |= exprTableUsage(pMaskSet, pS->pHaving);
95827     pS = pS->pPrior;
95828   }
95829   return mask;
95830 }
95831
95832 /*
95833 ** Return TRUE if the given operator is one of the operators that is
95834 ** allowed for an indexable WHERE clause term.  The allowed operators are
95835 ** "=", "<", ">", "<=", ">=", and "IN".
95836 **
95837 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
95838 ** of one of the following forms: column = expression column > expression
95839 ** column >= expression column < expression column <= expression
95840 ** expression = column expression > column expression >= column
95841 ** expression < column expression <= column column IN
95842 ** (expression-list) column IN (subquery) column IS NULL
95843 */
95844 static int allowedOp(int op){
95845   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
95846   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
95847   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
95848   assert( TK_GE==TK_EQ+4 );
95849   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
95850 }
95851
95852 /*
95853 ** Swap two objects of type TYPE.
95854 */
95855 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
95856
95857 /*
95858 ** Commute a comparison operator.  Expressions of the form "X op Y"
95859 ** are converted into "Y op X".
95860 **
95861 ** If a collation sequence is associated with either the left or right
95862 ** side of the comparison, it remains associated with the same side after
95863 ** the commutation. So "Y collate NOCASE op X" becomes 
95864 ** "X collate NOCASE op Y". This is because any collation sequence on
95865 ** the left hand side of a comparison overrides any collation sequence 
95866 ** attached to the right. For the same reason the EP_ExpCollate flag
95867 ** is not commuted.
95868 */
95869 static void exprCommute(Parse *pParse, Expr *pExpr){
95870   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
95871   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
95872   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
95873   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
95874   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
95875   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
95876   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
95877   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
95878   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
95879   if( pExpr->op>=TK_GT ){
95880     assert( TK_LT==TK_GT+2 );
95881     assert( TK_GE==TK_LE+2 );
95882     assert( TK_GT>TK_EQ );
95883     assert( TK_GT<TK_LE );
95884     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
95885     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
95886   }
95887 }
95888
95889 /*
95890 ** Translate from TK_xx operator to WO_xx bitmask.
95891 */
95892 static u16 operatorMask(int op){
95893   u16 c;
95894   assert( allowedOp(op) );
95895   if( op==TK_IN ){
95896     c = WO_IN;
95897   }else if( op==TK_ISNULL ){
95898     c = WO_ISNULL;
95899   }else{
95900     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
95901     c = (u16)(WO_EQ<<(op-TK_EQ));
95902   }
95903   assert( op!=TK_ISNULL || c==WO_ISNULL );
95904   assert( op!=TK_IN || c==WO_IN );
95905   assert( op!=TK_EQ || c==WO_EQ );
95906   assert( op!=TK_LT || c==WO_LT );
95907   assert( op!=TK_LE || c==WO_LE );
95908   assert( op!=TK_GT || c==WO_GT );
95909   assert( op!=TK_GE || c==WO_GE );
95910   return c;
95911 }
95912
95913 /*
95914 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
95915 ** where X is a reference to the iColumn of table iCur and <op> is one of
95916 ** the WO_xx operator codes specified by the op parameter.
95917 ** Return a pointer to the term.  Return 0 if not found.
95918 */
95919 static WhereTerm *findTerm(
95920   WhereClause *pWC,     /* The WHERE clause to be searched */
95921   int iCur,             /* Cursor number of LHS */
95922   int iColumn,          /* Column number of LHS */
95923   Bitmask notReady,     /* RHS must not overlap with this mask */
95924   u32 op,               /* Mask of WO_xx values describing operator */
95925   Index *pIdx           /* Must be compatible with this index, if not NULL */
95926 ){
95927   WhereTerm *pTerm;
95928   int k;
95929   assert( iCur>=0 );
95930   op &= WO_ALL;
95931   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
95932     if( pTerm->leftCursor==iCur
95933        && (pTerm->prereqRight & notReady)==0
95934        && pTerm->u.leftColumn==iColumn
95935        && (pTerm->eOperator & op)!=0
95936     ){
95937       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
95938         Expr *pX = pTerm->pExpr;
95939         CollSeq *pColl;
95940         char idxaff;
95941         int j;
95942         Parse *pParse = pWC->pParse;
95943
95944         idxaff = pIdx->pTable->aCol[iColumn].affinity;
95945         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
95946
95947         /* Figure out the collation sequence required from an index for
95948         ** it to be useful for optimising expression pX. Store this
95949         ** value in variable pColl.
95950         */
95951         assert(pX->pLeft);
95952         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
95953         assert(pColl || pParse->nErr);
95954
95955         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
95956           if( NEVER(j>=pIdx->nColumn) ) return 0;
95957         }
95958         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
95959       }
95960       return pTerm;
95961     }
95962   }
95963   return 0;
95964 }
95965
95966 /* Forward reference */
95967 static void exprAnalyze(SrcList*, WhereClause*, int);
95968
95969 /*
95970 ** Call exprAnalyze on all terms in a WHERE clause.  
95971 **
95972 **
95973 */
95974 static void exprAnalyzeAll(
95975   SrcList *pTabList,       /* the FROM clause */
95976   WhereClause *pWC         /* the WHERE clause to be analyzed */
95977 ){
95978   int i;
95979   for(i=pWC->nTerm-1; i>=0; i--){
95980     exprAnalyze(pTabList, pWC, i);
95981   }
95982 }
95983
95984 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
95985 /*
95986 ** Check to see if the given expression is a LIKE or GLOB operator that
95987 ** can be optimized using inequality constraints.  Return TRUE if it is
95988 ** so and false if not.
95989 **
95990 ** In order for the operator to be optimizible, the RHS must be a string
95991 ** literal that does not begin with a wildcard.  
95992 */
95993 static int isLikeOrGlob(
95994   Parse *pParse,    /* Parsing and code generating context */
95995   Expr *pExpr,      /* Test this expression */
95996   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
95997   int *pisComplete, /* True if the only wildcard is % in the last character */
95998   int *pnoCase      /* True if uppercase is equivalent to lowercase */
95999 ){
96000   const char *z = 0;         /* String on RHS of LIKE operator */
96001   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
96002   ExprList *pList;           /* List of operands to the LIKE operator */
96003   int c;                     /* One character in z[] */
96004   int cnt;                   /* Number of non-wildcard prefix characters */
96005   char wc[3];                /* Wildcard characters */
96006   sqlite3 *db = pParse->db;  /* Database connection */
96007   sqlite3_value *pVal = 0;
96008   int op;                    /* Opcode of pRight */
96009
96010   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
96011     return 0;
96012   }
96013 #ifdef SQLITE_EBCDIC
96014   if( *pnoCase ) return 0;
96015 #endif
96016   pList = pExpr->x.pList;
96017   pLeft = pList->a[1].pExpr;
96018   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
96019     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
96020     ** be the name of an indexed column with TEXT affinity. */
96021     return 0;
96022   }
96023   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
96024
96025   pRight = pList->a[0].pExpr;
96026   op = pRight->op;
96027   if( op==TK_REGISTER ){
96028     op = pRight->op2;
96029   }
96030   if( op==TK_VARIABLE ){
96031     Vdbe *pReprepare = pParse->pReprepare;
96032     int iCol = pRight->iColumn;
96033     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
96034     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
96035       z = (char *)sqlite3_value_text(pVal);
96036     }
96037     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
96038     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
96039   }else if( op==TK_STRING ){
96040     z = pRight->u.zToken;
96041   }
96042   if( z ){
96043     cnt = 0;
96044     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
96045       cnt++;
96046     }
96047     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
96048       Expr *pPrefix;
96049       *pisComplete = c==wc[0] && z[cnt+1]==0;
96050       pPrefix = sqlite3Expr(db, TK_STRING, z);
96051       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
96052       *ppPrefix = pPrefix;
96053       if( op==TK_VARIABLE ){
96054         Vdbe *v = pParse->pVdbe;
96055         sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
96056         if( *pisComplete && pRight->u.zToken[1] ){
96057           /* If the rhs of the LIKE expression is a variable, and the current
96058           ** value of the variable means there is no need to invoke the LIKE
96059           ** function, then no OP_Variable will be added to the program.
96060           ** This causes problems for the sqlite3_bind_parameter_name()
96061           ** API. To workaround them, add a dummy OP_Variable here.
96062           */ 
96063           int r1 = sqlite3GetTempReg(pParse);
96064           sqlite3ExprCodeTarget(pParse, pRight, r1);
96065           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
96066           sqlite3ReleaseTempReg(pParse, r1);
96067         }
96068       }
96069     }else{
96070       z = 0;
96071     }
96072   }
96073
96074   sqlite3ValueFree(pVal);
96075   return (z!=0);
96076 }
96077 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
96078
96079
96080 #ifndef SQLITE_OMIT_VIRTUALTABLE
96081 /*
96082 ** Check to see if the given expression is of the form
96083 **
96084 **         column MATCH expr
96085 **
96086 ** If it is then return TRUE.  If not, return FALSE.
96087 */
96088 static int isMatchOfColumn(
96089   Expr *pExpr      /* Test this expression */
96090 ){
96091   ExprList *pList;
96092
96093   if( pExpr->op!=TK_FUNCTION ){
96094     return 0;
96095   }
96096   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
96097     return 0;
96098   }
96099   pList = pExpr->x.pList;
96100   if( pList->nExpr!=2 ){
96101     return 0;
96102   }
96103   if( pList->a[1].pExpr->op != TK_COLUMN ){
96104     return 0;
96105   }
96106   return 1;
96107 }
96108 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96109
96110 /*
96111 ** If the pBase expression originated in the ON or USING clause of
96112 ** a join, then transfer the appropriate markings over to derived.
96113 */
96114 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
96115   pDerived->flags |= pBase->flags & EP_FromJoin;
96116   pDerived->iRightJoinTable = pBase->iRightJoinTable;
96117 }
96118
96119 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
96120 /*
96121 ** Analyze a term that consists of two or more OR-connected
96122 ** subterms.  So in:
96123 **
96124 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
96125 **                          ^^^^^^^^^^^^^^^^^^^^
96126 **
96127 ** This routine analyzes terms such as the middle term in the above example.
96128 ** A WhereOrTerm object is computed and attached to the term under
96129 ** analysis, regardless of the outcome of the analysis.  Hence:
96130 **
96131 **     WhereTerm.wtFlags   |=  TERM_ORINFO
96132 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
96133 **
96134 ** The term being analyzed must have two or more of OR-connected subterms.
96135 ** A single subterm might be a set of AND-connected sub-subterms.
96136 ** Examples of terms under analysis:
96137 **
96138 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
96139 **     (B)     x=expr1 OR expr2=x OR x=expr3
96140 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
96141 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
96142 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
96143 **
96144 ** CASE 1:
96145 **
96146 ** If all subterms are of the form T.C=expr for some single column of C
96147 ** a single table T (as shown in example B above) then create a new virtual
96148 ** term that is an equivalent IN expression.  In other words, if the term
96149 ** being analyzed is:
96150 **
96151 **      x = expr1  OR  expr2 = x  OR  x = expr3
96152 **
96153 ** then create a new virtual term like this:
96154 **
96155 **      x IN (expr1,expr2,expr3)
96156 **
96157 ** CASE 2:
96158 **
96159 ** If all subterms are indexable by a single table T, then set
96160 **
96161 **     WhereTerm.eOperator              =  WO_OR
96162 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
96163 **
96164 ** A subterm is "indexable" if it is of the form
96165 ** "T.C <op> <expr>" where C is any column of table T and 
96166 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
96167 ** A subterm is also indexable if it is an AND of two or more
96168 ** subsubterms at least one of which is indexable.  Indexable AND 
96169 ** subterms have their eOperator set to WO_AND and they have
96170 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
96171 **
96172 ** From another point of view, "indexable" means that the subterm could
96173 ** potentially be used with an index if an appropriate index exists.
96174 ** This analysis does not consider whether or not the index exists; that
96175 ** is something the bestIndex() routine will determine.  This analysis
96176 ** only looks at whether subterms appropriate for indexing exist.
96177 **
96178 ** All examples A through E above all satisfy case 2.  But if a term
96179 ** also statisfies case 1 (such as B) we know that the optimizer will
96180 ** always prefer case 1, so in that case we pretend that case 2 is not
96181 ** satisfied.
96182 **
96183 ** It might be the case that multiple tables are indexable.  For example,
96184 ** (E) above is indexable on tables P, Q, and R.
96185 **
96186 ** Terms that satisfy case 2 are candidates for lookup by using
96187 ** separate indices to find rowids for each subterm and composing
96188 ** the union of all rowids using a RowSet object.  This is similar
96189 ** to "bitmap indices" in other database engines.
96190 **
96191 ** OTHERWISE:
96192 **
96193 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
96194 ** zero.  This term is not useful for search.
96195 */
96196 static void exprAnalyzeOrTerm(
96197   SrcList *pSrc,            /* the FROM clause */
96198   WhereClause *pWC,         /* the complete WHERE clause */
96199   int idxTerm               /* Index of the OR-term to be analyzed */
96200 ){
96201   Parse *pParse = pWC->pParse;            /* Parser context */
96202   sqlite3 *db = pParse->db;               /* Database connection */
96203   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
96204   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
96205   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
96206   int i;                                  /* Loop counters */
96207   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
96208   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
96209   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
96210   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
96211   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
96212
96213   /*
96214   ** Break the OR clause into its separate subterms.  The subterms are
96215   ** stored in a WhereClause structure containing within the WhereOrInfo
96216   ** object that is attached to the original OR clause term.
96217   */
96218   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
96219   assert( pExpr->op==TK_OR );
96220   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
96221   if( pOrInfo==0 ) return;
96222   pTerm->wtFlags |= TERM_ORINFO;
96223   pOrWc = &pOrInfo->wc;
96224   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
96225   whereSplit(pOrWc, pExpr, TK_OR);
96226   exprAnalyzeAll(pSrc, pOrWc);
96227   if( db->mallocFailed ) return;
96228   assert( pOrWc->nTerm>=2 );
96229
96230   /*
96231   ** Compute the set of tables that might satisfy cases 1 or 2.
96232   */
96233   indexable = ~(Bitmask)0;
96234   chngToIN = ~(pWC->vmask);
96235   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
96236     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
96237       WhereAndInfo *pAndInfo;
96238       assert( pOrTerm->eOperator==0 );
96239       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
96240       chngToIN = 0;
96241       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
96242       if( pAndInfo ){
96243         WhereClause *pAndWC;
96244         WhereTerm *pAndTerm;
96245         int j;
96246         Bitmask b = 0;
96247         pOrTerm->u.pAndInfo = pAndInfo;
96248         pOrTerm->wtFlags |= TERM_ANDINFO;
96249         pOrTerm->eOperator = WO_AND;
96250         pAndWC = &pAndInfo->wc;
96251         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
96252         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
96253         exprAnalyzeAll(pSrc, pAndWC);
96254         testcase( db->mallocFailed );
96255         if( !db->mallocFailed ){
96256           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
96257             assert( pAndTerm->pExpr );
96258             if( allowedOp(pAndTerm->pExpr->op) ){
96259               b |= getMask(pMaskSet, pAndTerm->leftCursor);
96260             }
96261           }
96262         }
96263         indexable &= b;
96264       }
96265     }else if( pOrTerm->wtFlags & TERM_COPIED ){
96266       /* Skip this term for now.  We revisit it when we process the
96267       ** corresponding TERM_VIRTUAL term */
96268     }else{
96269       Bitmask b;
96270       b = getMask(pMaskSet, pOrTerm->leftCursor);
96271       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
96272         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
96273         b |= getMask(pMaskSet, pOther->leftCursor);
96274       }
96275       indexable &= b;
96276       if( pOrTerm->eOperator!=WO_EQ ){
96277         chngToIN = 0;
96278       }else{
96279         chngToIN &= b;
96280       }
96281     }
96282   }
96283
96284   /*
96285   ** Record the set of tables that satisfy case 2.  The set might be
96286   ** empty.
96287   */
96288   pOrInfo->indexable = indexable;
96289   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
96290
96291   /*
96292   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
96293   ** we have to do some additional checking to see if case 1 really
96294   ** is satisfied.
96295   **
96296   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
96297   ** that there is no possibility of transforming the OR clause into an
96298   ** IN operator because one or more terms in the OR clause contain
96299   ** something other than == on a column in the single table.  The 1-bit
96300   ** case means that every term of the OR clause is of the form
96301   ** "table.column=expr" for some single table.  The one bit that is set
96302   ** will correspond to the common table.  We still need to check to make
96303   ** sure the same column is used on all terms.  The 2-bit case is when
96304   ** the all terms are of the form "table1.column=table2.column".  It
96305   ** might be possible to form an IN operator with either table1.column
96306   ** or table2.column as the LHS if either is common to every term of
96307   ** the OR clause.
96308   **
96309   ** Note that terms of the form "table.column1=table.column2" (the
96310   ** same table on both sizes of the ==) cannot be optimized.
96311   */
96312   if( chngToIN ){
96313     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
96314     int iColumn = -1;         /* Column index on lhs of IN operator */
96315     int iCursor = -1;         /* Table cursor common to all terms */
96316     int j = 0;                /* Loop counter */
96317
96318     /* Search for a table and column that appears on one side or the
96319     ** other of the == operator in every subterm.  That table and column
96320     ** will be recorded in iCursor and iColumn.  There might not be any
96321     ** such table and column.  Set okToChngToIN if an appropriate table
96322     ** and column is found but leave okToChngToIN false if not found.
96323     */
96324     for(j=0; j<2 && !okToChngToIN; j++){
96325       pOrTerm = pOrWc->a;
96326       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
96327         assert( pOrTerm->eOperator==WO_EQ );
96328         pOrTerm->wtFlags &= ~TERM_OR_OK;
96329         if( pOrTerm->leftCursor==iCursor ){
96330           /* This is the 2-bit case and we are on the second iteration and
96331           ** current term is from the first iteration.  So skip this term. */
96332           assert( j==1 );
96333           continue;
96334         }
96335         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
96336           /* This term must be of the form t1.a==t2.b where t2 is in the
96337           ** chngToIN set but t1 is not.  This term will be either preceeded
96338           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
96339           ** and use its inversion. */
96340           testcase( pOrTerm->wtFlags & TERM_COPIED );
96341           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
96342           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
96343           continue;
96344         }
96345         iColumn = pOrTerm->u.leftColumn;
96346         iCursor = pOrTerm->leftCursor;
96347         break;
96348       }
96349       if( i<0 ){
96350         /* No candidate table+column was found.  This can only occur
96351         ** on the second iteration */
96352         assert( j==1 );
96353         assert( (chngToIN&(chngToIN-1))==0 );
96354         assert( chngToIN==getMask(pMaskSet, iCursor) );
96355         break;
96356       }
96357       testcase( j==1 );
96358
96359       /* We have found a candidate table and column.  Check to see if that
96360       ** table and column is common to every term in the OR clause */
96361       okToChngToIN = 1;
96362       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
96363         assert( pOrTerm->eOperator==WO_EQ );
96364         if( pOrTerm->leftCursor!=iCursor ){
96365           pOrTerm->wtFlags &= ~TERM_OR_OK;
96366         }else if( pOrTerm->u.leftColumn!=iColumn ){
96367           okToChngToIN = 0;
96368         }else{
96369           int affLeft, affRight;
96370           /* If the right-hand side is also a column, then the affinities
96371           ** of both right and left sides must be such that no type
96372           ** conversions are required on the right.  (Ticket #2249)
96373           */
96374           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
96375           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
96376           if( affRight!=0 && affRight!=affLeft ){
96377             okToChngToIN = 0;
96378           }else{
96379             pOrTerm->wtFlags |= TERM_OR_OK;
96380           }
96381         }
96382       }
96383     }
96384
96385     /* At this point, okToChngToIN is true if original pTerm satisfies
96386     ** case 1.  In that case, construct a new virtual term that is 
96387     ** pTerm converted into an IN operator.
96388     **
96389     ** EV: R-00211-15100
96390     */
96391     if( okToChngToIN ){
96392       Expr *pDup;            /* A transient duplicate expression */
96393       ExprList *pList = 0;   /* The RHS of the IN operator */
96394       Expr *pLeft = 0;       /* The LHS of the IN operator */
96395       Expr *pNew;            /* The complete IN operator */
96396
96397       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
96398         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
96399         assert( pOrTerm->eOperator==WO_EQ );
96400         assert( pOrTerm->leftCursor==iCursor );
96401         assert( pOrTerm->u.leftColumn==iColumn );
96402         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
96403         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
96404         pLeft = pOrTerm->pExpr->pLeft;
96405       }
96406       assert( pLeft!=0 );
96407       pDup = sqlite3ExprDup(db, pLeft, 0);
96408       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
96409       if( pNew ){
96410         int idxNew;
96411         transferJoinMarkings(pNew, pExpr);
96412         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
96413         pNew->x.pList = pList;
96414         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
96415         testcase( idxNew==0 );
96416         exprAnalyze(pSrc, pWC, idxNew);
96417         pTerm = &pWC->a[idxTerm];
96418         pWC->a[idxNew].iParent = idxTerm;
96419         pTerm->nChild = 1;
96420       }else{
96421         sqlite3ExprListDelete(db, pList);
96422       }
96423       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
96424     }
96425   }
96426 }
96427 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
96428
96429
96430 /*
96431 ** The input to this routine is an WhereTerm structure with only the
96432 ** "pExpr" field filled in.  The job of this routine is to analyze the
96433 ** subexpression and populate all the other fields of the WhereTerm
96434 ** structure.
96435 **
96436 ** If the expression is of the form "<expr> <op> X" it gets commuted
96437 ** to the standard form of "X <op> <expr>".
96438 **
96439 ** If the expression is of the form "X <op> Y" where both X and Y are
96440 ** columns, then the original expression is unchanged and a new virtual
96441 ** term of the form "Y <op> X" is added to the WHERE clause and
96442 ** analyzed separately.  The original term is marked with TERM_COPIED
96443 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
96444 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
96445 ** is a commuted copy of a prior term.)  The original term has nChild=1
96446 ** and the copy has idxParent set to the index of the original term.
96447 */
96448 static void exprAnalyze(
96449   SrcList *pSrc,            /* the FROM clause */
96450   WhereClause *pWC,         /* the WHERE clause */
96451   int idxTerm               /* Index of the term to be analyzed */
96452 ){
96453   WhereTerm *pTerm;                /* The term to be analyzed */
96454   WhereMaskSet *pMaskSet;          /* Set of table index masks */
96455   Expr *pExpr;                     /* The expression to be analyzed */
96456   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
96457   Bitmask prereqAll;               /* Prerequesites of pExpr */
96458   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
96459   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
96460   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
96461   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
96462   int op;                          /* Top-level operator.  pExpr->op */
96463   Parse *pParse = pWC->pParse;     /* Parsing context */
96464   sqlite3 *db = pParse->db;        /* Database connection */
96465
96466   if( db->mallocFailed ){
96467     return;
96468   }
96469   pTerm = &pWC->a[idxTerm];
96470   pMaskSet = pWC->pMaskSet;
96471   pExpr = pTerm->pExpr;
96472   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
96473   op = pExpr->op;
96474   if( op==TK_IN ){
96475     assert( pExpr->pRight==0 );
96476     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
96477       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
96478     }else{
96479       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
96480     }
96481   }else if( op==TK_ISNULL ){
96482     pTerm->prereqRight = 0;
96483   }else{
96484     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
96485   }
96486   prereqAll = exprTableUsage(pMaskSet, pExpr);
96487   if( ExprHasProperty(pExpr, EP_FromJoin) ){
96488     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
96489     prereqAll |= x;
96490     extraRight = x-1;  /* ON clause terms may not be used with an index
96491                        ** on left table of a LEFT JOIN.  Ticket #3015 */
96492   }
96493   pTerm->prereqAll = prereqAll;
96494   pTerm->leftCursor = -1;
96495   pTerm->iParent = -1;
96496   pTerm->eOperator = 0;
96497   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
96498     Expr *pLeft = pExpr->pLeft;
96499     Expr *pRight = pExpr->pRight;
96500     if( pLeft->op==TK_COLUMN ){
96501       pTerm->leftCursor = pLeft->iTable;
96502       pTerm->u.leftColumn = pLeft->iColumn;
96503       pTerm->eOperator = operatorMask(op);
96504     }
96505     if( pRight && pRight->op==TK_COLUMN ){
96506       WhereTerm *pNew;
96507       Expr *pDup;
96508       if( pTerm->leftCursor>=0 ){
96509         int idxNew;
96510         pDup = sqlite3ExprDup(db, pExpr, 0);
96511         if( db->mallocFailed ){
96512           sqlite3ExprDelete(db, pDup);
96513           return;
96514         }
96515         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
96516         if( idxNew==0 ) return;
96517         pNew = &pWC->a[idxNew];
96518         pNew->iParent = idxTerm;
96519         pTerm = &pWC->a[idxTerm];
96520         pTerm->nChild = 1;
96521         pTerm->wtFlags |= TERM_COPIED;
96522       }else{
96523         pDup = pExpr;
96524         pNew = pTerm;
96525       }
96526       exprCommute(pParse, pDup);
96527       pLeft = pDup->pLeft;
96528       pNew->leftCursor = pLeft->iTable;
96529       pNew->u.leftColumn = pLeft->iColumn;
96530       testcase( (prereqLeft | extraRight) != prereqLeft );
96531       pNew->prereqRight = prereqLeft | extraRight;
96532       pNew->prereqAll = prereqAll;
96533       pNew->eOperator = operatorMask(pDup->op);
96534     }
96535   }
96536
96537 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
96538   /* If a term is the BETWEEN operator, create two new virtual terms
96539   ** that define the range that the BETWEEN implements.  For example:
96540   **
96541   **      a BETWEEN b AND c
96542   **
96543   ** is converted into:
96544   **
96545   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
96546   **
96547   ** The two new terms are added onto the end of the WhereClause object.
96548   ** The new terms are "dynamic" and are children of the original BETWEEN
96549   ** term.  That means that if the BETWEEN term is coded, the children are
96550   ** skipped.  Or, if the children are satisfied by an index, the original
96551   ** BETWEEN term is skipped.
96552   */
96553   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
96554     ExprList *pList = pExpr->x.pList;
96555     int i;
96556     static const u8 ops[] = {TK_GE, TK_LE};
96557     assert( pList!=0 );
96558     assert( pList->nExpr==2 );
96559     for(i=0; i<2; i++){
96560       Expr *pNewExpr;
96561       int idxNew;
96562       pNewExpr = sqlite3PExpr(pParse, ops[i], 
96563                              sqlite3ExprDup(db, pExpr->pLeft, 0),
96564                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
96565       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
96566       testcase( idxNew==0 );
96567       exprAnalyze(pSrc, pWC, idxNew);
96568       pTerm = &pWC->a[idxTerm];
96569       pWC->a[idxNew].iParent = idxTerm;
96570     }
96571     pTerm->nChild = 2;
96572   }
96573 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
96574
96575 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
96576   /* Analyze a term that is composed of two or more subterms connected by
96577   ** an OR operator.
96578   */
96579   else if( pExpr->op==TK_OR ){
96580     assert( pWC->op==TK_AND );
96581     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
96582     pTerm = &pWC->a[idxTerm];
96583   }
96584 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
96585
96586 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
96587   /* Add constraints to reduce the search space on a LIKE or GLOB
96588   ** operator.
96589   **
96590   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
96591   **
96592   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
96593   **
96594   ** The last character of the prefix "abc" is incremented to form the
96595   ** termination condition "abd".
96596   */
96597   if( pWC->op==TK_AND 
96598    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
96599   ){
96600     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
96601     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
96602     Expr *pNewExpr1;
96603     Expr *pNewExpr2;
96604     int idxNew1;
96605     int idxNew2;
96606     CollSeq *pColl;    /* Collating sequence to use */
96607
96608     pLeft = pExpr->x.pList->a[1].pExpr;
96609     pStr2 = sqlite3ExprDup(db, pStr1, 0);
96610     if( !db->mallocFailed ){
96611       u8 c, *pC;       /* Last character before the first wildcard */
96612       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
96613       c = *pC;
96614       if( noCase ){
96615         /* The point is to increment the last character before the first
96616         ** wildcard.  But if we increment '@', that will push it into the
96617         ** alphabetic range where case conversions will mess up the 
96618         ** inequality.  To avoid this, make sure to also run the full
96619         ** LIKE on all candidate expressions by clearing the isComplete flag
96620         */
96621         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
96622
96623
96624         c = sqlite3UpperToLower[c];
96625       }
96626       *pC = c + 1;
96627     }
96628     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
96629     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
96630                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
96631                      pStr1, 0);
96632     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
96633     testcase( idxNew1==0 );
96634     exprAnalyze(pSrc, pWC, idxNew1);
96635     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
96636                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
96637                      pStr2, 0);
96638     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
96639     testcase( idxNew2==0 );
96640     exprAnalyze(pSrc, pWC, idxNew2);
96641     pTerm = &pWC->a[idxTerm];
96642     if( isComplete ){
96643       pWC->a[idxNew1].iParent = idxTerm;
96644       pWC->a[idxNew2].iParent = idxTerm;
96645       pTerm->nChild = 2;
96646     }
96647   }
96648 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
96649
96650 #ifndef SQLITE_OMIT_VIRTUALTABLE
96651   /* Add a WO_MATCH auxiliary term to the constraint set if the
96652   ** current expression is of the form:  column MATCH expr.
96653   ** This information is used by the xBestIndex methods of
96654   ** virtual tables.  The native query optimizer does not attempt
96655   ** to do anything with MATCH functions.
96656   */
96657   if( isMatchOfColumn(pExpr) ){
96658     int idxNew;
96659     Expr *pRight, *pLeft;
96660     WhereTerm *pNewTerm;
96661     Bitmask prereqColumn, prereqExpr;
96662
96663     pRight = pExpr->x.pList->a[0].pExpr;
96664     pLeft = pExpr->x.pList->a[1].pExpr;
96665     prereqExpr = exprTableUsage(pMaskSet, pRight);
96666     prereqColumn = exprTableUsage(pMaskSet, pLeft);
96667     if( (prereqExpr & prereqColumn)==0 ){
96668       Expr *pNewExpr;
96669       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
96670                               0, sqlite3ExprDup(db, pRight, 0), 0);
96671       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
96672       testcase( idxNew==0 );
96673       pNewTerm = &pWC->a[idxNew];
96674       pNewTerm->prereqRight = prereqExpr;
96675       pNewTerm->leftCursor = pLeft->iTable;
96676       pNewTerm->u.leftColumn = pLeft->iColumn;
96677       pNewTerm->eOperator = WO_MATCH;
96678       pNewTerm->iParent = idxTerm;
96679       pTerm = &pWC->a[idxTerm];
96680       pTerm->nChild = 1;
96681       pTerm->wtFlags |= TERM_COPIED;
96682       pNewTerm->prereqAll = pTerm->prereqAll;
96683     }
96684   }
96685 #endif /* SQLITE_OMIT_VIRTUALTABLE */
96686
96687   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
96688   ** an index for tables to the left of the join.
96689   */
96690   pTerm->prereqRight |= extraRight;
96691 }
96692
96693 /*
96694 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
96695 ** a reference to any table other than the iBase table.
96696 */
96697 static int referencesOtherTables(
96698   ExprList *pList,          /* Search expressions in ths list */
96699   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
96700   int iFirst,               /* Be searching with the iFirst-th expression */
96701   int iBase                 /* Ignore references to this table */
96702 ){
96703   Bitmask allowed = ~getMask(pMaskSet, iBase);
96704   while( iFirst<pList->nExpr ){
96705     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
96706       return 1;
96707     }
96708   }
96709   return 0;
96710 }
96711
96712
96713 /*
96714 ** This routine decides if pIdx can be used to satisfy the ORDER BY
96715 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
96716 ** ORDER BY clause, this routine returns 0.
96717 **
96718 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
96719 ** left-most table in the FROM clause of that same SELECT statement and
96720 ** the table has a cursor number of "base".  pIdx is an index on pTab.
96721 **
96722 ** nEqCol is the number of columns of pIdx that are used as equality
96723 ** constraints.  Any of these columns may be missing from the ORDER BY
96724 ** clause and the match can still be a success.
96725 **
96726 ** All terms of the ORDER BY that match against the index must be either
96727 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
96728 ** index do not need to satisfy this constraint.)  The *pbRev value is
96729 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
96730 ** the ORDER BY clause is all ASC.
96731 */
96732 static int isSortingIndex(
96733   Parse *pParse,          /* Parsing context */
96734   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
96735   Index *pIdx,            /* The index we are testing */
96736   int base,               /* Cursor number for the table to be sorted */
96737   ExprList *pOrderBy,     /* The ORDER BY clause */
96738   int nEqCol,             /* Number of index columns with == constraints */
96739   int *pbRev              /* Set to 1 if ORDER BY is DESC */
96740 ){
96741   int i, j;                       /* Loop counters */
96742   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
96743   int nTerm;                      /* Number of ORDER BY terms */
96744   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
96745   sqlite3 *db = pParse->db;
96746
96747   assert( pOrderBy!=0 );
96748   nTerm = pOrderBy->nExpr;
96749   assert( nTerm>0 );
96750
96751   /* Argument pIdx must either point to a 'real' named index structure, 
96752   ** or an index structure allocated on the stack by bestBtreeIndex() to
96753   ** represent the rowid index that is part of every table.  */
96754   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
96755
96756   /* Match terms of the ORDER BY clause against columns of
96757   ** the index.
96758   **
96759   ** Note that indices have pIdx->nColumn regular columns plus
96760   ** one additional column containing the rowid.  The rowid column
96761   ** of the index is also allowed to match against the ORDER BY
96762   ** clause.
96763   */
96764   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
96765     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
96766     CollSeq *pColl;    /* The collating sequence of pExpr */
96767     int termSortOrder; /* Sort order for this term */
96768     int iColumn;       /* The i-th column of the index.  -1 for rowid */
96769     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
96770     const char *zColl; /* Name of the collating sequence for i-th index term */
96771
96772     pExpr = pTerm->pExpr;
96773     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
96774       /* Can not use an index sort on anything that is not a column in the
96775       ** left-most table of the FROM clause */
96776       break;
96777     }
96778     pColl = sqlite3ExprCollSeq(pParse, pExpr);
96779     if( !pColl ){
96780       pColl = db->pDfltColl;
96781     }
96782     if( pIdx->zName && i<pIdx->nColumn ){
96783       iColumn = pIdx->aiColumn[i];
96784       if( iColumn==pIdx->pTable->iPKey ){
96785         iColumn = -1;
96786       }
96787       iSortOrder = pIdx->aSortOrder[i];
96788       zColl = pIdx->azColl[i];
96789     }else{
96790       iColumn = -1;
96791       iSortOrder = 0;
96792       zColl = pColl->zName;
96793     }
96794     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
96795       /* Term j of the ORDER BY clause does not match column i of the index */
96796       if( i<nEqCol ){
96797         /* If an index column that is constrained by == fails to match an
96798         ** ORDER BY term, that is OK.  Just ignore that column of the index
96799         */
96800         continue;
96801       }else if( i==pIdx->nColumn ){
96802         /* Index column i is the rowid.  All other terms match. */
96803         break;
96804       }else{
96805         /* If an index column fails to match and is not constrained by ==
96806         ** then the index cannot satisfy the ORDER BY constraint.
96807         */
96808         return 0;
96809       }
96810     }
96811     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
96812     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
96813     assert( iSortOrder==0 || iSortOrder==1 );
96814     termSortOrder = iSortOrder ^ pTerm->sortOrder;
96815     if( i>nEqCol ){
96816       if( termSortOrder!=sortOrder ){
96817         /* Indices can only be used if all ORDER BY terms past the
96818         ** equality constraints are all either DESC or ASC. */
96819         return 0;
96820       }
96821     }else{
96822       sortOrder = termSortOrder;
96823     }
96824     j++;
96825     pTerm++;
96826     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
96827       /* If the indexed column is the primary key and everything matches
96828       ** so far and none of the ORDER BY terms to the right reference other
96829       ** tables in the join, then we are assured that the index can be used 
96830       ** to sort because the primary key is unique and so none of the other
96831       ** columns will make any difference
96832       */
96833       j = nTerm;
96834     }
96835   }
96836
96837   *pbRev = sortOrder!=0;
96838   if( j>=nTerm ){
96839     /* All terms of the ORDER BY clause are covered by this index so
96840     ** this index can be used for sorting. */
96841     return 1;
96842   }
96843   if( pIdx->onError!=OE_None && i==pIdx->nColumn
96844       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
96845     /* All terms of this index match some prefix of the ORDER BY clause
96846     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
96847     ** clause reference other tables in a join.  If this is all true then
96848     ** the order by clause is superfluous. */
96849     return 1;
96850   }
96851   return 0;
96852 }
96853
96854 /*
96855 ** Prepare a crude estimate of the logarithm of the input value.
96856 ** The results need not be exact.  This is only used for estimating
96857 ** the total cost of performing operations with O(logN) or O(NlogN)
96858 ** complexity.  Because N is just a guess, it is no great tragedy if
96859 ** logN is a little off.
96860 */
96861 static double estLog(double N){
96862   double logN = 1;
96863   double x = 10;
96864   while( N>x ){
96865     logN += 1;
96866     x *= 10;
96867   }
96868   return logN;
96869 }
96870
96871 /*
96872 ** Two routines for printing the content of an sqlite3_index_info
96873 ** structure.  Used for testing and debugging only.  If neither
96874 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
96875 ** are no-ops.
96876 */
96877 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
96878 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
96879   int i;
96880   if( !sqlite3WhereTrace ) return;
96881   for(i=0; i<p->nConstraint; i++){
96882     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
96883        i,
96884        p->aConstraint[i].iColumn,
96885        p->aConstraint[i].iTermOffset,
96886        p->aConstraint[i].op,
96887        p->aConstraint[i].usable);
96888   }
96889   for(i=0; i<p->nOrderBy; i++){
96890     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
96891        i,
96892        p->aOrderBy[i].iColumn,
96893        p->aOrderBy[i].desc);
96894   }
96895 }
96896 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
96897   int i;
96898   if( !sqlite3WhereTrace ) return;
96899   for(i=0; i<p->nConstraint; i++){
96900     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
96901        i,
96902        p->aConstraintUsage[i].argvIndex,
96903        p->aConstraintUsage[i].omit);
96904   }
96905   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
96906   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
96907   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
96908   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
96909 }
96910 #else
96911 #define TRACE_IDX_INPUTS(A)
96912 #define TRACE_IDX_OUTPUTS(A)
96913 #endif
96914
96915 /* 
96916 ** Required because bestIndex() is called by bestOrClauseIndex() 
96917 */
96918 static void bestIndex(
96919     Parse*, WhereClause*, struct SrcList_item*,
96920     Bitmask, Bitmask, ExprList*, WhereCost*);
96921
96922 /*
96923 ** This routine attempts to find an scanning strategy that can be used 
96924 ** to optimize an 'OR' expression that is part of a WHERE clause. 
96925 **
96926 ** The table associated with FROM clause term pSrc may be either a
96927 ** regular B-Tree table or a virtual table.
96928 */
96929 static void bestOrClauseIndex(
96930   Parse *pParse,              /* The parsing context */
96931   WhereClause *pWC,           /* The WHERE clause */
96932   struct SrcList_item *pSrc,  /* The FROM clause term to search */
96933   Bitmask notReady,           /* Mask of cursors not available for indexing */
96934   Bitmask notValid,           /* Cursors not available for any purpose */
96935   ExprList *pOrderBy,         /* The ORDER BY clause */
96936   WhereCost *pCost            /* Lowest cost query plan */
96937 ){
96938 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
96939   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
96940   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
96941   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
96942   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
96943
96944   /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
96945   ** are used */
96946   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
96947     return;
96948   }
96949
96950   /* Search the WHERE clause terms for a usable WO_OR term. */
96951   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
96952     if( pTerm->eOperator==WO_OR 
96953      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
96954      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
96955     ){
96956       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
96957       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
96958       WhereTerm *pOrTerm;
96959       int flags = WHERE_MULTI_OR;
96960       double rTotal = 0;
96961       double nRow = 0;
96962       Bitmask used = 0;
96963
96964       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
96965         WhereCost sTermCost;
96966         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
96967           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
96968         ));
96969         if( pOrTerm->eOperator==WO_AND ){
96970           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
96971           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
96972         }else if( pOrTerm->leftCursor==iCur ){
96973           WhereClause tempWC;
96974           tempWC.pParse = pWC->pParse;
96975           tempWC.pMaskSet = pWC->pMaskSet;
96976           tempWC.op = TK_AND;
96977           tempWC.a = pOrTerm;
96978           tempWC.nTerm = 1;
96979           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
96980         }else{
96981           continue;
96982         }
96983         rTotal += sTermCost.rCost;
96984         nRow += sTermCost.plan.nRow;
96985         used |= sTermCost.used;
96986         if( rTotal>=pCost->rCost ) break;
96987       }
96988
96989       /* If there is an ORDER BY clause, increase the scan cost to account 
96990       ** for the cost of the sort. */
96991       if( pOrderBy!=0 ){
96992         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
96993                     rTotal, rTotal+nRow*estLog(nRow)));
96994         rTotal += nRow*estLog(nRow);
96995       }
96996
96997       /* If the cost of scanning using this OR term for optimization is
96998       ** less than the current cost stored in pCost, replace the contents
96999       ** of pCost. */
97000       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
97001       if( rTotal<pCost->rCost ){
97002         pCost->rCost = rTotal;
97003         pCost->used = used;
97004         pCost->plan.nRow = nRow;
97005         pCost->plan.wsFlags = flags;
97006         pCost->plan.u.pTerm = pTerm;
97007       }
97008     }
97009   }
97010 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
97011 }
97012
97013 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
97014 /*
97015 ** Return TRUE if the WHERE clause term pTerm is of a form where it
97016 ** could be used with an index to access pSrc, assuming an appropriate
97017 ** index existed.
97018 */
97019 static int termCanDriveIndex(
97020   WhereTerm *pTerm,              /* WHERE clause term to check */
97021   struct SrcList_item *pSrc,     /* Table we are trying to access */
97022   Bitmask notReady               /* Tables in outer loops of the join */
97023 ){
97024   char aff;
97025   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
97026   if( pTerm->eOperator!=WO_EQ ) return 0;
97027   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
97028   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
97029   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
97030   return 1;
97031 }
97032 #endif
97033
97034 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
97035 /*
97036 ** If the query plan for pSrc specified in pCost is a full table scan
97037 ** and indexing is allows (if there is no NOT INDEXED clause) and it
97038 ** possible to construct a transient index that would perform better
97039 ** than a full table scan even when the cost of constructing the index
97040 ** is taken into account, then alter the query plan to use the
97041 ** transient index.
97042 */
97043 static void bestAutomaticIndex(
97044   Parse *pParse,              /* The parsing context */
97045   WhereClause *pWC,           /* The WHERE clause */
97046   struct SrcList_item *pSrc,  /* The FROM clause term to search */
97047   Bitmask notReady,           /* Mask of cursors that are not available */
97048   WhereCost *pCost            /* Lowest cost query plan */
97049 ){
97050   double nTableRow;           /* Rows in the input table */
97051   double logN;                /* log(nTableRow) */
97052   double costTempIdx;         /* per-query cost of the transient index */
97053   WhereTerm *pTerm;           /* A single term of the WHERE clause */
97054   WhereTerm *pWCEnd;          /* End of pWC->a[] */
97055   Table *pTable;              /* Table tht might be indexed */
97056
97057   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
97058     /* Automatic indices are disabled at run-time */
97059     return;
97060   }
97061   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
97062     /* We already have some kind of index in use for this query. */
97063     return;
97064   }
97065   if( pSrc->notIndexed ){
97066     /* The NOT INDEXED clause appears in the SQL. */
97067     return;
97068   }
97069
97070   assert( pParse->nQueryLoop >= (double)1 );
97071   pTable = pSrc->pTab;
97072   nTableRow = pTable->nRowEst;
97073   logN = estLog(nTableRow);
97074   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
97075   if( costTempIdx>=pCost->rCost ){
97076     /* The cost of creating the transient table would be greater than
97077     ** doing the full table scan */
97078     return;
97079   }
97080
97081   /* Search for any equality comparison term */
97082   pWCEnd = &pWC->a[pWC->nTerm];
97083   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
97084     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
97085       WHERETRACE(("auto-index reduces cost from %.2f to %.2f\n",
97086                     pCost->rCost, costTempIdx));
97087       pCost->rCost = costTempIdx;
97088       pCost->plan.nRow = logN + 1;
97089       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
97090       pCost->used = pTerm->prereqRight;
97091       break;
97092     }
97093   }
97094 }
97095 #else
97096 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
97097 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
97098
97099
97100 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
97101 /*
97102 ** Generate code to construct the Index object for an automatic index
97103 ** and to set up the WhereLevel object pLevel so that the code generator
97104 ** makes use of the automatic index.
97105 */
97106 static void constructAutomaticIndex(
97107   Parse *pParse,              /* The parsing context */
97108   WhereClause *pWC,           /* The WHERE clause */
97109   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
97110   Bitmask notReady,           /* Mask of cursors that are not available */
97111   WhereLevel *pLevel          /* Write new index here */
97112 ){
97113   int nColumn;                /* Number of columns in the constructed index */
97114   WhereTerm *pTerm;           /* A single term of the WHERE clause */
97115   WhereTerm *pWCEnd;          /* End of pWC->a[] */
97116   int nByte;                  /* Byte of memory needed for pIdx */
97117   Index *pIdx;                /* Object describing the transient index */
97118   Vdbe *v;                    /* Prepared statement under construction */
97119   int regIsInit;              /* Register set by initialization */
97120   int addrInit;               /* Address of the initialization bypass jump */
97121   Table *pTable;              /* The table being indexed */
97122   KeyInfo *pKeyinfo;          /* Key information for the index */   
97123   int addrTop;                /* Top of the index fill loop */
97124   int regRecord;              /* Register holding an index record */
97125   int n;                      /* Column counter */
97126   int i;                      /* Loop counter */
97127   int mxBitCol;               /* Maximum column in pSrc->colUsed */
97128   CollSeq *pColl;             /* Collating sequence to on a column */
97129   Bitmask idxCols;            /* Bitmap of columns used for indexing */
97130   Bitmask extraCols;          /* Bitmap of additional columns */
97131
97132   /* Generate code to skip over the creation and initialization of the
97133   ** transient index on 2nd and subsequent iterations of the loop. */
97134   v = pParse->pVdbe;
97135   assert( v!=0 );
97136   regIsInit = ++pParse->nMem;
97137   addrInit = sqlite3VdbeAddOp1(v, OP_If, regIsInit);
97138   sqlite3VdbeAddOp2(v, OP_Integer, 1, regIsInit);
97139
97140   /* Count the number of columns that will be added to the index
97141   ** and used to match WHERE clause constraints */
97142   nColumn = 0;
97143   pTable = pSrc->pTab;
97144   pWCEnd = &pWC->a[pWC->nTerm];
97145   idxCols = 0;
97146   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
97147     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
97148       int iCol = pTerm->u.leftColumn;
97149       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
97150       testcase( iCol==BMS );
97151       testcase( iCol==BMS-1 );
97152       if( (idxCols & cMask)==0 ){
97153         nColumn++;
97154         idxCols |= cMask;
97155       }
97156     }
97157   }
97158   assert( nColumn>0 );
97159   pLevel->plan.nEq = nColumn;
97160
97161   /* Count the number of additional columns needed to create a
97162   ** covering index.  A "covering index" is an index that contains all
97163   ** columns that are needed by the query.  With a covering index, the
97164   ** original table never needs to be accessed.  Automatic indices must
97165   ** be a covering index because the index will not be updated if the
97166   ** original table changes and the index and table cannot both be used
97167   ** if they go out of sync.
97168   */
97169   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
97170   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
97171   testcase( pTable->nCol==BMS-1 );
97172   testcase( pTable->nCol==BMS-2 );
97173   for(i=0; i<mxBitCol; i++){
97174     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
97175   }
97176   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
97177     nColumn += pTable->nCol - BMS + 1;
97178   }
97179   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
97180
97181   /* Construct the Index object to describe this index */
97182   nByte = sizeof(Index);
97183   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
97184   nByte += nColumn*sizeof(char*);   /* Index.azColl */
97185   nByte += nColumn;                 /* Index.aSortOrder */
97186   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
97187   if( pIdx==0 ) return;
97188   pLevel->plan.u.pIdx = pIdx;
97189   pIdx->azColl = (char**)&pIdx[1];
97190   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
97191   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
97192   pIdx->zName = "auto-index";
97193   pIdx->nColumn = nColumn;
97194   pIdx->pTable = pTable;
97195   n = 0;
97196   idxCols = 0;
97197   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
97198     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
97199       int iCol = pTerm->u.leftColumn;
97200       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
97201       if( (idxCols & cMask)==0 ){
97202         Expr *pX = pTerm->pExpr;
97203         idxCols |= cMask;
97204         pIdx->aiColumn[n] = pTerm->u.leftColumn;
97205         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
97206         pIdx->azColl[n] = pColl->zName;
97207         n++;
97208       }
97209     }
97210   }
97211   assert( (u32)n==pLevel->plan.nEq );
97212
97213   /* Add additional columns needed to make the automatic index into
97214   ** a covering index */
97215   for(i=0; i<mxBitCol; i++){
97216     if( extraCols & (((Bitmask)1)<<i) ){
97217       pIdx->aiColumn[n] = i;
97218       pIdx->azColl[n] = "BINARY";
97219       n++;
97220     }
97221   }
97222   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
97223     for(i=BMS-1; i<pTable->nCol; i++){
97224       pIdx->aiColumn[n] = i;
97225       pIdx->azColl[n] = "BINARY";
97226       n++;
97227     }
97228   }
97229   assert( n==nColumn );
97230
97231   /* Create the automatic index */
97232   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
97233   assert( pLevel->iIdxCur>=0 );
97234   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
97235                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
97236   VdbeComment((v, "for %s", pTable->zName));
97237
97238   /* Fill the automatic index with content */
97239   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
97240   regRecord = sqlite3GetTempReg(pParse);
97241   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
97242   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
97243   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
97244   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
97245   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
97246   sqlite3VdbeJumpHere(v, addrTop);
97247   sqlite3ReleaseTempReg(pParse, regRecord);
97248   
97249   /* Jump here when skipping the initialization */
97250   sqlite3VdbeJumpHere(v, addrInit);
97251 }
97252 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
97253
97254 #ifndef SQLITE_OMIT_VIRTUALTABLE
97255 /*
97256 ** Allocate and populate an sqlite3_index_info structure. It is the 
97257 ** responsibility of the caller to eventually release the structure
97258 ** by passing the pointer returned by this function to sqlite3_free().
97259 */
97260 static sqlite3_index_info *allocateIndexInfo(
97261   Parse *pParse, 
97262   WhereClause *pWC,
97263   struct SrcList_item *pSrc,
97264   ExprList *pOrderBy
97265 ){
97266   int i, j;
97267   int nTerm;
97268   struct sqlite3_index_constraint *pIdxCons;
97269   struct sqlite3_index_orderby *pIdxOrderBy;
97270   struct sqlite3_index_constraint_usage *pUsage;
97271   WhereTerm *pTerm;
97272   int nOrderBy;
97273   sqlite3_index_info *pIdxInfo;
97274
97275   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
97276
97277   /* Count the number of possible WHERE clause constraints referring
97278   ** to this virtual table */
97279   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
97280     if( pTerm->leftCursor != pSrc->iCursor ) continue;
97281     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
97282     testcase( pTerm->eOperator==WO_IN );
97283     testcase( pTerm->eOperator==WO_ISNULL );
97284     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
97285     nTerm++;
97286   }
97287
97288   /* If the ORDER BY clause contains only columns in the current 
97289   ** virtual table then allocate space for the aOrderBy part of
97290   ** the sqlite3_index_info structure.
97291   */
97292   nOrderBy = 0;
97293   if( pOrderBy ){
97294     for(i=0; i<pOrderBy->nExpr; i++){
97295       Expr *pExpr = pOrderBy->a[i].pExpr;
97296       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
97297     }
97298     if( i==pOrderBy->nExpr ){
97299       nOrderBy = pOrderBy->nExpr;
97300     }
97301   }
97302
97303   /* Allocate the sqlite3_index_info structure
97304   */
97305   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
97306                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
97307                            + sizeof(*pIdxOrderBy)*nOrderBy );
97308   if( pIdxInfo==0 ){
97309     sqlite3ErrorMsg(pParse, "out of memory");
97310     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
97311     return 0;
97312   }
97313
97314   /* Initialize the structure.  The sqlite3_index_info structure contains
97315   ** many fields that are declared "const" to prevent xBestIndex from
97316   ** changing them.  We have to do some funky casting in order to
97317   ** initialize those fields.
97318   */
97319   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
97320   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
97321   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
97322   *(int*)&pIdxInfo->nConstraint = nTerm;
97323   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
97324   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
97325   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
97326   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
97327                                                                    pUsage;
97328
97329   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
97330     if( pTerm->leftCursor != pSrc->iCursor ) continue;
97331     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
97332     testcase( pTerm->eOperator==WO_IN );
97333     testcase( pTerm->eOperator==WO_ISNULL );
97334     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
97335     pIdxCons[j].iColumn = pTerm->u.leftColumn;
97336     pIdxCons[j].iTermOffset = i;
97337     pIdxCons[j].op = (u8)pTerm->eOperator;
97338     /* The direct assignment in the previous line is possible only because
97339     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
97340     ** following asserts verify this fact. */
97341     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
97342     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
97343     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
97344     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
97345     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
97346     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
97347     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
97348     j++;
97349   }
97350   for(i=0; i<nOrderBy; i++){
97351     Expr *pExpr = pOrderBy->a[i].pExpr;
97352     pIdxOrderBy[i].iColumn = pExpr->iColumn;
97353     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
97354   }
97355
97356   return pIdxInfo;
97357 }
97358
97359 /*
97360 ** The table object reference passed as the second argument to this function
97361 ** must represent a virtual table. This function invokes the xBestIndex()
97362 ** method of the virtual table with the sqlite3_index_info pointer passed
97363 ** as the argument.
97364 **
97365 ** If an error occurs, pParse is populated with an error message and a
97366 ** non-zero value is returned. Otherwise, 0 is returned and the output
97367 ** part of the sqlite3_index_info structure is left populated.
97368 **
97369 ** Whether or not an error is returned, it is the responsibility of the
97370 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
97371 ** that this is required.
97372 */
97373 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
97374   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
97375   int i;
97376   int rc;
97377
97378   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
97379   TRACE_IDX_INPUTS(p);
97380   rc = pVtab->pModule->xBestIndex(pVtab, p);
97381   TRACE_IDX_OUTPUTS(p);
97382
97383   if( rc!=SQLITE_OK ){
97384     if( rc==SQLITE_NOMEM ){
97385       pParse->db->mallocFailed = 1;
97386     }else if( !pVtab->zErrMsg ){
97387       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
97388     }else{
97389       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
97390     }
97391   }
97392   sqlite3_free(pVtab->zErrMsg);
97393   pVtab->zErrMsg = 0;
97394
97395   for(i=0; i<p->nConstraint; i++){
97396     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
97397       sqlite3ErrorMsg(pParse, 
97398           "table %s: xBestIndex returned an invalid plan", pTab->zName);
97399     }
97400   }
97401
97402   return pParse->nErr;
97403 }
97404
97405
97406 /*
97407 ** Compute the best index for a virtual table.
97408 **
97409 ** The best index is computed by the xBestIndex method of the virtual
97410 ** table module.  This routine is really just a wrapper that sets up
97411 ** the sqlite3_index_info structure that is used to communicate with
97412 ** xBestIndex.
97413 **
97414 ** In a join, this routine might be called multiple times for the
97415 ** same virtual table.  The sqlite3_index_info structure is created
97416 ** and initialized on the first invocation and reused on all subsequent
97417 ** invocations.  The sqlite3_index_info structure is also used when
97418 ** code is generated to access the virtual table.  The whereInfoDelete() 
97419 ** routine takes care of freeing the sqlite3_index_info structure after
97420 ** everybody has finished with it.
97421 */
97422 static void bestVirtualIndex(
97423   Parse *pParse,                  /* The parsing context */
97424   WhereClause *pWC,               /* The WHERE clause */
97425   struct SrcList_item *pSrc,      /* The FROM clause term to search */
97426   Bitmask notReady,               /* Mask of cursors not available for index */
97427   Bitmask notValid,               /* Cursors not valid for any purpose */
97428   ExprList *pOrderBy,             /* The order by clause */
97429   WhereCost *pCost,               /* Lowest cost query plan */
97430   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
97431 ){
97432   Table *pTab = pSrc->pTab;
97433   sqlite3_index_info *pIdxInfo;
97434   struct sqlite3_index_constraint *pIdxCons;
97435   struct sqlite3_index_constraint_usage *pUsage;
97436   WhereTerm *pTerm;
97437   int i, j;
97438   int nOrderBy;
97439   double rCost;
97440
97441   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
97442   ** malloc in allocateIndexInfo() fails and this function returns leaving
97443   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
97444   */
97445   memset(pCost, 0, sizeof(*pCost));
97446   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
97447
97448   /* If the sqlite3_index_info structure has not been previously
97449   ** allocated and initialized, then allocate and initialize it now.
97450   */
97451   pIdxInfo = *ppIdxInfo;
97452   if( pIdxInfo==0 ){
97453     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
97454   }
97455   if( pIdxInfo==0 ){
97456     return;
97457   }
97458
97459   /* At this point, the sqlite3_index_info structure that pIdxInfo points
97460   ** to will have been initialized, either during the current invocation or
97461   ** during some prior invocation.  Now we just have to customize the
97462   ** details of pIdxInfo for the current invocation and pass it to
97463   ** xBestIndex.
97464   */
97465
97466   /* The module name must be defined. Also, by this point there must
97467   ** be a pointer to an sqlite3_vtab structure. Otherwise
97468   ** sqlite3ViewGetColumnNames() would have picked up the error. 
97469   */
97470   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
97471   assert( sqlite3GetVTable(pParse->db, pTab) );
97472
97473   /* Set the aConstraint[].usable fields and initialize all 
97474   ** output variables to zero.
97475   **
97476   ** aConstraint[].usable is true for constraints where the right-hand
97477   ** side contains only references to tables to the left of the current
97478   ** table.  In other words, if the constraint is of the form:
97479   **
97480   **           column = expr
97481   **
97482   ** and we are evaluating a join, then the constraint on column is 
97483   ** only valid if all tables referenced in expr occur to the left
97484   ** of the table containing column.
97485   **
97486   ** The aConstraints[] array contains entries for all constraints
97487   ** on the current table.  That way we only have to compute it once
97488   ** even though we might try to pick the best index multiple times.
97489   ** For each attempt at picking an index, the order of tables in the
97490   ** join might be different so we have to recompute the usable flag
97491   ** each time.
97492   */
97493   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
97494   pUsage = pIdxInfo->aConstraintUsage;
97495   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
97496     j = pIdxCons->iTermOffset;
97497     pTerm = &pWC->a[j];
97498     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
97499   }
97500   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
97501   if( pIdxInfo->needToFreeIdxStr ){
97502     sqlite3_free(pIdxInfo->idxStr);
97503   }
97504   pIdxInfo->idxStr = 0;
97505   pIdxInfo->idxNum = 0;
97506   pIdxInfo->needToFreeIdxStr = 0;
97507   pIdxInfo->orderByConsumed = 0;
97508   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
97509   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
97510   nOrderBy = pIdxInfo->nOrderBy;
97511   if( !pOrderBy ){
97512     pIdxInfo->nOrderBy = 0;
97513   }
97514
97515   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
97516     return;
97517   }
97518
97519   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
97520   for(i=0; i<pIdxInfo->nConstraint; i++){
97521     if( pUsage[i].argvIndex>0 ){
97522       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
97523     }
97524   }
97525
97526   /* If there is an ORDER BY clause, and the selected virtual table index
97527   ** does not satisfy it, increase the cost of the scan accordingly. This
97528   ** matches the processing for non-virtual tables in bestBtreeIndex().
97529   */
97530   rCost = pIdxInfo->estimatedCost;
97531   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
97532     rCost += estLog(rCost)*rCost;
97533   }
97534
97535   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
97536   ** inital value of lowestCost in this loop. If it is, then the
97537   ** (cost<lowestCost) test below will never be true.
97538   ** 
97539   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
97540   ** is defined.
97541   */
97542   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
97543     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
97544   }else{
97545     pCost->rCost = rCost;
97546   }
97547   pCost->plan.u.pVtabIdx = pIdxInfo;
97548   if( pIdxInfo->orderByConsumed ){
97549     pCost->plan.wsFlags |= WHERE_ORDERBY;
97550   }
97551   pCost->plan.nEq = 0;
97552   pIdxInfo->nOrderBy = nOrderBy;
97553
97554   /* Try to find a more efficient access pattern by using multiple indexes
97555   ** to optimize an OR expression within the WHERE clause. 
97556   */
97557   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
97558 }
97559 #endif /* SQLITE_OMIT_VIRTUALTABLE */
97560
97561 /*
97562 ** Argument pIdx is a pointer to an index structure that has an array of
97563 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
97564 ** stored in Index.aSample. The domain of values stored in said column
97565 ** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
97566 ** Region 0 contains all values smaller than the first sample value. Region
97567 ** 1 contains values larger than or equal to the value of the first sample,
97568 ** but smaller than the value of the second. And so on.
97569 **
97570 ** If successful, this function determines which of the regions value 
97571 ** pVal lies in, sets *piRegion to the region index (a value between 0
97572 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
97573 ** Or, if an OOM occurs while converting text values between encodings,
97574 ** SQLITE_NOMEM is returned and *piRegion is undefined.
97575 */
97576 #ifdef SQLITE_ENABLE_STAT2
97577 static int whereRangeRegion(
97578   Parse *pParse,              /* Database connection */
97579   Index *pIdx,                /* Index to consider domain of */
97580   sqlite3_value *pVal,        /* Value to consider */
97581   int *piRegion               /* OUT: Region of domain in which value lies */
97582 ){
97583   if( ALWAYS(pVal) ){
97584     IndexSample *aSample = pIdx->aSample;
97585     int i = 0;
97586     int eType = sqlite3_value_type(pVal);
97587
97588     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
97589       double r = sqlite3_value_double(pVal);
97590       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
97591         if( aSample[i].eType==SQLITE_NULL ) continue;
97592         if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
97593       }
97594     }else{ 
97595       sqlite3 *db = pParse->db;
97596       CollSeq *pColl;
97597       const u8 *z;
97598       int n;
97599
97600       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
97601       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
97602
97603       if( eType==SQLITE_BLOB ){
97604         z = (const u8 *)sqlite3_value_blob(pVal);
97605         pColl = db->pDfltColl;
97606         assert( pColl->enc==SQLITE_UTF8 );
97607       }else{
97608         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
97609         if( pColl==0 ){
97610           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
97611                           *pIdx->azColl);
97612           return SQLITE_ERROR;
97613         }
97614         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
97615         if( !z ){
97616           return SQLITE_NOMEM;
97617         }
97618         assert( z && pColl && pColl->xCmp );
97619       }
97620       n = sqlite3ValueBytes(pVal, pColl->enc);
97621
97622       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
97623         int r;
97624         int eSampletype = aSample[i].eType;
97625         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
97626         if( (eSampletype!=eType) ) break;
97627 #ifndef SQLITE_OMIT_UTF16
97628         if( pColl->enc!=SQLITE_UTF8 ){
97629           int nSample;
97630           char *zSample = sqlite3Utf8to16(
97631               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
97632           );
97633           if( !zSample ){
97634             assert( db->mallocFailed );
97635             return SQLITE_NOMEM;
97636           }
97637           r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
97638           sqlite3DbFree(db, zSample);
97639         }else
97640 #endif
97641         {
97642           r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
97643         }
97644         if( r>0 ) break;
97645       }
97646     }
97647
97648     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
97649     *piRegion = i;
97650   }
97651   return SQLITE_OK;
97652 }
97653 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
97654
97655 /*
97656 ** If expression pExpr represents a literal value, set *pp to point to
97657 ** an sqlite3_value structure containing the same value, with affinity
97658 ** aff applied to it, before returning. It is the responsibility of the 
97659 ** caller to eventually release this structure by passing it to 
97660 ** sqlite3ValueFree().
97661 **
97662 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
97663 ** is an SQL variable that currently has a non-NULL value bound to it,
97664 ** create an sqlite3_value structure containing this value, again with
97665 ** affinity aff applied to it, instead.
97666 **
97667 ** If neither of the above apply, set *pp to NULL.
97668 **
97669 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
97670 */
97671 #ifdef SQLITE_ENABLE_STAT2
97672 static int valueFromExpr(
97673   Parse *pParse, 
97674   Expr *pExpr, 
97675   u8 aff, 
97676   sqlite3_value **pp
97677 ){
97678   /* The evalConstExpr() function will have already converted any TK_VARIABLE
97679   ** expression involved in an comparison into a TK_REGISTER. */
97680   assert( pExpr->op!=TK_VARIABLE );
97681   if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
97682     int iVar = pExpr->iColumn;
97683     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
97684     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
97685     return SQLITE_OK;
97686   }
97687   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
97688 }
97689 #endif
97690
97691 /*
97692 ** This function is used to estimate the number of rows that will be visited
97693 ** by scanning an index for a range of values. The range may have an upper
97694 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
97695 ** and lower bounds are represented by pLower and pUpper respectively. For
97696 ** example, assuming that index p is on t1(a):
97697 **
97698 **   ... FROM t1 WHERE a > ? AND a < ? ...
97699 **                    |_____|   |_____|
97700 **                       |         |
97701 **                     pLower    pUpper
97702 **
97703 ** If either of the upper or lower bound is not present, then NULL is passed in
97704 ** place of the corresponding WhereTerm.
97705 **
97706 ** The nEq parameter is passed the index of the index column subject to the
97707 ** range constraint. Or, equivalently, the number of equality constraints
97708 ** optimized by the proposed index scan. For example, assuming index p is
97709 ** on t1(a, b), and the SQL query is:
97710 **
97711 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
97712 **
97713 ** then nEq should be passed the value 1 (as the range restricted column,
97714 ** b, is the second left-most column of the index). Or, if the query is:
97715 **
97716 **   ... FROM t1 WHERE a > ? AND a < ? ...
97717 **
97718 ** then nEq should be passed 0.
97719 **
97720 ** The returned value is an integer between 1 and 100, inclusive. A return
97721 ** value of 1 indicates that the proposed range scan is expected to visit
97722 ** approximately 1/100th (1%) of the rows selected by the nEq equality
97723 ** constraints (if any). A return value of 100 indicates that it is expected
97724 ** that the range scan will visit every row (100%) selected by the equality
97725 ** constraints.
97726 **
97727 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
97728 ** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
97729 ** results in a return of 33 and a range constraint (x>? AND x<?) results
97730 ** in a return of 11.
97731 */
97732 static int whereRangeScanEst(
97733   Parse *pParse,       /* Parsing & code generating context */
97734   Index *p,            /* The index containing the range-compared column; "x" */
97735   int nEq,             /* index into p->aCol[] of the range-compared column */
97736   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
97737   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
97738   int *piEst           /* OUT: Return value */
97739 ){
97740   int rc = SQLITE_OK;
97741
97742 #ifdef SQLITE_ENABLE_STAT2
97743
97744   if( nEq==0 && p->aSample ){
97745     sqlite3_value *pLowerVal = 0;
97746     sqlite3_value *pUpperVal = 0;
97747     int iEst;
97748     int iLower = 0;
97749     int iUpper = SQLITE_INDEX_SAMPLES;
97750     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
97751
97752     if( pLower ){
97753       Expr *pExpr = pLower->pExpr->pRight;
97754       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
97755     }
97756     if( rc==SQLITE_OK && pUpper ){
97757       Expr *pExpr = pUpper->pExpr->pRight;
97758       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
97759     }
97760
97761     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
97762       sqlite3ValueFree(pLowerVal);
97763       sqlite3ValueFree(pUpperVal);
97764       goto range_est_fallback;
97765     }else if( pLowerVal==0 ){
97766       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
97767       if( pLower ) iLower = iUpper/2;
97768     }else if( pUpperVal==0 ){
97769       rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
97770       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
97771     }else{
97772       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
97773       if( rc==SQLITE_OK ){
97774         rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
97775       }
97776     }
97777
97778     iEst = iUpper - iLower;
97779     testcase( iEst==SQLITE_INDEX_SAMPLES );
97780     assert( iEst<=SQLITE_INDEX_SAMPLES );
97781     if( iEst<1 ){
97782       iEst = 1;
97783     }
97784
97785     sqlite3ValueFree(pLowerVal);
97786     sqlite3ValueFree(pUpperVal);
97787     *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
97788     return rc;
97789   }
97790 range_est_fallback:
97791 #else
97792   UNUSED_PARAMETER(pParse);
97793   UNUSED_PARAMETER(p);
97794   UNUSED_PARAMETER(nEq);
97795 #endif
97796   assert( pLower || pUpper );
97797   if( pLower && pUpper ){
97798     *piEst = 11;
97799   }else{
97800     *piEst = 33;
97801   }
97802   return rc;
97803 }
97804
97805
97806 /*
97807 ** Find the query plan for accessing a particular table.  Write the
97808 ** best query plan and its cost into the WhereCost object supplied as the
97809 ** last parameter.
97810 **
97811 ** The lowest cost plan wins.  The cost is an estimate of the amount of
97812 ** CPU and disk I/O need to process the request using the selected plan.
97813 ** Factors that influence cost include:
97814 **
97815 **    *  The estimated number of rows that will be retrieved.  (The
97816 **       fewer the better.)
97817 **
97818 **    *  Whether or not sorting must occur.
97819 **
97820 **    *  Whether or not there must be separate lookups in the
97821 **       index and in the main table.
97822 **
97823 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
97824 ** the SQL statement, then this function only considers plans using the 
97825 ** named index. If no such plan is found, then the returned cost is
97826 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
97827 ** then the cost is calculated in the usual way.
97828 **
97829 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
97830 ** in the SELECT statement, then no indexes are considered. However, the 
97831 ** selected plan may still take advantage of the tables built-in rowid
97832 ** index.
97833 */
97834 static void bestBtreeIndex(
97835   Parse *pParse,              /* The parsing context */
97836   WhereClause *pWC,           /* The WHERE clause */
97837   struct SrcList_item *pSrc,  /* The FROM clause term to search */
97838   Bitmask notReady,           /* Mask of cursors not available for indexing */
97839   Bitmask notValid,           /* Cursors not available for any purpose */
97840   ExprList *pOrderBy,         /* The ORDER BY clause */
97841   WhereCost *pCost            /* Lowest cost query plan */
97842 ){
97843   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
97844   Index *pProbe;              /* An index we are evaluating */
97845   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
97846   int eqTermMask;             /* Current mask of valid equality operators */
97847   int idxEqTermMask;          /* Index mask of valid equality operators */
97848   Index sPk;                  /* A fake index object for the primary key */
97849   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
97850   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
97851   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
97852
97853   /* Initialize the cost to a worst-case value */
97854   memset(pCost, 0, sizeof(*pCost));
97855   pCost->rCost = SQLITE_BIG_DBL;
97856
97857   /* If the pSrc table is the right table of a LEFT JOIN then we may not
97858   ** use an index to satisfy IS NULL constraints on that table.  This is
97859   ** because columns might end up being NULL if the table does not match -
97860   ** a circumstance which the index cannot help us discover.  Ticket #2177.
97861   */
97862   if( pSrc->jointype & JT_LEFT ){
97863     idxEqTermMask = WO_EQ|WO_IN;
97864   }else{
97865     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
97866   }
97867
97868   if( pSrc->pIndex ){
97869     /* An INDEXED BY clause specifies a particular index to use */
97870     pIdx = pProbe = pSrc->pIndex;
97871     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
97872     eqTermMask = idxEqTermMask;
97873   }else{
97874     /* There is no INDEXED BY clause.  Create a fake Index object to
97875     ** represent the primary key */
97876     Index *pFirst;                /* Any other index on the table */
97877     memset(&sPk, 0, sizeof(Index));
97878     sPk.nColumn = 1;
97879     sPk.aiColumn = &aiColumnPk;
97880     sPk.aiRowEst = aiRowEstPk;
97881     sPk.onError = OE_Replace;
97882     sPk.pTable = pSrc->pTab;
97883     aiRowEstPk[0] = pSrc->pTab->nRowEst;
97884     aiRowEstPk[1] = 1;
97885     pFirst = pSrc->pTab->pIndex;
97886     if( pSrc->notIndexed==0 ){
97887       sPk.pNext = pFirst;
97888     }
97889     pProbe = &sPk;
97890     wsFlagMask = ~(
97891         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
97892     );
97893     eqTermMask = WO_EQ|WO_IN;
97894     pIdx = 0;
97895   }
97896
97897   /* Loop over all indices looking for the best one to use
97898   */
97899   for(; pProbe; pIdx=pProbe=pProbe->pNext){
97900     const unsigned int * const aiRowEst = pProbe->aiRowEst;
97901     double cost;                /* Cost of using pProbe */
97902     double nRow;                /* Estimated number of rows in result set */
97903     int rev;                    /* True to scan in reverse order */
97904     int wsFlags = 0;
97905     Bitmask used = 0;
97906
97907     /* The following variables are populated based on the properties of
97908     ** scan being evaluated. They are then used to determine the expected
97909     ** cost and number of rows returned.
97910     **
97911     **  nEq: 
97912     **    Number of equality terms that can be implemented using the index.
97913     **
97914     **  nInMul:  
97915     **    The "in-multiplier". This is an estimate of how many seek operations 
97916     **    SQLite must perform on the index in question. For example, if the 
97917     **    WHERE clause is:
97918     **
97919     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
97920     **
97921     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
97922     **    set to 9. Given the same schema and either of the following WHERE 
97923     **    clauses:
97924     **
97925     **      WHERE a =  1
97926     **      WHERE a >= 2
97927     **
97928     **    nInMul is set to 1.
97929     **
97930     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
97931     **    the sub-select is assumed to return 25 rows for the purposes of 
97932     **    determining nInMul.
97933     **
97934     **  bInEst:  
97935     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
97936     **    in determining the value of nInMul.
97937     **
97938     **  estBound:
97939     **    An estimate on the amount of the table that must be searched.  A
97940     **    value of 100 means the entire table is searched.  Range constraints
97941     **    might reduce this to a value less than 100 to indicate that only
97942     **    a fraction of the table needs searching.  In the absence of
97943     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
97944     **    space to 1/3rd its original size.  So an x>? constraint reduces
97945     **    estBound to 33.  Two constraints (x>? AND x<?) reduce estBound to 11.
97946     **
97947     **  bSort:   
97948     **    Boolean. True if there is an ORDER BY clause that will require an 
97949     **    external sort (i.e. scanning the index being evaluated will not 
97950     **    correctly order records).
97951     **
97952     **  bLookup: 
97953     **    Boolean. True if for each index entry visited a lookup on the 
97954     **    corresponding table b-tree is required. This is always false 
97955     **    for the rowid index. For other indexes, it is true unless all the 
97956     **    columns of the table used by the SELECT statement are present in 
97957     **    the index (such an index is sometimes described as a covering index).
97958     **    For example, given the index on (a, b), the second of the following 
97959     **    two queries requires table b-tree lookups, but the first does not.
97960     **
97961     **             SELECT a, b    FROM tbl WHERE a = 1;
97962     **             SELECT a, b, c FROM tbl WHERE a = 1;
97963     */
97964     int nEq;
97965     int bInEst = 0;
97966     int nInMul = 1;
97967     int estBound = 100;
97968     int nBound = 0;             /* Number of range constraints seen */
97969     int bSort = 0;
97970     int bLookup = 0;
97971     WhereTerm *pTerm;           /* A single term of the WHERE clause */
97972
97973     /* Determine the values of nEq and nInMul */
97974     for(nEq=0; nEq<pProbe->nColumn; nEq++){
97975       int j = pProbe->aiColumn[nEq];
97976       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
97977       if( pTerm==0 ) break;
97978       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
97979       if( pTerm->eOperator & WO_IN ){
97980         Expr *pExpr = pTerm->pExpr;
97981         wsFlags |= WHERE_COLUMN_IN;
97982         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97983           nInMul *= 25;
97984           bInEst = 1;
97985         }else if( ALWAYS(pExpr->x.pList) ){
97986           nInMul *= pExpr->x.pList->nExpr + 1;
97987         }
97988       }else if( pTerm->eOperator & WO_ISNULL ){
97989         wsFlags |= WHERE_COLUMN_NULL;
97990       }
97991       used |= pTerm->prereqRight;
97992     }
97993
97994     /* Determine the value of estBound. */
97995     if( nEq<pProbe->nColumn ){
97996       int j = pProbe->aiColumn[nEq];
97997       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
97998         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
97999         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
98000         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
98001         if( pTop ){
98002           nBound = 1;
98003           wsFlags |= WHERE_TOP_LIMIT;
98004           used |= pTop->prereqRight;
98005         }
98006         if( pBtm ){
98007           nBound++;
98008           wsFlags |= WHERE_BTM_LIMIT;
98009           used |= pBtm->prereqRight;
98010         }
98011         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
98012       }
98013     }else if( pProbe->onError!=OE_None ){
98014       testcase( wsFlags & WHERE_COLUMN_IN );
98015       testcase( wsFlags & WHERE_COLUMN_NULL );
98016       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
98017         wsFlags |= WHERE_UNIQUE;
98018       }
98019     }
98020
98021     /* If there is an ORDER BY clause and the index being considered will
98022     ** naturally scan rows in the required order, set the appropriate flags
98023     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
98024     ** will scan rows in a different order, set the bSort variable.  */
98025     if( pOrderBy ){
98026       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
98027         && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
98028       ){
98029         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
98030         wsFlags |= (rev ? WHERE_REVERSE : 0);
98031       }else{
98032         bSort = 1;
98033       }
98034     }
98035
98036     /* If currently calculating the cost of using an index (not the IPK
98037     ** index), determine if all required column data may be obtained without 
98038     ** using the main table (i.e. if the index is a covering
98039     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
98040     ** wsFlags. Otherwise, set the bLookup variable to true.  */
98041     if( pIdx && wsFlags ){
98042       Bitmask m = pSrc->colUsed;
98043       int j;
98044       for(j=0; j<pIdx->nColumn; j++){
98045         int x = pIdx->aiColumn[j];
98046         if( x<BMS-1 ){
98047           m &= ~(((Bitmask)1)<<x);
98048         }
98049       }
98050       if( m==0 ){
98051         wsFlags |= WHERE_IDX_ONLY;
98052       }else{
98053         bLookup = 1;
98054       }
98055     }
98056
98057     /*
98058     ** Estimate the number of rows of output.  For an IN operator,
98059     ** do not let the estimate exceed half the rows in the table.
98060     */
98061     nRow = (double)(aiRowEst[nEq] * nInMul);
98062     if( bInEst && nRow*2>aiRowEst[0] ){
98063       nRow = aiRowEst[0]/2;
98064       nInMul = (int)(nRow / aiRowEst[nEq]);
98065     }
98066
98067     /* Assume constant cost to access a row and logarithmic cost to
98068     ** do a binary search.  Hence, the initial cost is the number of output
98069     ** rows plus log2(table-size) times the number of binary searches.
98070     */
98071     cost = nRow + nInMul*estLog(aiRowEst[0]);
98072
98073     /* Adjust the number of rows and the cost downward to reflect rows
98074     ** that are excluded by range constraints.
98075     */
98076     nRow = (nRow * (double)estBound) / (double)100;
98077     cost = (cost * (double)estBound) / (double)100;
98078
98079     /* Add in the estimated cost of sorting the result
98080     */
98081     if( bSort ){
98082       cost += cost*estLog(cost);
98083     }
98084
98085     /* If all information can be taken directly from the index, we avoid
98086     ** doing table lookups.  This reduces the cost by half.  (Not really -
98087     ** this needs to be fixed.)
98088     */
98089     if( pIdx && bLookup==0 ){
98090       cost /= (double)2;
98091     }
98092     /**** Cost of using this index has now been computed ****/
98093
98094     /* If there are additional constraints on this table that cannot
98095     ** be used with the current index, but which might lower the number
98096     ** of output rows, adjust the nRow value accordingly.  This only 
98097     ** matters if the current index is the least costly, so do not bother
98098     ** with this step if we already know this index will not be chosen.
98099     ** Also, never reduce the output row count below 2 using this step.
98100     **
98101     ** It is critical that the notValid mask be used here instead of
98102     ** the notReady mask.  When computing an "optimal" index, the notReady
98103     ** mask will only have one bit set - the bit for the current table.
98104     ** The notValid mask, on the other hand, always has all bits set for
98105     ** tables that are not in outer loops.  If notReady is used here instead
98106     ** of notValid, then a optimal index that depends on inner joins loops
98107     ** might be selected even when there exists an optimal index that has
98108     ** no such dependency.
98109     */
98110     if( nRow>2 && cost<=pCost->rCost ){
98111       int k;                       /* Loop counter */
98112       int nSkipEq = nEq;           /* Number of == constraints to skip */
98113       int nSkipRange = nBound;     /* Number of < constraints to skip */
98114       Bitmask thisTab;             /* Bitmap for pSrc */
98115
98116       thisTab = getMask(pWC->pMaskSet, iCur);
98117       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
98118         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
98119         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
98120         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
98121           if( nSkipEq ){
98122             /* Ignore the first nEq equality matches since the index
98123             ** has already accounted for these */
98124             nSkipEq--;
98125           }else{
98126             /* Assume each additional equality match reduces the result
98127             ** set size by a factor of 10 */
98128             nRow /= 10;
98129           }
98130         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
98131           if( nSkipRange ){
98132             /* Ignore the first nBound range constraints since the index
98133             ** has already accounted for these */
98134             nSkipRange--;
98135           }else{
98136             /* Assume each additional range constraint reduces the result
98137             ** set size by a factor of 3 */
98138             nRow /= 3;
98139           }
98140         }else{
98141           /* Any other expression lowers the output row count by half */
98142           nRow /= 2;
98143         }
98144       }
98145       if( nRow<2 ) nRow = 2;
98146     }
98147
98148
98149     WHERETRACE((
98150       "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
98151       "         notReady=0x%llx nRow=%.2f cost=%.2f used=0x%llx\n",
98152       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
98153       nEq, nInMul, estBound, bSort, bLookup, wsFlags,
98154       notReady, nRow, cost, used
98155     ));
98156
98157     /* If this index is the best we have seen so far, then record this
98158     ** index and its cost in the pCost structure.
98159     */
98160     if( (!pIdx || wsFlags)
98161      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
98162     ){
98163       pCost->rCost = cost;
98164       pCost->used = used;
98165       pCost->plan.nRow = nRow;
98166       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
98167       pCost->plan.nEq = nEq;
98168       pCost->plan.u.pIdx = pIdx;
98169     }
98170
98171     /* If there was an INDEXED BY clause, then only that one index is
98172     ** considered. */
98173     if( pSrc->pIndex ) break;
98174
98175     /* Reset masks for the next index in the loop */
98176     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
98177     eqTermMask = idxEqTermMask;
98178   }
98179
98180   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
98181   ** is set, then reverse the order that the index will be scanned
98182   ** in. This is used for application testing, to help find cases
98183   ** where application behaviour depends on the (undefined) order that
98184   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
98185   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
98186     pCost->plan.wsFlags |= WHERE_REVERSE;
98187   }
98188
98189   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
98190   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
98191   assert( pSrc->pIndex==0 
98192        || pCost->plan.u.pIdx==0 
98193        || pCost->plan.u.pIdx==pSrc->pIndex 
98194   );
98195
98196   WHERETRACE(("best index is: %s\n", 
98197     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" : 
98198          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
98199   ));
98200   
98201   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
98202   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
98203   pCost->plan.wsFlags |= eqTermMask;
98204 }
98205
98206 /*
98207 ** Find the query plan for accessing table pSrc->pTab. Write the
98208 ** best query plan and its cost into the WhereCost object supplied 
98209 ** as the last parameter. This function may calculate the cost of
98210 ** both real and virtual table scans.
98211 */
98212 static void bestIndex(
98213   Parse *pParse,              /* The parsing context */
98214   WhereClause *pWC,           /* The WHERE clause */
98215   struct SrcList_item *pSrc,  /* The FROM clause term to search */
98216   Bitmask notReady,           /* Mask of cursors not available for indexing */
98217   Bitmask notValid,           /* Cursors not available for any purpose */
98218   ExprList *pOrderBy,         /* The ORDER BY clause */
98219   WhereCost *pCost            /* Lowest cost query plan */
98220 ){
98221 #ifndef SQLITE_OMIT_VIRTUALTABLE
98222   if( IsVirtual(pSrc->pTab) ){
98223     sqlite3_index_info *p = 0;
98224     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
98225     if( p->needToFreeIdxStr ){
98226       sqlite3_free(p->idxStr);
98227     }
98228     sqlite3DbFree(pParse->db, p);
98229   }else
98230 #endif
98231   {
98232     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
98233   }
98234 }
98235
98236 /*
98237 ** Disable a term in the WHERE clause.  Except, do not disable the term
98238 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
98239 ** or USING clause of that join.
98240 **
98241 ** Consider the term t2.z='ok' in the following queries:
98242 **
98243 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
98244 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
98245 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
98246 **
98247 ** The t2.z='ok' is disabled in the in (2) because it originates
98248 ** in the ON clause.  The term is disabled in (3) because it is not part
98249 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
98250 **
98251 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
98252 ** completely satisfied by indices.
98253 **
98254 ** Disabling a term causes that term to not be tested in the inner loop
98255 ** of the join.  Disabling is an optimization.  When terms are satisfied
98256 ** by indices, we disable them to prevent redundant tests in the inner
98257 ** loop.  We would get the correct results if nothing were ever disabled,
98258 ** but joins might run a little slower.  The trick is to disable as much
98259 ** as we can without disabling too much.  If we disabled in (1), we'd get
98260 ** the wrong answer.  See ticket #813.
98261 */
98262 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
98263   if( pTerm
98264       && (pTerm->wtFlags & TERM_CODED)==0
98265       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
98266   ){
98267     pTerm->wtFlags |= TERM_CODED;
98268     if( pTerm->iParent>=0 ){
98269       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
98270       if( (--pOther->nChild)==0 ){
98271         disableTerm(pLevel, pOther);
98272       }
98273     }
98274   }
98275 }
98276
98277 /*
98278 ** Code an OP_Affinity opcode to apply the column affinity string zAff
98279 ** to the n registers starting at base. 
98280 **
98281 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
98282 ** beginning and end of zAff are ignored.  If all entries in zAff are
98283 ** SQLITE_AFF_NONE, then no code gets generated.
98284 **
98285 ** This routine makes its own copy of zAff so that the caller is free
98286 ** to modify zAff after this routine returns.
98287 */
98288 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
98289   Vdbe *v = pParse->pVdbe;
98290   if( zAff==0 ){
98291     assert( pParse->db->mallocFailed );
98292     return;
98293   }
98294   assert( v!=0 );
98295
98296   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
98297   ** and end of the affinity string.
98298   */
98299   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
98300     n--;
98301     base++;
98302     zAff++;
98303   }
98304   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
98305     n--;
98306   }
98307
98308   /* Code the OP_Affinity opcode if there is anything left to do. */
98309   if( n>0 ){
98310     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
98311     sqlite3VdbeChangeP4(v, -1, zAff, n);
98312     sqlite3ExprCacheAffinityChange(pParse, base, n);
98313   }
98314 }
98315
98316
98317 /*
98318 ** Generate code for a single equality term of the WHERE clause.  An equality
98319 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
98320 ** coded.
98321 **
98322 ** The current value for the constraint is left in register iReg.
98323 **
98324 ** For a constraint of the form X=expr, the expression is evaluated and its
98325 ** result is left on the stack.  For constraints of the form X IN (...)
98326 ** this routine sets up a loop that will iterate over all values of X.
98327 */
98328 static int codeEqualityTerm(
98329   Parse *pParse,      /* The parsing context */
98330   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
98331   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
98332   int iTarget         /* Attempt to leave results in this register */
98333 ){
98334   Expr *pX = pTerm->pExpr;
98335   Vdbe *v = pParse->pVdbe;
98336   int iReg;                  /* Register holding results */
98337
98338   assert( iTarget>0 );
98339   if( pX->op==TK_EQ ){
98340     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
98341   }else if( pX->op==TK_ISNULL ){
98342     iReg = iTarget;
98343     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
98344 #ifndef SQLITE_OMIT_SUBQUERY
98345   }else{
98346     int eType;
98347     int iTab;
98348     struct InLoop *pIn;
98349
98350     assert( pX->op==TK_IN );
98351     iReg = iTarget;
98352     eType = sqlite3FindInIndex(pParse, pX, 0);
98353     iTab = pX->iTable;
98354     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
98355     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
98356     if( pLevel->u.in.nIn==0 ){
98357       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
98358     }
98359     pLevel->u.in.nIn++;
98360     pLevel->u.in.aInLoop =
98361        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
98362                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
98363     pIn = pLevel->u.in.aInLoop;
98364     if( pIn ){
98365       pIn += pLevel->u.in.nIn - 1;
98366       pIn->iCur = iTab;
98367       if( eType==IN_INDEX_ROWID ){
98368         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
98369       }else{
98370         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
98371       }
98372       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
98373     }else{
98374       pLevel->u.in.nIn = 0;
98375     }
98376 #endif
98377   }
98378   disableTerm(pLevel, pTerm);
98379   return iReg;
98380 }
98381
98382 /*
98383 ** Generate code that will evaluate all == and IN constraints for an
98384 ** index.
98385 **
98386 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
98387 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
98388 ** The index has as many as three equality constraints, but in this
98389 ** example, the third "c" value is an inequality.  So only two 
98390 ** constraints are coded.  This routine will generate code to evaluate
98391 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
98392 ** in consecutive registers and the index of the first register is returned.
98393 **
98394 ** In the example above nEq==2.  But this subroutine works for any value
98395 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
98396 ** The only thing it does is allocate the pLevel->iMem memory cell and
98397 ** compute the affinity string.
98398 **
98399 ** This routine always allocates at least one memory cell and returns
98400 ** the index of that memory cell. The code that
98401 ** calls this routine will use that memory cell to store the termination
98402 ** key value of the loop.  If one or more IN operators appear, then
98403 ** this routine allocates an additional nEq memory cells for internal
98404 ** use.
98405 **
98406 ** Before returning, *pzAff is set to point to a buffer containing a
98407 ** copy of the column affinity string of the index allocated using
98408 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
98409 ** with equality constraints that use NONE affinity are set to
98410 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
98411 **
98412 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
98413 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
98414 **
98415 ** In the example above, the index on t1(a) has TEXT affinity. But since
98416 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
98417 ** no conversion should be attempted before using a t2.b value as part of
98418 ** a key to search the index. Hence the first byte in the returned affinity
98419 ** string in this example would be set to SQLITE_AFF_NONE.
98420 */
98421 static int codeAllEqualityTerms(
98422   Parse *pParse,        /* Parsing context */
98423   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
98424   WhereClause *pWC,     /* The WHERE clause */
98425   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
98426   int nExtraReg,        /* Number of extra registers to allocate */
98427   char **pzAff          /* OUT: Set to point to affinity string */
98428 ){
98429   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
98430   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
98431   Index *pIdx;                  /* The index being used for this loop */
98432   int iCur = pLevel->iTabCur;   /* The cursor of the table */
98433   WhereTerm *pTerm;             /* A single constraint term */
98434   int j;                        /* Loop counter */
98435   int regBase;                  /* Base register */
98436   int nReg;                     /* Number of registers to allocate */
98437   char *zAff;                   /* Affinity string to return */
98438
98439   /* This module is only called on query plans that use an index. */
98440   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
98441   pIdx = pLevel->plan.u.pIdx;
98442
98443   /* Figure out how many memory cells we will need then allocate them.
98444   */
98445   regBase = pParse->nMem + 1;
98446   nReg = pLevel->plan.nEq + nExtraReg;
98447   pParse->nMem += nReg;
98448
98449   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
98450   if( !zAff ){
98451     pParse->db->mallocFailed = 1;
98452   }
98453
98454   /* Evaluate the equality constraints
98455   */
98456   assert( pIdx->nColumn>=nEq );
98457   for(j=0; j<nEq; j++){
98458     int r1;
98459     int k = pIdx->aiColumn[j];
98460     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
98461     if( NEVER(pTerm==0) ) break;
98462     /* The following true for indices with redundant columns. 
98463     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
98464     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
98465     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98466     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
98467     if( r1!=regBase+j ){
98468       if( nReg==1 ){
98469         sqlite3ReleaseTempReg(pParse, regBase);
98470         regBase = r1;
98471       }else{
98472         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
98473       }
98474     }
98475     testcase( pTerm->eOperator & WO_ISNULL );
98476     testcase( pTerm->eOperator & WO_IN );
98477     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
98478       Expr *pRight = pTerm->pExpr->pRight;
98479       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
98480       if( zAff ){
98481         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
98482           zAff[j] = SQLITE_AFF_NONE;
98483         }
98484         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
98485           zAff[j] = SQLITE_AFF_NONE;
98486         }
98487       }
98488     }
98489   }
98490   *pzAff = zAff;
98491   return regBase;
98492 }
98493
98494 #ifndef SQLITE_OMIT_EXPLAIN
98495 /*
98496 ** This routine is a helper for explainIndexRange() below
98497 **
98498 ** pStr holds the text of an expression that we are building up one term
98499 ** at a time.  This routine adds a new term to the end of the expression.
98500 ** Terms are separated by AND so add the "AND" text for second and subsequent
98501 ** terms only.
98502 */
98503 static void explainAppendTerm(
98504   StrAccum *pStr,             /* The text expression being built */
98505   int iTerm,                  /* Index of this term.  First is zero */
98506   const char *zColumn,        /* Name of the column */
98507   const char *zOp             /* Name of the operator */
98508 ){
98509   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
98510   sqlite3StrAccumAppend(pStr, zColumn, -1);
98511   sqlite3StrAccumAppend(pStr, zOp, 1);
98512   sqlite3StrAccumAppend(pStr, "?", 1);
98513 }
98514
98515 /*
98516 ** Argument pLevel describes a strategy for scanning table pTab. This 
98517 ** function returns a pointer to a string buffer containing a description
98518 ** of the subset of table rows scanned by the strategy in the form of an
98519 ** SQL expression. Or, if all rows are scanned, NULL is returned.
98520 **
98521 ** For example, if the query:
98522 **
98523 **   SELECT * FROM t1 WHERE a=1 AND b>2;
98524 **
98525 ** is run and there is an index on (a, b), then this function returns a
98526 ** string similar to:
98527 **
98528 **   "a=? AND b>?"
98529 **
98530 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
98531 ** It is the responsibility of the caller to free the buffer when it is
98532 ** no longer required.
98533 */
98534 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
98535   WherePlan *pPlan = &pLevel->plan;
98536   Index *pIndex = pPlan->u.pIdx;
98537   int nEq = pPlan->nEq;
98538   int i, j;
98539   Column *aCol = pTab->aCol;
98540   int *aiColumn = pIndex->aiColumn;
98541   StrAccum txt;
98542
98543   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
98544     return 0;
98545   }
98546   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
98547   txt.db = db;
98548   sqlite3StrAccumAppend(&txt, " (", 2);
98549   for(i=0; i<nEq; i++){
98550     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
98551   }
98552
98553   j = i;
98554   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
98555     explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
98556   }
98557   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
98558     explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
98559   }
98560   sqlite3StrAccumAppend(&txt, ")", 1);
98561   return sqlite3StrAccumFinish(&txt);
98562 }
98563
98564 /*
98565 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
98566 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
98567 ** record is added to the output to describe the table scan strategy in 
98568 ** pLevel.
98569 */
98570 static void explainOneScan(
98571   Parse *pParse,                  /* Parse context */
98572   SrcList *pTabList,              /* Table list this loop refers to */
98573   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
98574   int iLevel,                     /* Value for "level" column of output */
98575   int iFrom,                      /* Value for "from" column of output */
98576   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
98577 ){
98578   if( pParse->explain==2 ){
98579     u32 flags = pLevel->plan.wsFlags;
98580     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
98581     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
98582     sqlite3 *db = pParse->db;     /* Database handle */
98583     char *zMsg;                   /* Text to add to EQP output */
98584     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
98585     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
98586     int isSearch;                 /* True for a SEARCH. False for SCAN. */
98587
98588     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
98589
98590     isSearch = (pLevel->plan.nEq>0)
98591              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
98592              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
98593
98594     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
98595     if( pItem->pSelect ){
98596       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
98597     }else{
98598       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
98599     }
98600
98601     if( pItem->zAlias ){
98602       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
98603     }
98604     if( (flags & WHERE_INDEXED)!=0 ){
98605       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
98606       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
98607           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
98608           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
98609           ((flags & WHERE_TEMP_INDEX)?"":" "),
98610           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
98611           zWhere
98612       );
98613       sqlite3DbFree(db, zWhere);
98614     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
98615       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
98616
98617       if( flags&WHERE_ROWID_EQ ){
98618         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
98619       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
98620         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
98621       }else if( flags&WHERE_BTM_LIMIT ){
98622         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
98623       }else if( flags&WHERE_TOP_LIMIT ){
98624         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
98625       }
98626     }
98627 #ifndef SQLITE_OMIT_VIRTUALTABLE
98628     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
98629       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
98630       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
98631                   pVtabIdx->idxNum, pVtabIdx->idxStr);
98632     }
98633 #endif
98634     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
98635       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
98636       nRow = 1;
98637     }else{
98638       nRow = (sqlite3_int64)pLevel->plan.nRow;
98639     }
98640     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
98641     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
98642   }
98643 }
98644 #else
98645 # define explainOneScan(u,v,w,x,y,z)
98646 #endif /* SQLITE_OMIT_EXPLAIN */
98647
98648
98649 /*
98650 ** Generate code for the start of the iLevel-th loop in the WHERE clause
98651 ** implementation described by pWInfo.
98652 */
98653 static Bitmask codeOneLoopStart(
98654   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
98655   int iLevel,          /* Which level of pWInfo->a[] should be coded */
98656   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
98657   Bitmask notReady     /* Which tables are currently available */
98658 ){
98659   int j, k;            /* Loop counters */
98660   int iCur;            /* The VDBE cursor for the table */
98661   int addrNxt;         /* Where to jump to continue with the next IN case */
98662   int omitTable;       /* True if we use the index only */
98663   int bRev;            /* True if we need to scan in reverse order */
98664   WhereLevel *pLevel;  /* The where level to be coded */
98665   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
98666   WhereTerm *pTerm;               /* A WHERE clause term */
98667   Parse *pParse;                  /* Parsing context */
98668   Vdbe *v;                        /* The prepared stmt under constructions */
98669   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
98670   int addrBrk;                    /* Jump here to break out of the loop */
98671   int addrCont;                   /* Jump here to continue with next cycle */
98672   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
98673   int iReleaseReg = 0;      /* Temp register to free before returning */
98674
98675   pParse = pWInfo->pParse;
98676   v = pParse->pVdbe;
98677   pWC = pWInfo->pWC;
98678   pLevel = &pWInfo->a[iLevel];
98679   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
98680   iCur = pTabItem->iCursor;
98681   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
98682   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
98683            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
98684
98685   /* Create labels for the "break" and "continue" instructions
98686   ** for the current loop.  Jump to addrBrk to break out of a loop.
98687   ** Jump to cont to go immediately to the next iteration of the
98688   ** loop.
98689   **
98690   ** When there is an IN operator, we also have a "addrNxt" label that
98691   ** means to continue with the next IN value combination.  When
98692   ** there are no IN operators in the constraints, the "addrNxt" label
98693   ** is the same as "addrBrk".
98694   */
98695   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
98696   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
98697
98698   /* If this is the right table of a LEFT OUTER JOIN, allocate and
98699   ** initialize a memory cell that records if this table matches any
98700   ** row of the left table of the join.
98701   */
98702   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
98703     pLevel->iLeftJoin = ++pParse->nMem;
98704     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
98705     VdbeComment((v, "init LEFT JOIN no-match flag"));
98706   }
98707
98708 #ifndef SQLITE_OMIT_VIRTUALTABLE
98709   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
98710     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
98711     **          to access the data.
98712     */
98713     int iReg;   /* P3 Value for OP_VFilter */
98714     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
98715     int nConstraint = pVtabIdx->nConstraint;
98716     struct sqlite3_index_constraint_usage *aUsage =
98717                                                 pVtabIdx->aConstraintUsage;
98718     const struct sqlite3_index_constraint *aConstraint =
98719                                                 pVtabIdx->aConstraint;
98720
98721     sqlite3ExprCachePush(pParse);
98722     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
98723     for(j=1; j<=nConstraint; j++){
98724       for(k=0; k<nConstraint; k++){
98725         if( aUsage[k].argvIndex==j ){
98726           int iTerm = aConstraint[k].iTermOffset;
98727           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
98728           break;
98729         }
98730       }
98731       if( k==nConstraint ) break;
98732     }
98733     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
98734     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
98735     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
98736                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
98737     pVtabIdx->needToFreeIdxStr = 0;
98738     for(j=0; j<nConstraint; j++){
98739       if( aUsage[j].omit ){
98740         int iTerm = aConstraint[j].iTermOffset;
98741         disableTerm(pLevel, &pWC->a[iTerm]);
98742       }
98743     }
98744     pLevel->op = OP_VNext;
98745     pLevel->p1 = iCur;
98746     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
98747     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
98748     sqlite3ExprCachePop(pParse, 1);
98749   }else
98750 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98751
98752   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
98753     /* Case 1:  We can directly reference a single row using an
98754     **          equality comparison against the ROWID field.  Or
98755     **          we reference multiple rows using a "rowid IN (...)"
98756     **          construct.
98757     */
98758     iReleaseReg = sqlite3GetTempReg(pParse);
98759     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
98760     assert( pTerm!=0 );
98761     assert( pTerm->pExpr!=0 );
98762     assert( pTerm->leftCursor==iCur );
98763     assert( omitTable==0 );
98764     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98765     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
98766     addrNxt = pLevel->addrNxt;
98767     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
98768     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
98769     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
98770     VdbeComment((v, "pk"));
98771     pLevel->op = OP_Noop;
98772   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
98773     /* Case 2:  We have an inequality comparison against the ROWID field.
98774     */
98775     int testOp = OP_Noop;
98776     int start;
98777     int memEndValue = 0;
98778     WhereTerm *pStart, *pEnd;
98779
98780     assert( omitTable==0 );
98781     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
98782     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
98783     if( bRev ){
98784       pTerm = pStart;
98785       pStart = pEnd;
98786       pEnd = pTerm;
98787     }
98788     if( pStart ){
98789       Expr *pX;             /* The expression that defines the start bound */
98790       int r1, rTemp;        /* Registers for holding the start boundary */
98791
98792       /* The following constant maps TK_xx codes into corresponding 
98793       ** seek opcodes.  It depends on a particular ordering of TK_xx
98794       */
98795       const u8 aMoveOp[] = {
98796            /* TK_GT */  OP_SeekGt,
98797            /* TK_LE */  OP_SeekLe,
98798            /* TK_LT */  OP_SeekLt,
98799            /* TK_GE */  OP_SeekGe
98800       };
98801       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
98802       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
98803       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
98804
98805       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98806       pX = pStart->pExpr;
98807       assert( pX!=0 );
98808       assert( pStart->leftCursor==iCur );
98809       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
98810       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
98811       VdbeComment((v, "pk"));
98812       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
98813       sqlite3ReleaseTempReg(pParse, rTemp);
98814       disableTerm(pLevel, pStart);
98815     }else{
98816       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
98817     }
98818     if( pEnd ){
98819       Expr *pX;
98820       pX = pEnd->pExpr;
98821       assert( pX!=0 );
98822       assert( pEnd->leftCursor==iCur );
98823       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98824       memEndValue = ++pParse->nMem;
98825       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
98826       if( pX->op==TK_LT || pX->op==TK_GT ){
98827         testOp = bRev ? OP_Le : OP_Ge;
98828       }else{
98829         testOp = bRev ? OP_Lt : OP_Gt;
98830       }
98831       disableTerm(pLevel, pEnd);
98832     }
98833     start = sqlite3VdbeCurrentAddr(v);
98834     pLevel->op = bRev ? OP_Prev : OP_Next;
98835     pLevel->p1 = iCur;
98836     pLevel->p2 = start;
98837     if( pStart==0 && pEnd==0 ){
98838       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
98839     }else{
98840       assert( pLevel->p5==0 );
98841     }
98842     if( testOp!=OP_Noop ){
98843       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
98844       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
98845       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
98846       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
98847       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
98848     }
98849   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
98850     /* Case 3: A scan using an index.
98851     **
98852     **         The WHERE clause may contain zero or more equality 
98853     **         terms ("==" or "IN" operators) that refer to the N
98854     **         left-most columns of the index. It may also contain
98855     **         inequality constraints (>, <, >= or <=) on the indexed
98856     **         column that immediately follows the N equalities. Only 
98857     **         the right-most column can be an inequality - the rest must
98858     **         use the "==" and "IN" operators. For example, if the 
98859     **         index is on (x,y,z), then the following clauses are all 
98860     **         optimized:
98861     **
98862     **            x=5
98863     **            x=5 AND y=10
98864     **            x=5 AND y<10
98865     **            x=5 AND y>5 AND y<10
98866     **            x=5 AND y=5 AND z<=10
98867     **
98868     **         The z<10 term of the following cannot be used, only
98869     **         the x=5 term:
98870     **
98871     **            x=5 AND z<10
98872     **
98873     **         N may be zero if there are inequality constraints.
98874     **         If there are no inequality constraints, then N is at
98875     **         least one.
98876     **
98877     **         This case is also used when there are no WHERE clause
98878     **         constraints but an index is selected anyway, in order
98879     **         to force the output order to conform to an ORDER BY.
98880     */  
98881     static const u8 aStartOp[] = {
98882       0,
98883       0,
98884       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
98885       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
98886       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
98887       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
98888       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
98889       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
98890     };
98891     static const u8 aEndOp[] = {
98892       OP_Noop,             /* 0: (!end_constraints) */
98893       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
98894       OP_IdxLT             /* 2: (end_constraints && bRev) */
98895     };
98896     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
98897     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
98898     int regBase;                 /* Base register holding constraint values */
98899     int r1;                      /* Temp register */
98900     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
98901     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
98902     int startEq;                 /* True if range start uses ==, >= or <= */
98903     int endEq;                   /* True if range end uses ==, >= or <= */
98904     int start_constraints;       /* Start of range is constrained */
98905     int nConstraint;             /* Number of constraint terms */
98906     Index *pIdx;                 /* The index we will be using */
98907     int iIdxCur;                 /* The VDBE cursor for the index */
98908     int nExtraReg = 0;           /* Number of extra registers needed */
98909     int op;                      /* Instruction opcode */
98910     char *zStartAff;             /* Affinity for start of range constraint */
98911     char *zEndAff;               /* Affinity for end of range constraint */
98912
98913     pIdx = pLevel->plan.u.pIdx;
98914     iIdxCur = pLevel->iIdxCur;
98915     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
98916
98917     /* If this loop satisfies a sort order (pOrderBy) request that 
98918     ** was passed to this function to implement a "SELECT min(x) ..." 
98919     ** query, then the caller will only allow the loop to run for
98920     ** a single iteration. This means that the first row returned
98921     ** should not have a NULL value stored in 'x'. If column 'x' is
98922     ** the first one after the nEq equality constraints in the index,
98923     ** this requires some special handling.
98924     */
98925     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
98926      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
98927      && (pIdx->nColumn>nEq)
98928     ){
98929       /* assert( pOrderBy->nExpr==1 ); */
98930       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
98931       isMinQuery = 1;
98932       nExtraReg = 1;
98933     }
98934
98935     /* Find any inequality constraint terms for the start and end 
98936     ** of the range. 
98937     */
98938     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
98939       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
98940       nExtraReg = 1;
98941     }
98942     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
98943       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
98944       nExtraReg = 1;
98945     }
98946
98947     /* Generate code to evaluate all constraint terms using == or IN
98948     ** and store the values of those terms in an array of registers
98949     ** starting at regBase.
98950     */
98951     regBase = codeAllEqualityTerms(
98952         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
98953     );
98954     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
98955     addrNxt = pLevel->addrNxt;
98956
98957     /* If we are doing a reverse order scan on an ascending index, or
98958     ** a forward order scan on a descending index, interchange the 
98959     ** start and end terms (pRangeStart and pRangeEnd).
98960     */
98961     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
98962       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
98963     }
98964
98965     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
98966     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
98967     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
98968     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
98969     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
98970     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
98971     start_constraints = pRangeStart || nEq>0;
98972
98973     /* Seek the index cursor to the start of the range. */
98974     nConstraint = nEq;
98975     if( pRangeStart ){
98976       Expr *pRight = pRangeStart->pExpr->pRight;
98977       sqlite3ExprCode(pParse, pRight, regBase+nEq);
98978       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
98979       if( zStartAff ){
98980         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
98981           /* Since the comparison is to be performed with no conversions
98982           ** applied to the operands, set the affinity to apply to pRight to 
98983           ** SQLITE_AFF_NONE.  */
98984           zStartAff[nEq] = SQLITE_AFF_NONE;
98985         }
98986         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
98987           zStartAff[nEq] = SQLITE_AFF_NONE;
98988         }
98989       }  
98990       nConstraint++;
98991       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
98992     }else if( isMinQuery ){
98993       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
98994       nConstraint++;
98995       startEq = 0;
98996       start_constraints = 1;
98997     }
98998     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
98999     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
99000     assert( op!=0 );
99001     testcase( op==OP_Rewind );
99002     testcase( op==OP_Last );
99003     testcase( op==OP_SeekGt );
99004     testcase( op==OP_SeekGe );
99005     testcase( op==OP_SeekLe );
99006     testcase( op==OP_SeekLt );
99007     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
99008
99009     /* Load the value for the inequality constraint at the end of the
99010     ** range (if any).
99011     */
99012     nConstraint = nEq;
99013     if( pRangeEnd ){
99014       Expr *pRight = pRangeEnd->pExpr->pRight;
99015       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
99016       sqlite3ExprCode(pParse, pRight, regBase+nEq);
99017       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
99018       if( zEndAff ){
99019         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
99020           /* Since the comparison is to be performed with no conversions
99021           ** applied to the operands, set the affinity to apply to pRight to 
99022           ** SQLITE_AFF_NONE.  */
99023           zEndAff[nEq] = SQLITE_AFF_NONE;
99024         }
99025         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
99026           zEndAff[nEq] = SQLITE_AFF_NONE;
99027         }
99028       }  
99029       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
99030       nConstraint++;
99031       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
99032     }
99033     sqlite3DbFree(pParse->db, zStartAff);
99034     sqlite3DbFree(pParse->db, zEndAff);
99035
99036     /* Top of the loop body */
99037     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
99038
99039     /* Check if the index cursor is past the end of the range. */
99040     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
99041     testcase( op==OP_Noop );
99042     testcase( op==OP_IdxGE );
99043     testcase( op==OP_IdxLT );
99044     if( op!=OP_Noop ){
99045       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
99046       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
99047     }
99048
99049     /* If there are inequality constraints, check that the value
99050     ** of the table column that the inequality contrains is not NULL.
99051     ** If it is, jump to the next iteration of the loop.
99052     */
99053     r1 = sqlite3GetTempReg(pParse);
99054     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
99055     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
99056     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
99057       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
99058       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
99059     }
99060     sqlite3ReleaseTempReg(pParse, r1);
99061
99062     /* Seek the table cursor, if required */
99063     disableTerm(pLevel, pRangeStart);
99064     disableTerm(pLevel, pRangeEnd);
99065     if( !omitTable ){
99066       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
99067       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
99068       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
99069       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
99070     }
99071
99072     /* Record the instruction used to terminate the loop. Disable 
99073     ** WHERE clause terms made redundant by the index range scan.
99074     */
99075     pLevel->op = bRev ? OP_Prev : OP_Next;
99076     pLevel->p1 = iIdxCur;
99077   }else
99078
99079 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
99080   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
99081     /* Case 4:  Two or more separately indexed terms connected by OR
99082     **
99083     ** Example:
99084     **
99085     **   CREATE TABLE t1(a,b,c,d);
99086     **   CREATE INDEX i1 ON t1(a);
99087     **   CREATE INDEX i2 ON t1(b);
99088     **   CREATE INDEX i3 ON t1(c);
99089     **
99090     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
99091     **
99092     ** In the example, there are three indexed terms connected by OR.
99093     ** The top of the loop looks like this:
99094     **
99095     **          Null       1                # Zero the rowset in reg 1
99096     **
99097     ** Then, for each indexed term, the following. The arguments to
99098     ** RowSetTest are such that the rowid of the current row is inserted
99099     ** into the RowSet. If it is already present, control skips the
99100     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
99101     **
99102     **        sqlite3WhereBegin(<term>)
99103     **          RowSetTest                  # Insert rowid into rowset
99104     **          Gosub      2 A
99105     **        sqlite3WhereEnd()
99106     **
99107     ** Following the above, code to terminate the loop. Label A, the target
99108     ** of the Gosub above, jumps to the instruction right after the Goto.
99109     **
99110     **          Null       1                # Zero the rowset in reg 1
99111     **          Goto       B                # The loop is finished.
99112     **
99113     **       A: <loop body>                 # Return data, whatever.
99114     **
99115     **          Return     2                # Jump back to the Gosub
99116     **
99117     **       B: <after the loop>
99118     **
99119     */
99120     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
99121     WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
99122     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
99123
99124     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
99125     int regRowset = 0;                        /* Register for RowSet object */
99126     int regRowid = 0;                         /* Register holding rowid */
99127     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
99128     int iRetInit;                             /* Address of regReturn init */
99129     int untestedTerms = 0;             /* Some terms not completely tested */
99130     int ii;
99131    
99132     pTerm = pLevel->plan.u.pTerm;
99133     assert( pTerm!=0 );
99134     assert( pTerm->eOperator==WO_OR );
99135     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
99136     pOrWc = &pTerm->u.pOrInfo->wc;
99137     pFinal = &pOrWc->a[pOrWc->nTerm-1];
99138     pLevel->op = OP_Return;
99139     pLevel->p1 = regReturn;
99140
99141     /* Set up a new SrcList ni pOrTab containing the table being scanned
99142     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
99143     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
99144     */
99145     if( pWInfo->nLevel>1 ){
99146       int nNotReady;                 /* The number of notReady tables */
99147       struct SrcList_item *origSrc;     /* Original list of tables */
99148       nNotReady = pWInfo->nLevel - iLevel - 1;
99149       pOrTab = sqlite3StackAllocRaw(pParse->db,
99150                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
99151       if( pOrTab==0 ) return notReady;
99152       pOrTab->nAlloc = (i16)(nNotReady + 1);
99153       pOrTab->nSrc = pOrTab->nAlloc;
99154       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
99155       origSrc = pWInfo->pTabList->a;
99156       for(k=1; k<=nNotReady; k++){
99157         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
99158       }
99159     }else{
99160       pOrTab = pWInfo->pTabList;
99161     }
99162
99163     /* Initialize the rowset register to contain NULL. An SQL NULL is 
99164     ** equivalent to an empty rowset.
99165     **
99166     ** Also initialize regReturn to contain the address of the instruction 
99167     ** immediately following the OP_Return at the bottom of the loop. This
99168     ** is required in a few obscure LEFT JOIN cases where control jumps
99169     ** over the top of the loop into the body of it. In this case the 
99170     ** correct response for the end-of-loop code (the OP_Return) is to 
99171     ** fall through to the next instruction, just as an OP_Next does if
99172     ** called on an uninitialized cursor.
99173     */
99174     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
99175       regRowset = ++pParse->nMem;
99176       regRowid = ++pParse->nMem;
99177       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
99178     }
99179     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
99180
99181     for(ii=0; ii<pOrWc->nTerm; ii++){
99182       WhereTerm *pOrTerm = &pOrWc->a[ii];
99183       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
99184         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
99185         /* Loop through table entries that match term pOrTerm. */
99186         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
99187                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
99188                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
99189         if( pSubWInfo ){
99190           explainOneScan(
99191               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
99192           );
99193           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
99194             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
99195             int r;
99196             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
99197                                          regRowid);
99198             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
99199                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
99200           }
99201           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
99202
99203           /* The pSubWInfo->untestedTerms flag means that this OR term
99204           ** contained one or more AND term from a notReady table.  The
99205           ** terms from the notReady table could not be tested and will
99206           ** need to be tested later.
99207           */
99208           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
99209
99210           /* Finish the loop through table entries that match term pOrTerm. */
99211           sqlite3WhereEnd(pSubWInfo);
99212         }
99213       }
99214     }
99215     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
99216     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
99217     sqlite3VdbeResolveLabel(v, iLoopBody);
99218
99219     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
99220     if( !untestedTerms ) disableTerm(pLevel, pTerm);
99221   }else
99222 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
99223
99224   {
99225     /* Case 5:  There is no usable index.  We must do a complete
99226     **          scan of the entire table.
99227     */
99228     static const u8 aStep[] = { OP_Next, OP_Prev };
99229     static const u8 aStart[] = { OP_Rewind, OP_Last };
99230     assert( bRev==0 || bRev==1 );
99231     assert( omitTable==0 );
99232     pLevel->op = aStep[bRev];
99233     pLevel->p1 = iCur;
99234     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
99235     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
99236   }
99237   notReady &= ~getMask(pWC->pMaskSet, iCur);
99238
99239   /* Insert code to test every subexpression that can be completely
99240   ** computed using the current set of tables.
99241   **
99242   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
99243   ** the use of indices become tests that are evaluated against each row of
99244   ** the relevant input tables.
99245   */
99246   k = 0;
99247   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
99248     Expr *pE;
99249     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
99250     testcase( pTerm->wtFlags & TERM_CODED );
99251     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
99252     if( (pTerm->prereqAll & notReady)!=0 ){
99253       testcase( pWInfo->untestedTerms==0
99254                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
99255       pWInfo->untestedTerms = 1;
99256       continue;
99257     }
99258     pE = pTerm->pExpr;
99259     assert( pE!=0 );
99260     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
99261       continue;
99262     }
99263     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
99264     k = 1;
99265     pTerm->wtFlags |= TERM_CODED;
99266   }
99267
99268   /* For a LEFT OUTER JOIN, generate code that will record the fact that
99269   ** at least one row of the right table has matched the left table.  
99270   */
99271   if( pLevel->iLeftJoin ){
99272     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
99273     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
99274     VdbeComment((v, "record LEFT JOIN hit"));
99275     sqlite3ExprCacheClear(pParse);
99276     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
99277       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
99278       testcase( pTerm->wtFlags & TERM_CODED );
99279       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
99280       if( (pTerm->prereqAll & notReady)!=0 ){
99281         assert( pWInfo->untestedTerms );
99282         continue;
99283       }
99284       assert( pTerm->pExpr );
99285       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
99286       pTerm->wtFlags |= TERM_CODED;
99287     }
99288   }
99289   sqlite3ReleaseTempReg(pParse, iReleaseReg);
99290
99291   return notReady;
99292 }
99293
99294 #if defined(SQLITE_TEST)
99295 /*
99296 ** The following variable holds a text description of query plan generated
99297 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
99298 ** overwrites the previous.  This information is used for testing and
99299 ** analysis only.
99300 */
99301 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
99302 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
99303
99304 #endif /* SQLITE_TEST */
99305
99306
99307 /*
99308 ** Free a WhereInfo structure
99309 */
99310 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
99311   if( ALWAYS(pWInfo) ){
99312     int i;
99313     for(i=0; i<pWInfo->nLevel; i++){
99314       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
99315       if( pInfo ){
99316         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
99317         if( pInfo->needToFreeIdxStr ){
99318           sqlite3_free(pInfo->idxStr);
99319         }
99320         sqlite3DbFree(db, pInfo);
99321       }
99322       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
99323         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
99324         if( pIdx ){
99325           sqlite3DbFree(db, pIdx->zColAff);
99326           sqlite3DbFree(db, pIdx);
99327         }
99328       }
99329     }
99330     whereClauseClear(pWInfo->pWC);
99331     sqlite3DbFree(db, pWInfo);
99332   }
99333 }
99334
99335
99336 /*
99337 ** Generate the beginning of the loop used for WHERE clause processing.
99338 ** The return value is a pointer to an opaque structure that contains
99339 ** information needed to terminate the loop.  Later, the calling routine
99340 ** should invoke sqlite3WhereEnd() with the return value of this function
99341 ** in order to complete the WHERE clause processing.
99342 **
99343 ** If an error occurs, this routine returns NULL.
99344 **
99345 ** The basic idea is to do a nested loop, one loop for each table in
99346 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
99347 ** same as a SELECT with only a single table in the FROM clause.)  For
99348 ** example, if the SQL is this:
99349 **
99350 **       SELECT * FROM t1, t2, t3 WHERE ...;
99351 **
99352 ** Then the code generated is conceptually like the following:
99353 **
99354 **      foreach row1 in t1 do       \    Code generated
99355 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
99356 **          foreach row3 in t3 do   /
99357 **            ...
99358 **          end                     \    Code generated
99359 **        end                        |-- by sqlite3WhereEnd()
99360 **      end                         /
99361 **
99362 ** Note that the loops might not be nested in the order in which they
99363 ** appear in the FROM clause if a different order is better able to make
99364 ** use of indices.  Note also that when the IN operator appears in
99365 ** the WHERE clause, it might result in additional nested loops for
99366 ** scanning through all values on the right-hand side of the IN.
99367 **
99368 ** There are Btree cursors associated with each table.  t1 uses cursor
99369 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
99370 ** And so forth.  This routine generates code to open those VDBE cursors
99371 ** and sqlite3WhereEnd() generates the code to close them.
99372 **
99373 ** The code that sqlite3WhereBegin() generates leaves the cursors named
99374 ** in pTabList pointing at their appropriate entries.  The [...] code
99375 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
99376 ** data from the various tables of the loop.
99377 **
99378 ** If the WHERE clause is empty, the foreach loops must each scan their
99379 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
99380 ** the tables have indices and there are terms in the WHERE clause that
99381 ** refer to those indices, a complete table scan can be avoided and the
99382 ** code will run much faster.  Most of the work of this routine is checking
99383 ** to see if there are indices that can be used to speed up the loop.
99384 **
99385 ** Terms of the WHERE clause are also used to limit which rows actually
99386 ** make it to the "..." in the middle of the loop.  After each "foreach",
99387 ** terms of the WHERE clause that use only terms in that loop and outer
99388 ** loops are evaluated and if false a jump is made around all subsequent
99389 ** inner loops (or around the "..." if the test occurs within the inner-
99390 ** most loop)
99391 **
99392 ** OUTER JOINS
99393 **
99394 ** An outer join of tables t1 and t2 is conceptally coded as follows:
99395 **
99396 **    foreach row1 in t1 do
99397 **      flag = 0
99398 **      foreach row2 in t2 do
99399 **        start:
99400 **          ...
99401 **          flag = 1
99402 **      end
99403 **      if flag==0 then
99404 **        move the row2 cursor to a null row
99405 **        goto start
99406 **      fi
99407 **    end
99408 **
99409 ** ORDER BY CLAUSE PROCESSING
99410 **
99411 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
99412 ** if there is one.  If there is no ORDER BY clause or if this routine
99413 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
99414 **
99415 ** If an index can be used so that the natural output order of the table
99416 ** scan is correct for the ORDER BY clause, then that index is used and
99417 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
99418 ** unnecessary sort of the result set if an index appropriate for the
99419 ** ORDER BY clause already exists.
99420 **
99421 ** If the where clause loops cannot be arranged to provide the correct
99422 ** output order, then the *ppOrderBy is unchanged.
99423 */
99424 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
99425   Parse *pParse,        /* The parser context */
99426   SrcList *pTabList,    /* A list of all tables to be scanned */
99427   Expr *pWhere,         /* The WHERE clause */
99428   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
99429   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
99430 ){
99431   int i;                     /* Loop counter */
99432   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
99433   int nTabList;              /* Number of elements in pTabList */
99434   WhereInfo *pWInfo;         /* Will become the return value of this function */
99435   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
99436   Bitmask notReady;          /* Cursors that are not yet positioned */
99437   WhereMaskSet *pMaskSet;    /* The expression mask set */
99438   WhereClause *pWC;               /* Decomposition of the WHERE clause */
99439   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
99440   WhereLevel *pLevel;             /* A single level in the pWInfo list */
99441   int iFrom;                      /* First unused FROM clause element */
99442   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
99443   sqlite3 *db;               /* Database connection */
99444
99445   /* The number of tables in the FROM clause is limited by the number of
99446   ** bits in a Bitmask 
99447   */
99448   testcase( pTabList->nSrc==BMS );
99449   if( pTabList->nSrc>BMS ){
99450     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
99451     return 0;
99452   }
99453
99454   /* This function normally generates a nested loop for all tables in 
99455   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
99456   ** only generate code for the first table in pTabList and assume that
99457   ** any cursors associated with subsequent tables are uninitialized.
99458   */
99459   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
99460
99461   /* Allocate and initialize the WhereInfo structure that will become the
99462   ** return value. A single allocation is used to store the WhereInfo
99463   ** struct, the contents of WhereInfo.a[], the WhereClause structure
99464   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
99465   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
99466   ** some architectures. Hence the ROUND8() below.
99467   */
99468   db = pParse->db;
99469   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
99470   pWInfo = sqlite3DbMallocZero(db, 
99471       nByteWInfo + 
99472       sizeof(WhereClause) +
99473       sizeof(WhereMaskSet)
99474   );
99475   if( db->mallocFailed ){
99476     sqlite3DbFree(db, pWInfo);
99477     pWInfo = 0;
99478     goto whereBeginError;
99479   }
99480   pWInfo->nLevel = nTabList;
99481   pWInfo->pParse = pParse;
99482   pWInfo->pTabList = pTabList;
99483   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
99484   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
99485   pWInfo->wctrlFlags = wctrlFlags;
99486   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
99487   pMaskSet = (WhereMaskSet*)&pWC[1];
99488
99489   /* Split the WHERE clause into separate subexpressions where each
99490   ** subexpression is separated by an AND operator.
99491   */
99492   initMaskSet(pMaskSet);
99493   whereClauseInit(pWC, pParse, pMaskSet);
99494   sqlite3ExprCodeConstants(pParse, pWhere);
99495   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
99496     
99497   /* Special case: a WHERE clause that is constant.  Evaluate the
99498   ** expression and either jump over all of the code or fall thru.
99499   */
99500   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
99501     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
99502     pWhere = 0;
99503   }
99504
99505   /* Assign a bit from the bitmask to every term in the FROM clause.
99506   **
99507   ** When assigning bitmask values to FROM clause cursors, it must be
99508   ** the case that if X is the bitmask for the N-th FROM clause term then
99509   ** the bitmask for all FROM clause terms to the left of the N-th term
99510   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
99511   ** its Expr.iRightJoinTable value to find the bitmask of the right table
99512   ** of the join.  Subtracting one from the right table bitmask gives a
99513   ** bitmask for all tables to the left of the join.  Knowing the bitmask
99514   ** for all tables to the left of a left join is important.  Ticket #3015.
99515   **
99516   ** Configure the WhereClause.vmask variable so that bits that correspond
99517   ** to virtual table cursors are set. This is used to selectively disable 
99518   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
99519   ** with virtual tables.
99520   **
99521   ** Note that bitmasks are created for all pTabList->nSrc tables in
99522   ** pTabList, not just the first nTabList tables.  nTabList is normally
99523   ** equal to pTabList->nSrc but might be shortened to 1 if the
99524   ** WHERE_ONETABLE_ONLY flag is set.
99525   */
99526   assert( pWC->vmask==0 && pMaskSet->n==0 );
99527   for(i=0; i<pTabList->nSrc; i++){
99528     createMask(pMaskSet, pTabList->a[i].iCursor);
99529 #ifndef SQLITE_OMIT_VIRTUALTABLE
99530     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
99531       pWC->vmask |= ((Bitmask)1 << i);
99532     }
99533 #endif
99534   }
99535 #ifndef NDEBUG
99536   {
99537     Bitmask toTheLeft = 0;
99538     for(i=0; i<pTabList->nSrc; i++){
99539       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
99540       assert( (m-1)==toTheLeft );
99541       toTheLeft |= m;
99542     }
99543   }
99544 #endif
99545
99546   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
99547   ** add new virtual terms onto the end of the WHERE clause.  We do not
99548   ** want to analyze these virtual terms, so start analyzing at the end
99549   ** and work forward so that the added virtual terms are never processed.
99550   */
99551   exprAnalyzeAll(pTabList, pWC);
99552   if( db->mallocFailed ){
99553     goto whereBeginError;
99554   }
99555
99556   /* Chose the best index to use for each table in the FROM clause.
99557   **
99558   ** This loop fills in the following fields:
99559   **
99560   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
99561   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
99562   **   pWInfo->a[].nEq       The number of == and IN constraints
99563   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
99564   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
99565   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
99566   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
99567   **
99568   ** This loop also figures out the nesting order of tables in the FROM
99569   ** clause.
99570   */
99571   notReady = ~(Bitmask)0;
99572   pTabItem = pTabList->a;
99573   pLevel = pWInfo->a;
99574   andFlags = ~0;
99575   WHERETRACE(("*** Optimizer Start ***\n"));
99576   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
99577     WhereCost bestPlan;         /* Most efficient plan seen so far */
99578     Index *pIdx;                /* Index for FROM table at pTabItem */
99579     int j;                      /* For looping over FROM tables */
99580     int bestJ = -1;             /* The value of j */
99581     Bitmask m;                  /* Bitmask value for j or bestJ */
99582     int isOptimal;              /* Iterator for optimal/non-optimal search */
99583     int nUnconstrained;         /* Number tables without INDEXED BY */
99584     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
99585
99586     memset(&bestPlan, 0, sizeof(bestPlan));
99587     bestPlan.rCost = SQLITE_BIG_DBL;
99588     WHERETRACE(("*** Begin search for loop %d ***\n", i));
99589
99590     /* Loop through the remaining entries in the FROM clause to find the
99591     ** next nested loop. The loop tests all FROM clause entries
99592     ** either once or twice. 
99593     **
99594     ** The first test is always performed if there are two or more entries
99595     ** remaining and never performed if there is only one FROM clause entry
99596     ** to choose from.  The first test looks for an "optimal" scan.  In
99597     ** this context an optimal scan is one that uses the same strategy
99598     ** for the given FROM clause entry as would be selected if the entry
99599     ** were used as the innermost nested loop.  In other words, a table
99600     ** is chosen such that the cost of running that table cannot be reduced
99601     ** by waiting for other tables to run first.  This "optimal" test works
99602     ** by first assuming that the FROM clause is on the inner loop and finding
99603     ** its query plan, then checking to see if that query plan uses any
99604     ** other FROM clause terms that are notReady.  If no notReady terms are
99605     ** used then the "optimal" query plan works.
99606     **
99607     ** Note that the WhereCost.nRow parameter for an optimal scan might
99608     ** not be as small as it would be if the table really were the innermost
99609     ** join.  The nRow value can be reduced by WHERE clause constraints
99610     ** that do not use indices.  But this nRow reduction only happens if the
99611     ** table really is the innermost join.  
99612     **
99613     ** The second loop iteration is only performed if no optimal scan
99614     ** strategies were found by the first iteration. This second iteration
99615     ** is used to search for the lowest cost scan overall.
99616     **
99617     ** Previous versions of SQLite performed only the second iteration -
99618     ** the next outermost loop was always that with the lowest overall
99619     ** cost. However, this meant that SQLite could select the wrong plan
99620     ** for scripts such as the following:
99621     **   
99622     **   CREATE TABLE t1(a, b); 
99623     **   CREATE TABLE t2(c, d);
99624     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
99625     **
99626     ** The best strategy is to iterate through table t1 first. However it
99627     ** is not possible to determine this with a simple greedy algorithm.
99628     ** Since the cost of a linear scan through table t2 is the same 
99629     ** as the cost of a linear scan through table t1, a simple greedy 
99630     ** algorithm may choose to use t2 for the outer loop, which is a much
99631     ** costlier approach.
99632     */
99633     nUnconstrained = 0;
99634     notIndexed = 0;
99635     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
99636       Bitmask mask;             /* Mask of tables not yet ready */
99637       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
99638         int doNotReorder;    /* True if this table should not be reordered */
99639         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
99640         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
99641   
99642         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
99643         if( j!=iFrom && doNotReorder ) break;
99644         m = getMask(pMaskSet, pTabItem->iCursor);
99645         if( (m & notReady)==0 ){
99646           if( j==iFrom ) iFrom++;
99647           continue;
99648         }
99649         mask = (isOptimal ? m : notReady);
99650         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
99651         if( pTabItem->pIndex==0 ) nUnconstrained++;
99652   
99653         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
99654                     j, isOptimal));
99655         assert( pTabItem->pTab );
99656 #ifndef SQLITE_OMIT_VIRTUALTABLE
99657         if( IsVirtual(pTabItem->pTab) ){
99658           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
99659           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
99660                            &sCost, pp);
99661         }else 
99662 #endif
99663         {
99664           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
99665                          &sCost);
99666         }
99667         assert( isOptimal || (sCost.used&notReady)==0 );
99668
99669         /* If an INDEXED BY clause is present, then the plan must use that
99670         ** index if it uses any index at all */
99671         assert( pTabItem->pIndex==0 
99672                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
99673                   || sCost.plan.u.pIdx==pTabItem->pIndex );
99674
99675         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
99676           notIndexed |= m;
99677         }
99678
99679         /* Conditions under which this table becomes the best so far:
99680         **
99681         **   (1) The table must not depend on other tables that have not
99682         **       yet run.
99683         **
99684         **   (2) A full-table-scan plan cannot supercede another plan unless
99685         **       it is an "optimal" plan as defined above.
99686         **
99687         **   (3) All tables have an INDEXED BY clause or this table lacks an
99688         **       INDEXED BY clause or this table uses the specific
99689         **       index specified by its INDEXED BY clause.  This rule ensures
99690         **       that a best-so-far is always selected even if an impossible
99691         **       combination of INDEXED BY clauses are given.  The error
99692         **       will be detected and relayed back to the application later.
99693         **       The NEVER() comes about because rule (2) above prevents
99694         **       An indexable full-table-scan from reaching rule (3).
99695         **
99696         **   (4) The plan cost must be lower than prior plans or else the
99697         **       cost must be the same and the number of rows must be lower.
99698         */
99699         if( (sCost.used&notReady)==0                       /* (1) */
99700             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
99701                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
99702             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
99703                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
99704             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
99705                 || (sCost.rCost<=bestPlan.rCost 
99706                  && sCost.plan.nRow<bestPlan.plan.nRow))
99707         ){
99708           WHERETRACE(("=== table %d is best so far"
99709                       " with cost=%g and nRow=%g\n",
99710                       j, sCost.rCost, sCost.plan.nRow));
99711           bestPlan = sCost;
99712           bestJ = j;
99713         }
99714         if( doNotReorder ) break;
99715       }
99716     }
99717     assert( bestJ>=0 );
99718     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
99719     WHERETRACE(("*** Optimizer selects table %d for loop %d"
99720                 " with cost=%g and nRow=%g\n",
99721                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
99722     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
99723       *ppOrderBy = 0;
99724     }
99725     andFlags &= bestPlan.plan.wsFlags;
99726     pLevel->plan = bestPlan.plan;
99727     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
99728     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
99729     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
99730       pLevel->iIdxCur = pParse->nTab++;
99731     }else{
99732       pLevel->iIdxCur = -1;
99733     }
99734     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
99735     pLevel->iFrom = (u8)bestJ;
99736     if( bestPlan.plan.nRow>=(double)1 ){
99737       pParse->nQueryLoop *= bestPlan.plan.nRow;
99738     }
99739
99740     /* Check that if the table scanned by this loop iteration had an
99741     ** INDEXED BY clause attached to it, that the named index is being
99742     ** used for the scan. If not, then query compilation has failed.
99743     ** Return an error.
99744     */
99745     pIdx = pTabList->a[bestJ].pIndex;
99746     if( pIdx ){
99747       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
99748         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
99749         goto whereBeginError;
99750       }else{
99751         /* If an INDEXED BY clause is used, the bestIndex() function is
99752         ** guaranteed to find the index specified in the INDEXED BY clause
99753         ** if it find an index at all. */
99754         assert( bestPlan.plan.u.pIdx==pIdx );
99755       }
99756     }
99757   }
99758   WHERETRACE(("*** Optimizer Finished ***\n"));
99759   if( pParse->nErr || db->mallocFailed ){
99760     goto whereBeginError;
99761   }
99762
99763   /* If the total query only selects a single row, then the ORDER BY
99764   ** clause is irrelevant.
99765   */
99766   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
99767     *ppOrderBy = 0;
99768   }
99769
99770   /* If the caller is an UPDATE or DELETE statement that is requesting
99771   ** to use a one-pass algorithm, determine if this is appropriate.
99772   ** The one-pass algorithm only works if the WHERE clause constraints
99773   ** the statement to update a single row.
99774   */
99775   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
99776   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
99777     pWInfo->okOnePass = 1;
99778     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
99779   }
99780
99781   /* Open all tables in the pTabList and any indices selected for
99782   ** searching those tables.
99783   */
99784   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
99785   notReady = ~(Bitmask)0;
99786   pWInfo->nRowOut = (double)1;
99787   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
99788     Table *pTab;     /* Table to open */
99789     int iDb;         /* Index of database containing table/index */
99790
99791     pTabItem = &pTabList->a[pLevel->iFrom];
99792     pTab = pTabItem->pTab;
99793     pLevel->iTabCur = pTabItem->iCursor;
99794     pWInfo->nRowOut *= pLevel->plan.nRow;
99795     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99796     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
99797       /* Do nothing */
99798     }else
99799 #ifndef SQLITE_OMIT_VIRTUALTABLE
99800     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
99801       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
99802       int iCur = pTabItem->iCursor;
99803       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
99804     }else
99805 #endif
99806     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
99807          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
99808       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
99809       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
99810       testcase( pTab->nCol==BMS-1 );
99811       testcase( pTab->nCol==BMS );
99812       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
99813         Bitmask b = pTabItem->colUsed;
99814         int n = 0;
99815         for(; b; b=b>>1, n++){}
99816         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
99817                             SQLITE_INT_TO_PTR(n), P4_INT32);
99818         assert( n<=pTab->nCol );
99819       }
99820     }else{
99821       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
99822     }
99823 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
99824     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
99825       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
99826     }else
99827 #endif
99828     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
99829       Index *pIx = pLevel->plan.u.pIdx;
99830       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
99831       int iIdxCur = pLevel->iIdxCur;
99832       assert( pIx->pSchema==pTab->pSchema );
99833       assert( iIdxCur>=0 );
99834       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
99835                         (char*)pKey, P4_KEYINFO_HANDOFF);
99836       VdbeComment((v, "%s", pIx->zName));
99837     }
99838     sqlite3CodeVerifySchema(pParse, iDb);
99839     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
99840   }
99841   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
99842   if( db->mallocFailed ) goto whereBeginError;
99843
99844   /* Generate the code to do the search.  Each iteration of the for
99845   ** loop below generates code for a single nested loop of the VM
99846   ** program.
99847   */
99848   notReady = ~(Bitmask)0;
99849   for(i=0; i<nTabList; i++){
99850     pLevel = &pWInfo->a[i];
99851     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
99852     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
99853     pWInfo->iContinue = pLevel->addrCont;
99854   }
99855
99856 #ifdef SQLITE_TEST  /* For testing and debugging use only */
99857   /* Record in the query plan information about the current table
99858   ** and the index used to access it (if any).  If the table itself
99859   ** is not used, its name is just '{}'.  If no index is used
99860   ** the index is listed as "{}".  If the primary key is used the
99861   ** index name is '*'.
99862   */
99863   for(i=0; i<nTabList; i++){
99864     char *z;
99865     int n;
99866     pLevel = &pWInfo->a[i];
99867     pTabItem = &pTabList->a[pLevel->iFrom];
99868     z = pTabItem->zAlias;
99869     if( z==0 ) z = pTabItem->pTab->zName;
99870     n = sqlite3Strlen30(z);
99871     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
99872       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
99873         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
99874         nQPlan += 2;
99875       }else{
99876         memcpy(&sqlite3_query_plan[nQPlan], z, n);
99877         nQPlan += n;
99878       }
99879       sqlite3_query_plan[nQPlan++] = ' ';
99880     }
99881     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
99882     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
99883     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
99884       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
99885       nQPlan += 2;
99886     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
99887       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
99888       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
99889         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
99890         nQPlan += n;
99891         sqlite3_query_plan[nQPlan++] = ' ';
99892       }
99893     }else{
99894       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
99895       nQPlan += 3;
99896     }
99897   }
99898   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
99899     sqlite3_query_plan[--nQPlan] = 0;
99900   }
99901   sqlite3_query_plan[nQPlan] = 0;
99902   nQPlan = 0;
99903 #endif /* SQLITE_TEST // Testing and debugging use only */
99904
99905   /* Record the continuation address in the WhereInfo structure.  Then
99906   ** clean up and return.
99907   */
99908   return pWInfo;
99909
99910   /* Jump here if malloc fails */
99911 whereBeginError:
99912   if( pWInfo ){
99913     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
99914     whereInfoFree(db, pWInfo);
99915   }
99916   return 0;
99917 }
99918
99919 /*
99920 ** Generate the end of the WHERE loop.  See comments on 
99921 ** sqlite3WhereBegin() for additional information.
99922 */
99923 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
99924   Parse *pParse = pWInfo->pParse;
99925   Vdbe *v = pParse->pVdbe;
99926   int i;
99927   WhereLevel *pLevel;
99928   SrcList *pTabList = pWInfo->pTabList;
99929   sqlite3 *db = pParse->db;
99930
99931   /* Generate loop termination code.
99932   */
99933   sqlite3ExprCacheClear(pParse);
99934   for(i=pWInfo->nLevel-1; i>=0; i--){
99935     pLevel = &pWInfo->a[i];
99936     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
99937     if( pLevel->op!=OP_Noop ){
99938       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
99939       sqlite3VdbeChangeP5(v, pLevel->p5);
99940     }
99941     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
99942       struct InLoop *pIn;
99943       int j;
99944       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
99945       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
99946         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
99947         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
99948         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
99949       }
99950       sqlite3DbFree(db, pLevel->u.in.aInLoop);
99951     }
99952     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
99953     if( pLevel->iLeftJoin ){
99954       int addr;
99955       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
99956       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
99957            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
99958       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
99959         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
99960       }
99961       if( pLevel->iIdxCur>=0 ){
99962         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
99963       }
99964       if( pLevel->op==OP_Return ){
99965         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
99966       }else{
99967         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
99968       }
99969       sqlite3VdbeJumpHere(v, addr);
99970     }
99971   }
99972
99973   /* The "break" point is here, just past the end of the outer loop.
99974   ** Set it.
99975   */
99976   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
99977
99978   /* Close all of the cursors that were opened by sqlite3WhereBegin.
99979   */
99980   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
99981   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
99982     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
99983     Table *pTab = pTabItem->pTab;
99984     assert( pTab!=0 );
99985     if( (pTab->tabFlags & TF_Ephemeral)==0
99986      && pTab->pSelect==0
99987      && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
99988     ){
99989       int ws = pLevel->plan.wsFlags;
99990       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
99991         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
99992       }
99993       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
99994         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
99995       }
99996     }
99997
99998     /* If this scan uses an index, make code substitutions to read data
99999     ** from the index in preference to the table. Sometimes, this means
100000     ** the table need never be read from. This is a performance boost,
100001     ** as the vdbe level waits until the table is read before actually
100002     ** seeking the table cursor to the record corresponding to the current
100003     ** position in the index.
100004     ** 
100005     ** Calls to the code generator in between sqlite3WhereBegin and
100006     ** sqlite3WhereEnd will have created code that references the table
100007     ** directly.  This loop scans all that code looking for opcodes
100008     ** that reference the table and converts them into opcodes that
100009     ** reference the index.
100010     */
100011     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
100012       int k, j, last;
100013       VdbeOp *pOp;
100014       Index *pIdx = pLevel->plan.u.pIdx;
100015
100016       assert( pIdx!=0 );
100017       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
100018       last = sqlite3VdbeCurrentAddr(v);
100019       for(k=pWInfo->iTop; k<last; k++, pOp++){
100020         if( pOp->p1!=pLevel->iTabCur ) continue;
100021         if( pOp->opcode==OP_Column ){
100022           for(j=0; j<pIdx->nColumn; j++){
100023             if( pOp->p2==pIdx->aiColumn[j] ){
100024               pOp->p2 = j;
100025               pOp->p1 = pLevel->iIdxCur;
100026               break;
100027             }
100028           }
100029           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
100030                || j<pIdx->nColumn );
100031         }else if( pOp->opcode==OP_Rowid ){
100032           pOp->p1 = pLevel->iIdxCur;
100033           pOp->opcode = OP_IdxRowid;
100034         }
100035       }
100036     }
100037   }
100038
100039   /* Final cleanup
100040   */
100041   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
100042   whereInfoFree(db, pWInfo);
100043   return;
100044 }
100045
100046 /************** End of where.c ***********************************************/
100047 /************** Begin file parse.c *******************************************/
100048 /* Driver template for the LEMON parser generator.
100049 ** The author disclaims copyright to this source code.
100050 **
100051 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
100052 ** The only modifications are the addition of a couple of NEVER()
100053 ** macros to disable tests that are needed in the case of a general
100054 ** LALR(1) grammar but which are always false in the
100055 ** specific grammar used by SQLite.
100056 */
100057 /* First off, code is included that follows the "include" declaration
100058 ** in the input grammar file. */
100059
100060
100061 /*
100062 ** Disable all error recovery processing in the parser push-down
100063 ** automaton.
100064 */
100065 #define YYNOERRORRECOVERY 1
100066
100067 /*
100068 ** Make yytestcase() the same as testcase()
100069 */
100070 #define yytestcase(X) testcase(X)
100071
100072 /*
100073 ** An instance of this structure holds information about the
100074 ** LIMIT clause of a SELECT statement.
100075 */
100076 struct LimitVal {
100077   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
100078   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
100079 };
100080
100081 /*
100082 ** An instance of this structure is used to store the LIKE,
100083 ** GLOB, NOT LIKE, and NOT GLOB operators.
100084 */
100085 struct LikeOp {
100086   Token eOperator;  /* "like" or "glob" or "regexp" */
100087   int not;         /* True if the NOT keyword is present */
100088 };
100089
100090 /*
100091 ** An instance of the following structure describes the event of a
100092 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
100093 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
100094 **
100095 **      UPDATE ON (a,b,c)
100096 **
100097 ** Then the "b" IdList records the list "a,b,c".
100098 */
100099 struct TrigEvent { int a; IdList * b; };
100100
100101 /*
100102 ** An instance of this structure holds the ATTACH key and the key type.
100103 */
100104 struct AttachKey { int type;  Token key; };
100105
100106
100107   /* This is a utility routine used to set the ExprSpan.zStart and
100108   ** ExprSpan.zEnd values of pOut so that the span covers the complete
100109   ** range of text beginning with pStart and going to the end of pEnd.
100110   */
100111   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
100112     pOut->zStart = pStart->z;
100113     pOut->zEnd = &pEnd->z[pEnd->n];
100114   }
100115
100116   /* Construct a new Expr object from a single identifier.  Use the
100117   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
100118   ** that created the expression.
100119   */
100120   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
100121     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
100122     pOut->zStart = pValue->z;
100123     pOut->zEnd = &pValue->z[pValue->n];
100124   }
100125
100126   /* This routine constructs a binary expression node out of two ExprSpan
100127   ** objects and uses the result to populate a new ExprSpan object.
100128   */
100129   static void spanBinaryExpr(
100130     ExprSpan *pOut,     /* Write the result here */
100131     Parse *pParse,      /* The parsing context.  Errors accumulate here */
100132     int op,             /* The binary operation */
100133     ExprSpan *pLeft,    /* The left operand */
100134     ExprSpan *pRight    /* The right operand */
100135   ){
100136     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
100137     pOut->zStart = pLeft->zStart;
100138     pOut->zEnd = pRight->zEnd;
100139   }
100140
100141   /* Construct an expression node for a unary postfix operator
100142   */
100143   static void spanUnaryPostfix(
100144     ExprSpan *pOut,        /* Write the new expression node here */
100145     Parse *pParse,         /* Parsing context to record errors */
100146     int op,                /* The operator */
100147     ExprSpan *pOperand,    /* The operand */
100148     Token *pPostOp         /* The operand token for setting the span */
100149   ){
100150     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
100151     pOut->zStart = pOperand->zStart;
100152     pOut->zEnd = &pPostOp->z[pPostOp->n];
100153   }                           
100154
100155   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
100156   ** unary TK_ISNULL or TK_NOTNULL expression. */
100157   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
100158     sqlite3 *db = pParse->db;
100159     if( db->mallocFailed==0 && pY->op==TK_NULL ){
100160       pA->op = (u8)op;
100161       sqlite3ExprDelete(db, pA->pRight);
100162       pA->pRight = 0;
100163     }
100164   }
100165
100166   /* Construct an expression node for a unary prefix operator
100167   */
100168   static void spanUnaryPrefix(
100169     ExprSpan *pOut,        /* Write the new expression node here */
100170     Parse *pParse,         /* Parsing context to record errors */
100171     int op,                /* The operator */
100172     ExprSpan *pOperand,    /* The operand */
100173     Token *pPreOp         /* The operand token for setting the span */
100174   ){
100175     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
100176     pOut->zStart = pPreOp->z;
100177     pOut->zEnd = pOperand->zEnd;
100178   }
100179 /* Next is all token values, in a form suitable for use by makeheaders.
100180 ** This section will be null unless lemon is run with the -m switch.
100181 */
100182 /* 
100183 ** These constants (all generated automatically by the parser generator)
100184 ** specify the various kinds of tokens (terminals) that the parser
100185 ** understands. 
100186 **
100187 ** Each symbol here is a terminal symbol in the grammar.
100188 */
100189 /* Make sure the INTERFACE macro is defined.
100190 */
100191 #ifndef INTERFACE
100192 # define INTERFACE 1
100193 #endif
100194 /* The next thing included is series of defines which control
100195 ** various aspects of the generated parser.
100196 **    YYCODETYPE         is the data type used for storing terminal
100197 **                       and nonterminal numbers.  "unsigned char" is
100198 **                       used if there are fewer than 250 terminals
100199 **                       and nonterminals.  "int" is used otherwise.
100200 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
100201 **                       to no legal terminal or nonterminal number.  This
100202 **                       number is used to fill in empty slots of the hash 
100203 **                       table.
100204 **    YYFALLBACK         If defined, this indicates that one or more tokens
100205 **                       have fall-back values which should be used if the
100206 **                       original value of the token will not parse.
100207 **    YYACTIONTYPE       is the data type used for storing terminal
100208 **                       and nonterminal numbers.  "unsigned char" is
100209 **                       used if there are fewer than 250 rules and
100210 **                       states combined.  "int" is used otherwise.
100211 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
100212 **                       directly to the parser from the tokenizer.
100213 **    YYMINORTYPE        is the data type used for all minor tokens.
100214 **                       This is typically a union of many types, one of
100215 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
100216 **                       for base tokens is called "yy0".
100217 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
100218 **                       zero the stack is dynamically sized using realloc()
100219 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
100220 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
100221 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
100222 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
100223 **    YYNSTATE           the combined number of states.
100224 **    YYNRULE            the number of rules in the grammar
100225 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
100226 **                       defined, then do no error processing.
100227 */
100228 #define YYCODETYPE unsigned char
100229 #define YYNOCODE 253
100230 #define YYACTIONTYPE unsigned short int
100231 #define YYWILDCARD 67
100232 #define sqlite3ParserTOKENTYPE Token
100233 typedef union {
100234   int yyinit;
100235   sqlite3ParserTOKENTYPE yy0;
100236   int yy4;
100237   struct TrigEvent yy90;
100238   ExprSpan yy118;
100239   TriggerStep* yy203;
100240   u8 yy210;
100241   struct {int value; int mask;} yy215;
100242   SrcList* yy259;
100243   struct LimitVal yy292;
100244   Expr* yy314;
100245   ExprList* yy322;
100246   struct LikeOp yy342;
100247   IdList* yy384;
100248   Select* yy387;
100249 } YYMINORTYPE;
100250 #ifndef YYSTACKDEPTH
100251 #define YYSTACKDEPTH 100
100252 #endif
100253 #define sqlite3ParserARG_SDECL Parse *pParse;
100254 #define sqlite3ParserARG_PDECL ,Parse *pParse
100255 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
100256 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
100257 #define YYNSTATE 630
100258 #define YYNRULE 329
100259 #define YYFALLBACK 1
100260 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
100261 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
100262 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
100263
100264 /* The yyzerominor constant is used to initialize instances of
100265 ** YYMINORTYPE objects to zero. */
100266 static const YYMINORTYPE yyzerominor = { 0 };
100267
100268 /* Define the yytestcase() macro to be a no-op if is not already defined
100269 ** otherwise.
100270 **
100271 ** Applications can choose to define yytestcase() in the %include section
100272 ** to a macro that can assist in verifying code coverage.  For production
100273 ** code the yytestcase() macro should be turned off.  But it is useful
100274 ** for testing.
100275 */
100276 #ifndef yytestcase
100277 # define yytestcase(X)
100278 #endif
100279
100280
100281 /* Next are the tables used to determine what action to take based on the
100282 ** current state and lookahead token.  These tables are used to implement
100283 ** functions that take a state number and lookahead value and return an
100284 ** action integer.  
100285 **
100286 ** Suppose the action integer is N.  Then the action is determined as
100287 ** follows
100288 **
100289 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
100290 **                                      token onto the stack and goto state N.
100291 **
100292 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
100293 **
100294 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
100295 **
100296 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
100297 **
100298 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
100299 **                                      slots in the yy_action[] table.
100300 **
100301 ** The action table is constructed as a single large table named yy_action[].
100302 ** Given state S and lookahead X, the action is computed as
100303 **
100304 **      yy_action[ yy_shift_ofst[S] + X ]
100305 **
100306 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
100307 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
100308 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
100309 ** and that yy_default[S] should be used instead.  
100310 **
100311 ** The formula above is for computing the action when the lookahead is
100312 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
100313 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
100314 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
100315 ** YY_SHIFT_USE_DFLT.
100316 **
100317 ** The following are the tables generated in this section:
100318 **
100319 **  yy_action[]        A single table containing all actions.
100320 **  yy_lookahead[]     A table containing the lookahead for each entry in
100321 **                     yy_action.  Used to detect hash collisions.
100322 **  yy_shift_ofst[]    For each state, the offset into yy_action for
100323 **                     shifting terminals.
100324 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
100325 **                     shifting non-terminals after a reduce.
100326 **  yy_default[]       Default action for each state.
100327 */
100328 #define YY_ACTTAB_COUNT (1557)
100329 static const YYACTIONTYPE yy_action[] = {
100330  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
100331  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
100332  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
100333  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
100334  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
100335  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
100336  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
100337  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
100338  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
100339  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
100340  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
100341  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
100342  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
100343  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
100344  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
100345  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
100346  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
100347  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
100348  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
100349  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
100350  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
100351  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
100352  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
100353  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
100354  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
100355  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
100356  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
100357  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
100358  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
100359  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
100360  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
100361  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
100362  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
100363  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
100364  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
100365  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
100366  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
100367  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
100368  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
100369  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
100370  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
100371  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
100372  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
100373  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
100374  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
100375  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
100376  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
100377  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
100378  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
100379  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
100380  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
100381  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
100382  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
100383  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
100384  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
100385  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
100386  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
100387  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
100388  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
100389  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
100390  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
100391  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
100392  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
100393  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
100394  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
100395  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
100396  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
100397  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
100398  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
100399  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
100400  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
100401  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
100402  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
100403  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
100404  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
100405  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
100406  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
100407  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
100408  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
100409  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
100410  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
100411  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
100412  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
100413  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
100414  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
100415  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
100416  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
100417  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
100418  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
100419  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
100420  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
100421  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
100422  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
100423  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
100424  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
100425  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
100426  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
100427  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
100428  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
100429  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
100430  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
100431  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
100432  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
100433  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
100434  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
100435  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
100436  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
100437  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
100438  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
100439  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
100440  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
100441  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
100442  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
100443  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
100444  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
100445  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
100446  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
100447  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
100448  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
100449  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
100450  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
100451  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
100452  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
100453  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
100454  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
100455  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
100456  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
100457  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
100458  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
100459  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
100460  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
100461  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
100462  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
100463  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
100464  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
100465  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
100466  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
100467  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
100468  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
100469  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
100470  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
100471  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
100472  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
100473  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
100474  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
100475  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
100476  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
100477  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
100478  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
100479  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
100480  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
100481  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
100482  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
100483  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
100484  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
100485  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
100486 };
100487 static const YYCODETYPE yy_lookahead[] = {
100488  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
100489  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
100490  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
100491  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
100492  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
100493  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
100494  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
100495  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
100496  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
100497  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
100498  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
100499  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
100500  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
100501  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
100502  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
100503  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
100504  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
100505  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
100506  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
100507  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
100508  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
100509  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
100510  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
100511  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
100512  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
100513  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
100514  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
100515  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
100516  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
100517  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
100518  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
100519  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
100520  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
100521  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
100522  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
100523  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
100524  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
100525  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
100526  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
100527  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
100528  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
100529  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
100530  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
100531  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
100532  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
100533  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
100534  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
100535  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
100536  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
100537  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
100538  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
100539  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
100540  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
100541  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
100542  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
100543  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
100544  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
100545  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
100546  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
100547  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
100548  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
100549  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
100550  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
100551  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
100552  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
100553  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
100554  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
100555  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
100556  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
100557  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
100558  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
100559  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
100560  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
100561  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
100562  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
100563  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
100564  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
100565  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
100566  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
100567  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
100568  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
100569  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
100570  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
100571  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
100572  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
100573  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
100574  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
100575  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
100576  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
100577  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
100578  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
100579  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
100580  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
100581  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
100582  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
100583  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
100584  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
100585  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
100586  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
100587  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
100588  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
100589  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
100590  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
100591  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
100592  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
100593  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
100594  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
100595  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
100596  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
100597  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
100598  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
100599  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
100600  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
100601  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
100602  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
100603  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
100604  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
100605  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
100606  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
100607  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
100608  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
100609  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
100610  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
100611  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
100612  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
100613  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
100614  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
100615  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
100616  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
100617  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
100618  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
100619  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
100620  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
100621  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
100622  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
100623  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
100624  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
100625  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
100626  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
100627  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
100628  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
100629  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
100630  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
100631  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
100632  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
100633  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
100634  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
100635  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
100636  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
100637  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
100638  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
100639  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
100640  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
100641  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
100642  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
100643  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
100644 };
100645 #define YY_SHIFT_USE_DFLT (-74)
100646 #define YY_SHIFT_COUNT (418)
100647 #define YY_SHIFT_MIN   (-73)
100648 #define YY_SHIFT_MAX   (1468)
100649 static const short yy_shift_ofst[] = {
100650  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
100651  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
100652  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
100653  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
100654  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
100655  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
100656  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
100657  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
100658  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
100659  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
100660  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
100661  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
100662  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
100663  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
100664  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
100665  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
100666  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
100667  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
100668  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
100669  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
100670  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
100671  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
100672  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
100673  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
100674  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
100675  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
100676  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
100677  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
100678  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
100679  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
100680  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
100681  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
100682  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
100683  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
100684  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
100685  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
100686  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
100687  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
100688  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
100689  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
100690  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
100691  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
100692 };
100693 #define YY_REDUCE_USE_DFLT (-142)
100694 #define YY_REDUCE_COUNT (312)
100695 #define YY_REDUCE_MIN   (-141)
100696 #define YY_REDUCE_MAX   (1369)
100697 static const short yy_reduce_ofst[] = {
100698  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
100699  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
100700  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
100701  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
100702  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
100703  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
100704  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
100705  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
100706  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
100707  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
100708  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
100709  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
100710  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
100711  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
100712  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
100713  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
100714  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
100715  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
100716  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
100717  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
100718  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
100719  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
100720  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
100721  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
100722  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
100723  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
100724  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
100725  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
100726  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
100727  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
100728  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
100729  /*   310 */  1031, 1023, 1030,
100730 };
100731 static const YYACTIONTYPE yy_default[] = {
100732  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
100733  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
100734  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100735  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100736  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100737  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100738  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
100739  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
100740  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
100741  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
100742  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
100743  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100744  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
100745  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
100746  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100747  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
100748  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100749  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100750  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
100751  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
100752  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
100753  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
100754  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
100755  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
100756  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
100757  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
100758  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
100759  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
100760  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
100761  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
100762  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
100763  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
100764  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100765  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
100766  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100767  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
100768  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
100769  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100770  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
100771  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
100772  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
100773  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
100774  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
100775  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
100776  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
100777  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
100778  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
100779  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
100780  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
100781  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
100782  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
100783  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
100784  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
100785  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
100786  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
100787  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
100788  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
100789  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
100790  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
100791  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
100792  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
100793  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
100794  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
100795 };
100796
100797 /* The next table maps tokens into fallback tokens.  If a construct
100798 ** like the following:
100799 ** 
100800 **      %fallback ID X Y Z.
100801 **
100802 ** appears in the grammar, then ID becomes a fallback token for X, Y,
100803 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
100804 ** but it does not parse, the type of the token is changed to ID and
100805 ** the parse is retried before an error is thrown.
100806 */
100807 #ifdef YYFALLBACK
100808 static const YYCODETYPE yyFallback[] = {
100809     0,  /*          $ => nothing */
100810     0,  /*       SEMI => nothing */
100811    26,  /*    EXPLAIN => ID */
100812    26,  /*      QUERY => ID */
100813    26,  /*       PLAN => ID */
100814    26,  /*      BEGIN => ID */
100815     0,  /* TRANSACTION => nothing */
100816    26,  /*   DEFERRED => ID */
100817    26,  /*  IMMEDIATE => ID */
100818    26,  /*  EXCLUSIVE => ID */
100819     0,  /*     COMMIT => nothing */
100820    26,  /*        END => ID */
100821    26,  /*   ROLLBACK => ID */
100822    26,  /*  SAVEPOINT => ID */
100823    26,  /*    RELEASE => ID */
100824     0,  /*         TO => nothing */
100825     0,  /*      TABLE => nothing */
100826     0,  /*     CREATE => nothing */
100827    26,  /*         IF => ID */
100828     0,  /*        NOT => nothing */
100829     0,  /*     EXISTS => nothing */
100830    26,  /*       TEMP => ID */
100831     0,  /*         LP => nothing */
100832     0,  /*         RP => nothing */
100833     0,  /*         AS => nothing */
100834     0,  /*      COMMA => nothing */
100835     0,  /*         ID => nothing */
100836     0,  /*    INDEXED => nothing */
100837    26,  /*      ABORT => ID */
100838    26,  /*     ACTION => ID */
100839    26,  /*      AFTER => ID */
100840    26,  /*    ANALYZE => ID */
100841    26,  /*        ASC => ID */
100842    26,  /*     ATTACH => ID */
100843    26,  /*     BEFORE => ID */
100844    26,  /*         BY => ID */
100845    26,  /*    CASCADE => ID */
100846    26,  /*       CAST => ID */
100847    26,  /*   COLUMNKW => ID */
100848    26,  /*   CONFLICT => ID */
100849    26,  /*   DATABASE => ID */
100850    26,  /*       DESC => ID */
100851    26,  /*     DETACH => ID */
100852    26,  /*       EACH => ID */
100853    26,  /*       FAIL => ID */
100854    26,  /*        FOR => ID */
100855    26,  /*     IGNORE => ID */
100856    26,  /*  INITIALLY => ID */
100857    26,  /*    INSTEAD => ID */
100858    26,  /*    LIKE_KW => ID */
100859    26,  /*      MATCH => ID */
100860    26,  /*         NO => ID */
100861    26,  /*        KEY => ID */
100862    26,  /*         OF => ID */
100863    26,  /*     OFFSET => ID */
100864    26,  /*     PRAGMA => ID */
100865    26,  /*      RAISE => ID */
100866    26,  /*    REPLACE => ID */
100867    26,  /*   RESTRICT => ID */
100868    26,  /*        ROW => ID */
100869    26,  /*    TRIGGER => ID */
100870    26,  /*     VACUUM => ID */
100871    26,  /*       VIEW => ID */
100872    26,  /*    VIRTUAL => ID */
100873    26,  /*    REINDEX => ID */
100874    26,  /*     RENAME => ID */
100875    26,  /*   CTIME_KW => ID */
100876 };
100877 #endif /* YYFALLBACK */
100878
100879 /* The following structure represents a single element of the
100880 ** parser's stack.  Information stored includes:
100881 **
100882 **   +  The state number for the parser at this level of the stack.
100883 **
100884 **   +  The value of the token stored at this level of the stack.
100885 **      (In other words, the "major" token.)
100886 **
100887 **   +  The semantic value stored at this level of the stack.  This is
100888 **      the information used by the action routines in the grammar.
100889 **      It is sometimes called the "minor" token.
100890 */
100891 struct yyStackEntry {
100892   YYACTIONTYPE stateno;  /* The state-number */
100893   YYCODETYPE major;      /* The major token value.  This is the code
100894                          ** number for the token at this stack level */
100895   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
100896                          ** is the value of the token  */
100897 };
100898 typedef struct yyStackEntry yyStackEntry;
100899
100900 /* The state of the parser is completely contained in an instance of
100901 ** the following structure */
100902 struct yyParser {
100903   int yyidx;                    /* Index of top element in stack */
100904 #ifdef YYTRACKMAXSTACKDEPTH
100905   int yyidxMax;                 /* Maximum value of yyidx */
100906 #endif
100907   int yyerrcnt;                 /* Shifts left before out of the error */
100908   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
100909 #if YYSTACKDEPTH<=0
100910   int yystksz;                  /* Current side of the stack */
100911   yyStackEntry *yystack;        /* The parser's stack */
100912 #else
100913   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
100914 #endif
100915 };
100916 typedef struct yyParser yyParser;
100917
100918 #ifndef NDEBUG
100919 static FILE *yyTraceFILE = 0;
100920 static char *yyTracePrompt = 0;
100921 #endif /* NDEBUG */
100922
100923 #ifndef NDEBUG
100924 /* 
100925 ** Turn parser tracing on by giving a stream to which to write the trace
100926 ** and a prompt to preface each trace message.  Tracing is turned off
100927 ** by making either argument NULL 
100928 **
100929 ** Inputs:
100930 ** <ul>
100931 ** <li> A FILE* to which trace output should be written.
100932 **      If NULL, then tracing is turned off.
100933 ** <li> A prefix string written at the beginning of every
100934 **      line of trace output.  If NULL, then tracing is
100935 **      turned off.
100936 ** </ul>
100937 **
100938 ** Outputs:
100939 ** None.
100940 */
100941 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
100942   yyTraceFILE = TraceFILE;
100943   yyTracePrompt = zTracePrompt;
100944   if( yyTraceFILE==0 ) yyTracePrompt = 0;
100945   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
100946 }
100947 #endif /* NDEBUG */
100948
100949 #ifndef NDEBUG
100950 /* For tracing shifts, the names of all terminals and nonterminals
100951 ** are required.  The following table supplies these names */
100952 static const char *const yyTokenName[] = { 
100953   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
100954   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
100955   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
100956   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
100957   "TABLE",         "CREATE",        "IF",            "NOT",         
100958   "EXISTS",        "TEMP",          "LP",            "RP",          
100959   "AS",            "COMMA",         "ID",            "INDEXED",     
100960   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
100961   "ASC",           "ATTACH",        "BEFORE",        "BY",          
100962   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
100963   "DATABASE",      "DESC",          "DETACH",        "EACH",        
100964   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
100965   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
100966   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
100967   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
100968   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
100969   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
100970   "OR",            "AND",           "IS",            "BETWEEN",     
100971   "IN",            "ISNULL",        "NOTNULL",       "NE",          
100972   "EQ",            "GT",            "LE",            "LT",          
100973   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
100974   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
100975   "STAR",          "SLASH",         "REM",           "CONCAT",      
100976   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
100977   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
100978   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
100979   "ON",            "INSERT",        "DELETE",        "UPDATE",      
100980   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
100981   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
100982   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
100983   "JOIN",          "USING",         "ORDER",         "GROUP",       
100984   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
100985   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
100986   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
100987   "THEN",          "ELSE",          "INDEX",         "ALTER",       
100988   "ADD",           "error",         "input",         "cmdlist",     
100989   "ecmd",          "explain",       "cmdx",          "cmd",         
100990   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
100991   "create_table",  "create_table_args",  "createkw",      "temp",        
100992   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
100993   "select",        "column",        "columnid",      "type",        
100994   "carglist",      "id",            "ids",           "typetoken",   
100995   "typename",      "signed",        "plus_num",      "minus_num",   
100996   "carg",          "ccons",         "term",          "expr",        
100997   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
100998   "refargs",       "defer_subclause",  "refarg",        "refact",      
100999   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
101000   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
101001   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
101002   "distinct",      "selcollist",    "from",          "where_opt",   
101003   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
101004   "sclp",          "as",            "seltablist",    "stl_prefix",  
101005   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
101006   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
101007   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
101008   "itemlist",      "exprlist",      "likeop",        "between_op",  
101009   "in_op",         "case_operand",  "case_exprlist",  "case_else",   
101010   "uniqueflag",    "collate",       "nmnum",         "plus_opt",    
101011   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
101012   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
101013   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
101014   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
101015   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
101016 };
101017 #endif /* NDEBUG */
101018
101019 #ifndef NDEBUG
101020 /* For tracing reduce actions, the names of all rules are required.
101021 */
101022 static const char *const yyRuleName[] = {
101023  /*   0 */ "input ::= cmdlist",
101024  /*   1 */ "cmdlist ::= cmdlist ecmd",
101025  /*   2 */ "cmdlist ::= ecmd",
101026  /*   3 */ "ecmd ::= SEMI",
101027  /*   4 */ "ecmd ::= explain cmdx SEMI",
101028  /*   5 */ "explain ::=",
101029  /*   6 */ "explain ::= EXPLAIN",
101030  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
101031  /*   8 */ "cmdx ::= cmd",
101032  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
101033  /*  10 */ "trans_opt ::=",
101034  /*  11 */ "trans_opt ::= TRANSACTION",
101035  /*  12 */ "trans_opt ::= TRANSACTION nm",
101036  /*  13 */ "transtype ::=",
101037  /*  14 */ "transtype ::= DEFERRED",
101038  /*  15 */ "transtype ::= IMMEDIATE",
101039  /*  16 */ "transtype ::= EXCLUSIVE",
101040  /*  17 */ "cmd ::= COMMIT trans_opt",
101041  /*  18 */ "cmd ::= END trans_opt",
101042  /*  19 */ "cmd ::= ROLLBACK trans_opt",
101043  /*  20 */ "savepoint_opt ::= SAVEPOINT",
101044  /*  21 */ "savepoint_opt ::=",
101045  /*  22 */ "cmd ::= SAVEPOINT nm",
101046  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
101047  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
101048  /*  25 */ "cmd ::= create_table create_table_args",
101049  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
101050  /*  27 */ "createkw ::= CREATE",
101051  /*  28 */ "ifnotexists ::=",
101052  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
101053  /*  30 */ "temp ::= TEMP",
101054  /*  31 */ "temp ::=",
101055  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
101056  /*  33 */ "create_table_args ::= AS select",
101057  /*  34 */ "columnlist ::= columnlist COMMA column",
101058  /*  35 */ "columnlist ::= column",
101059  /*  36 */ "column ::= columnid type carglist",
101060  /*  37 */ "columnid ::= nm",
101061  /*  38 */ "id ::= ID",
101062  /*  39 */ "id ::= INDEXED",
101063  /*  40 */ "ids ::= ID|STRING",
101064  /*  41 */ "nm ::= id",
101065  /*  42 */ "nm ::= STRING",
101066  /*  43 */ "nm ::= JOIN_KW",
101067  /*  44 */ "type ::=",
101068  /*  45 */ "type ::= typetoken",
101069  /*  46 */ "typetoken ::= typename",
101070  /*  47 */ "typetoken ::= typename LP signed RP",
101071  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
101072  /*  49 */ "typename ::= ids",
101073  /*  50 */ "typename ::= typename ids",
101074  /*  51 */ "signed ::= plus_num",
101075  /*  52 */ "signed ::= minus_num",
101076  /*  53 */ "carglist ::= carglist carg",
101077  /*  54 */ "carglist ::=",
101078  /*  55 */ "carg ::= CONSTRAINT nm ccons",
101079  /*  56 */ "carg ::= ccons",
101080  /*  57 */ "ccons ::= DEFAULT term",
101081  /*  58 */ "ccons ::= DEFAULT LP expr RP",
101082  /*  59 */ "ccons ::= DEFAULT PLUS term",
101083  /*  60 */ "ccons ::= DEFAULT MINUS term",
101084  /*  61 */ "ccons ::= DEFAULT id",
101085  /*  62 */ "ccons ::= NULL onconf",
101086  /*  63 */ "ccons ::= NOT NULL onconf",
101087  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
101088  /*  65 */ "ccons ::= UNIQUE onconf",
101089  /*  66 */ "ccons ::= CHECK LP expr RP",
101090  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
101091  /*  68 */ "ccons ::= defer_subclause",
101092  /*  69 */ "ccons ::= COLLATE ids",
101093  /*  70 */ "autoinc ::=",
101094  /*  71 */ "autoinc ::= AUTOINCR",
101095  /*  72 */ "refargs ::=",
101096  /*  73 */ "refargs ::= refargs refarg",
101097  /*  74 */ "refarg ::= MATCH nm",
101098  /*  75 */ "refarg ::= ON INSERT refact",
101099  /*  76 */ "refarg ::= ON DELETE refact",
101100  /*  77 */ "refarg ::= ON UPDATE refact",
101101  /*  78 */ "refact ::= SET NULL",
101102  /*  79 */ "refact ::= SET DEFAULT",
101103  /*  80 */ "refact ::= CASCADE",
101104  /*  81 */ "refact ::= RESTRICT",
101105  /*  82 */ "refact ::= NO ACTION",
101106  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
101107  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
101108  /*  85 */ "init_deferred_pred_opt ::=",
101109  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
101110  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
101111  /*  88 */ "conslist_opt ::=",
101112  /*  89 */ "conslist_opt ::= COMMA conslist",
101113  /*  90 */ "conslist ::= conslist COMMA tcons",
101114  /*  91 */ "conslist ::= conslist tcons",
101115  /*  92 */ "conslist ::= tcons",
101116  /*  93 */ "tcons ::= CONSTRAINT nm",
101117  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
101118  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
101119  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
101120  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
101121  /*  98 */ "defer_subclause_opt ::=",
101122  /*  99 */ "defer_subclause_opt ::= defer_subclause",
101123  /* 100 */ "onconf ::=",
101124  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
101125  /* 102 */ "orconf ::=",
101126  /* 103 */ "orconf ::= OR resolvetype",
101127  /* 104 */ "resolvetype ::= raisetype",
101128  /* 105 */ "resolvetype ::= IGNORE",
101129  /* 106 */ "resolvetype ::= REPLACE",
101130  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
101131  /* 108 */ "ifexists ::= IF EXISTS",
101132  /* 109 */ "ifexists ::=",
101133  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
101134  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
101135  /* 112 */ "cmd ::= select",
101136  /* 113 */ "select ::= oneselect",
101137  /* 114 */ "select ::= select multiselect_op oneselect",
101138  /* 115 */ "multiselect_op ::= UNION",
101139  /* 116 */ "multiselect_op ::= UNION ALL",
101140  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
101141  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
101142  /* 119 */ "distinct ::= DISTINCT",
101143  /* 120 */ "distinct ::= ALL",
101144  /* 121 */ "distinct ::=",
101145  /* 122 */ "sclp ::= selcollist COMMA",
101146  /* 123 */ "sclp ::=",
101147  /* 124 */ "selcollist ::= sclp expr as",
101148  /* 125 */ "selcollist ::= sclp STAR",
101149  /* 126 */ "selcollist ::= sclp nm DOT STAR",
101150  /* 127 */ "as ::= AS nm",
101151  /* 128 */ "as ::= ids",
101152  /* 129 */ "as ::=",
101153  /* 130 */ "from ::=",
101154  /* 131 */ "from ::= FROM seltablist",
101155  /* 132 */ "stl_prefix ::= seltablist joinop",
101156  /* 133 */ "stl_prefix ::=",
101157  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
101158  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
101159  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
101160  /* 137 */ "dbnm ::=",
101161  /* 138 */ "dbnm ::= DOT nm",
101162  /* 139 */ "fullname ::= nm dbnm",
101163  /* 140 */ "joinop ::= COMMA|JOIN",
101164  /* 141 */ "joinop ::= JOIN_KW JOIN",
101165  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
101166  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
101167  /* 144 */ "on_opt ::= ON expr",
101168  /* 145 */ "on_opt ::=",
101169  /* 146 */ "indexed_opt ::=",
101170  /* 147 */ "indexed_opt ::= INDEXED BY nm",
101171  /* 148 */ "indexed_opt ::= NOT INDEXED",
101172  /* 149 */ "using_opt ::= USING LP inscollist RP",
101173  /* 150 */ "using_opt ::=",
101174  /* 151 */ "orderby_opt ::=",
101175  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
101176  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
101177  /* 154 */ "sortlist ::= sortitem sortorder",
101178  /* 155 */ "sortitem ::= expr",
101179  /* 156 */ "sortorder ::= ASC",
101180  /* 157 */ "sortorder ::= DESC",
101181  /* 158 */ "sortorder ::=",
101182  /* 159 */ "groupby_opt ::=",
101183  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
101184  /* 161 */ "having_opt ::=",
101185  /* 162 */ "having_opt ::= HAVING expr",
101186  /* 163 */ "limit_opt ::=",
101187  /* 164 */ "limit_opt ::= LIMIT expr",
101188  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
101189  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
101190  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
101191  /* 168 */ "where_opt ::=",
101192  /* 169 */ "where_opt ::= WHERE expr",
101193  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
101194  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
101195  /* 172 */ "setlist ::= nm EQ expr",
101196  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
101197  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
101198  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
101199  /* 176 */ "insert_cmd ::= INSERT orconf",
101200  /* 177 */ "insert_cmd ::= REPLACE",
101201  /* 178 */ "itemlist ::= itemlist COMMA expr",
101202  /* 179 */ "itemlist ::= expr",
101203  /* 180 */ "inscollist_opt ::=",
101204  /* 181 */ "inscollist_opt ::= LP inscollist RP",
101205  /* 182 */ "inscollist ::= inscollist COMMA nm",
101206  /* 183 */ "inscollist ::= nm",
101207  /* 184 */ "expr ::= term",
101208  /* 185 */ "expr ::= LP expr RP",
101209  /* 186 */ "term ::= NULL",
101210  /* 187 */ "expr ::= id",
101211  /* 188 */ "expr ::= JOIN_KW",
101212  /* 189 */ "expr ::= nm DOT nm",
101213  /* 190 */ "expr ::= nm DOT nm DOT nm",
101214  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
101215  /* 192 */ "term ::= STRING",
101216  /* 193 */ "expr ::= REGISTER",
101217  /* 194 */ "expr ::= VARIABLE",
101218  /* 195 */ "expr ::= expr COLLATE ids",
101219  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
101220  /* 197 */ "expr ::= ID LP distinct exprlist RP",
101221  /* 198 */ "expr ::= ID LP STAR RP",
101222  /* 199 */ "term ::= CTIME_KW",
101223  /* 200 */ "expr ::= expr AND expr",
101224  /* 201 */ "expr ::= expr OR expr",
101225  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
101226  /* 203 */ "expr ::= expr EQ|NE expr",
101227  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
101228  /* 205 */ "expr ::= expr PLUS|MINUS expr",
101229  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
101230  /* 207 */ "expr ::= expr CONCAT expr",
101231  /* 208 */ "likeop ::= LIKE_KW",
101232  /* 209 */ "likeop ::= NOT LIKE_KW",
101233  /* 210 */ "likeop ::= MATCH",
101234  /* 211 */ "likeop ::= NOT MATCH",
101235  /* 212 */ "expr ::= expr likeop expr",
101236  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
101237  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
101238  /* 215 */ "expr ::= expr NOT NULL",
101239  /* 216 */ "expr ::= expr IS expr",
101240  /* 217 */ "expr ::= expr IS NOT expr",
101241  /* 218 */ "expr ::= NOT expr",
101242  /* 219 */ "expr ::= BITNOT expr",
101243  /* 220 */ "expr ::= MINUS expr",
101244  /* 221 */ "expr ::= PLUS expr",
101245  /* 222 */ "between_op ::= BETWEEN",
101246  /* 223 */ "between_op ::= NOT BETWEEN",
101247  /* 224 */ "expr ::= expr between_op expr AND expr",
101248  /* 225 */ "in_op ::= IN",
101249  /* 226 */ "in_op ::= NOT IN",
101250  /* 227 */ "expr ::= expr in_op LP exprlist RP",
101251  /* 228 */ "expr ::= LP select RP",
101252  /* 229 */ "expr ::= expr in_op LP select RP",
101253  /* 230 */ "expr ::= expr in_op nm dbnm",
101254  /* 231 */ "expr ::= EXISTS LP select RP",
101255  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
101256  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
101257  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
101258  /* 235 */ "case_else ::= ELSE expr",
101259  /* 236 */ "case_else ::=",
101260  /* 237 */ "case_operand ::= expr",
101261  /* 238 */ "case_operand ::=",
101262  /* 239 */ "exprlist ::= nexprlist",
101263  /* 240 */ "exprlist ::=",
101264  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
101265  /* 242 */ "nexprlist ::= expr",
101266  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
101267  /* 244 */ "uniqueflag ::= UNIQUE",
101268  /* 245 */ "uniqueflag ::=",
101269  /* 246 */ "idxlist_opt ::=",
101270  /* 247 */ "idxlist_opt ::= LP idxlist RP",
101271  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
101272  /* 249 */ "idxlist ::= nm collate sortorder",
101273  /* 250 */ "collate ::=",
101274  /* 251 */ "collate ::= COLLATE ids",
101275  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
101276  /* 253 */ "cmd ::= VACUUM",
101277  /* 254 */ "cmd ::= VACUUM nm",
101278  /* 255 */ "cmd ::= PRAGMA nm dbnm",
101279  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
101280  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
101281  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
101282  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
101283  /* 260 */ "nmnum ::= plus_num",
101284  /* 261 */ "nmnum ::= nm",
101285  /* 262 */ "nmnum ::= ON",
101286  /* 263 */ "nmnum ::= DELETE",
101287  /* 264 */ "nmnum ::= DEFAULT",
101288  /* 265 */ "plus_num ::= plus_opt number",
101289  /* 266 */ "minus_num ::= MINUS number",
101290  /* 267 */ "number ::= INTEGER|FLOAT",
101291  /* 268 */ "plus_opt ::= PLUS",
101292  /* 269 */ "plus_opt ::=",
101293  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
101294  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
101295  /* 272 */ "trigger_time ::= BEFORE",
101296  /* 273 */ "trigger_time ::= AFTER",
101297  /* 274 */ "trigger_time ::= INSTEAD OF",
101298  /* 275 */ "trigger_time ::=",
101299  /* 276 */ "trigger_event ::= DELETE|INSERT",
101300  /* 277 */ "trigger_event ::= UPDATE",
101301  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
101302  /* 279 */ "foreach_clause ::=",
101303  /* 280 */ "foreach_clause ::= FOR EACH ROW",
101304  /* 281 */ "when_clause ::=",
101305  /* 282 */ "when_clause ::= WHEN expr",
101306  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
101307  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
101308  /* 285 */ "trnm ::= nm",
101309  /* 286 */ "trnm ::= nm DOT nm",
101310  /* 287 */ "tridxby ::=",
101311  /* 288 */ "tridxby ::= INDEXED BY nm",
101312  /* 289 */ "tridxby ::= NOT INDEXED",
101313  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
101314  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
101315  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
101316  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
101317  /* 294 */ "trigger_cmd ::= select",
101318  /* 295 */ "expr ::= RAISE LP IGNORE RP",
101319  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
101320  /* 297 */ "raisetype ::= ROLLBACK",
101321  /* 298 */ "raisetype ::= ABORT",
101322  /* 299 */ "raisetype ::= FAIL",
101323  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
101324  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
101325  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
101326  /* 303 */ "key_opt ::=",
101327  /* 304 */ "key_opt ::= KEY expr",
101328  /* 305 */ "database_kw_opt ::= DATABASE",
101329  /* 306 */ "database_kw_opt ::=",
101330  /* 307 */ "cmd ::= REINDEX",
101331  /* 308 */ "cmd ::= REINDEX nm dbnm",
101332  /* 309 */ "cmd ::= ANALYZE",
101333  /* 310 */ "cmd ::= ANALYZE nm dbnm",
101334  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
101335  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
101336  /* 313 */ "add_column_fullname ::= fullname",
101337  /* 314 */ "kwcolumn_opt ::=",
101338  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
101339  /* 316 */ "cmd ::= create_vtab",
101340  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
101341  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
101342  /* 319 */ "vtabarglist ::= vtabarg",
101343  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
101344  /* 321 */ "vtabarg ::=",
101345  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
101346  /* 323 */ "vtabargtoken ::= ANY",
101347  /* 324 */ "vtabargtoken ::= lp anylist RP",
101348  /* 325 */ "lp ::= LP",
101349  /* 326 */ "anylist ::=",
101350  /* 327 */ "anylist ::= anylist LP anylist RP",
101351  /* 328 */ "anylist ::= anylist ANY",
101352 };
101353 #endif /* NDEBUG */
101354
101355
101356 #if YYSTACKDEPTH<=0
101357 /*
101358 ** Try to increase the size of the parser stack.
101359 */
101360 static void yyGrowStack(yyParser *p){
101361   int newSize;
101362   yyStackEntry *pNew;
101363
101364   newSize = p->yystksz*2 + 100;
101365   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
101366   if( pNew ){
101367     p->yystack = pNew;
101368     p->yystksz = newSize;
101369 #ifndef NDEBUG
101370     if( yyTraceFILE ){
101371       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
101372               yyTracePrompt, p->yystksz);
101373     }
101374 #endif
101375   }
101376 }
101377 #endif
101378
101379 /* 
101380 ** This function allocates a new parser.
101381 ** The only argument is a pointer to a function which works like
101382 ** malloc.
101383 **
101384 ** Inputs:
101385 ** A pointer to the function used to allocate memory.
101386 **
101387 ** Outputs:
101388 ** A pointer to a parser.  This pointer is used in subsequent calls
101389 ** to sqlite3Parser and sqlite3ParserFree.
101390 */
101391 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
101392   yyParser *pParser;
101393   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
101394   if( pParser ){
101395     pParser->yyidx = -1;
101396 #ifdef YYTRACKMAXSTACKDEPTH
101397     pParser->yyidxMax = 0;
101398 #endif
101399 #if YYSTACKDEPTH<=0
101400     pParser->yystack = NULL;
101401     pParser->yystksz = 0;
101402     yyGrowStack(pParser);
101403 #endif
101404   }
101405   return pParser;
101406 }
101407
101408 /* The following function deletes the value associated with a
101409 ** symbol.  The symbol can be either a terminal or nonterminal.
101410 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
101411 ** the value.
101412 */
101413 static void yy_destructor(
101414   yyParser *yypParser,    /* The parser */
101415   YYCODETYPE yymajor,     /* Type code for object to destroy */
101416   YYMINORTYPE *yypminor   /* The object to be destroyed */
101417 ){
101418   sqlite3ParserARG_FETCH;
101419   switch( yymajor ){
101420     /* Here is inserted the actions which take place when a
101421     ** terminal or non-terminal is destroyed.  This can happen
101422     ** when the symbol is popped from the stack during a
101423     ** reduce or during error processing or when a parser is 
101424     ** being destroyed before it is finished parsing.
101425     **
101426     ** Note: during a reduce, the only symbols destroyed are those
101427     ** which appear on the RHS of the rule, but which are not used
101428     ** inside the C code.
101429     */
101430     case 160: /* select */
101431     case 194: /* oneselect */
101432 {
101433 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
101434 }
101435       break;
101436     case 174: /* term */
101437     case 175: /* expr */
101438 {
101439 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
101440 }
101441       break;
101442     case 179: /* idxlist_opt */
101443     case 187: /* idxlist */
101444     case 197: /* selcollist */
101445     case 200: /* groupby_opt */
101446     case 202: /* orderby_opt */
101447     case 204: /* sclp */
101448     case 214: /* sortlist */
101449     case 216: /* nexprlist */
101450     case 217: /* setlist */
101451     case 220: /* itemlist */
101452     case 221: /* exprlist */
101453     case 226: /* case_exprlist */
101454 {
101455 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
101456 }
101457       break;
101458     case 193: /* fullname */
101459     case 198: /* from */
101460     case 206: /* seltablist */
101461     case 207: /* stl_prefix */
101462 {
101463 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
101464 }
101465       break;
101466     case 199: /* where_opt */
101467     case 201: /* having_opt */
101468     case 210: /* on_opt */
101469     case 215: /* sortitem */
101470     case 225: /* case_operand */
101471     case 227: /* case_else */
101472     case 238: /* when_clause */
101473     case 243: /* key_opt */
101474 {
101475 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
101476 }
101477       break;
101478     case 211: /* using_opt */
101479     case 213: /* inscollist */
101480     case 219: /* inscollist_opt */
101481 {
101482 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
101483 }
101484       break;
101485     case 234: /* trigger_cmd_list */
101486     case 239: /* trigger_cmd */
101487 {
101488 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
101489 }
101490       break;
101491     case 236: /* trigger_event */
101492 {
101493 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
101494 }
101495       break;
101496     default:  break;   /* If no destructor action specified: do nothing */
101497   }
101498 }
101499
101500 /*
101501 ** Pop the parser's stack once.
101502 **
101503 ** If there is a destructor routine associated with the token which
101504 ** is popped from the stack, then call it.
101505 **
101506 ** Return the major token number for the symbol popped.
101507 */
101508 static int yy_pop_parser_stack(yyParser *pParser){
101509   YYCODETYPE yymajor;
101510   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
101511
101512   /* There is no mechanism by which the parser stack can be popped below
101513   ** empty in SQLite.  */
101514   if( NEVER(pParser->yyidx<0) ) return 0;
101515 #ifndef NDEBUG
101516   if( yyTraceFILE && pParser->yyidx>=0 ){
101517     fprintf(yyTraceFILE,"%sPopping %s\n",
101518       yyTracePrompt,
101519       yyTokenName[yytos->major]);
101520   }
101521 #endif
101522   yymajor = yytos->major;
101523   yy_destructor(pParser, yymajor, &yytos->minor);
101524   pParser->yyidx--;
101525   return yymajor;
101526 }
101527
101528 /* 
101529 ** Deallocate and destroy a parser.  Destructors are all called for
101530 ** all stack elements before shutting the parser down.
101531 **
101532 ** Inputs:
101533 ** <ul>
101534 ** <li>  A pointer to the parser.  This should be a pointer
101535 **       obtained from sqlite3ParserAlloc.
101536 ** <li>  A pointer to a function used to reclaim memory obtained
101537 **       from malloc.
101538 ** </ul>
101539 */
101540 SQLITE_PRIVATE void sqlite3ParserFree(
101541   void *p,                    /* The parser to be deleted */
101542   void (*freeProc)(void*)     /* Function used to reclaim memory */
101543 ){
101544   yyParser *pParser = (yyParser*)p;
101545   /* In SQLite, we never try to destroy a parser that was not successfully
101546   ** created in the first place. */
101547   if( NEVER(pParser==0) ) return;
101548   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
101549 #if YYSTACKDEPTH<=0
101550   free(pParser->yystack);
101551 #endif
101552   (*freeProc)((void*)pParser);
101553 }
101554
101555 /*
101556 ** Return the peak depth of the stack for a parser.
101557 */
101558 #ifdef YYTRACKMAXSTACKDEPTH
101559 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
101560   yyParser *pParser = (yyParser*)p;
101561   return pParser->yyidxMax;
101562 }
101563 #endif
101564
101565 /*
101566 ** Find the appropriate action for a parser given the terminal
101567 ** look-ahead token iLookAhead.
101568 **
101569 ** If the look-ahead token is YYNOCODE, then check to see if the action is
101570 ** independent of the look-ahead.  If it is, return the action, otherwise
101571 ** return YY_NO_ACTION.
101572 */
101573 static int yy_find_shift_action(
101574   yyParser *pParser,        /* The parser */
101575   YYCODETYPE iLookAhead     /* The look-ahead token */
101576 ){
101577   int i;
101578   int stateno = pParser->yystack[pParser->yyidx].stateno;
101579  
101580   if( stateno>YY_SHIFT_COUNT
101581    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
101582     return yy_default[stateno];
101583   }
101584   assert( iLookAhead!=YYNOCODE );
101585   i += iLookAhead;
101586   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
101587     if( iLookAhead>0 ){
101588 #ifdef YYFALLBACK
101589       YYCODETYPE iFallback;            /* Fallback token */
101590       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
101591              && (iFallback = yyFallback[iLookAhead])!=0 ){
101592 #ifndef NDEBUG
101593         if( yyTraceFILE ){
101594           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
101595              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
101596         }
101597 #endif
101598         return yy_find_shift_action(pParser, iFallback);
101599       }
101600 #endif
101601 #ifdef YYWILDCARD
101602       {
101603         int j = i - iLookAhead + YYWILDCARD;
101604         if( 
101605 #if YY_SHIFT_MIN+YYWILDCARD<0
101606           j>=0 &&
101607 #endif
101608 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
101609           j<YY_ACTTAB_COUNT &&
101610 #endif
101611           yy_lookahead[j]==YYWILDCARD
101612         ){
101613 #ifndef NDEBUG
101614           if( yyTraceFILE ){
101615             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
101616                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
101617           }
101618 #endif /* NDEBUG */
101619           return yy_action[j];
101620         }
101621       }
101622 #endif /* YYWILDCARD */
101623     }
101624     return yy_default[stateno];
101625   }else{
101626     return yy_action[i];
101627   }
101628 }
101629
101630 /*
101631 ** Find the appropriate action for a parser given the non-terminal
101632 ** look-ahead token iLookAhead.
101633 **
101634 ** If the look-ahead token is YYNOCODE, then check to see if the action is
101635 ** independent of the look-ahead.  If it is, return the action, otherwise
101636 ** return YY_NO_ACTION.
101637 */
101638 static int yy_find_reduce_action(
101639   int stateno,              /* Current state number */
101640   YYCODETYPE iLookAhead     /* The look-ahead token */
101641 ){
101642   int i;
101643 #ifdef YYERRORSYMBOL
101644   if( stateno>YY_REDUCE_COUNT ){
101645     return yy_default[stateno];
101646   }
101647 #else
101648   assert( stateno<=YY_REDUCE_COUNT );
101649 #endif
101650   i = yy_reduce_ofst[stateno];
101651   assert( i!=YY_REDUCE_USE_DFLT );
101652   assert( iLookAhead!=YYNOCODE );
101653   i += iLookAhead;
101654 #ifdef YYERRORSYMBOL
101655   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
101656     return yy_default[stateno];
101657   }
101658 #else
101659   assert( i>=0 && i<YY_ACTTAB_COUNT );
101660   assert( yy_lookahead[i]==iLookAhead );
101661 #endif
101662   return yy_action[i];
101663 }
101664
101665 /*
101666 ** The following routine is called if the stack overflows.
101667 */
101668 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
101669    sqlite3ParserARG_FETCH;
101670    yypParser->yyidx--;
101671 #ifndef NDEBUG
101672    if( yyTraceFILE ){
101673      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
101674    }
101675 #endif
101676    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
101677    /* Here code is inserted which will execute if the parser
101678    ** stack every overflows */
101679
101680   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
101681   sqlite3ErrorMsg(pParse, "parser stack overflow");
101682   pParse->parseError = 1;
101683    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
101684 }
101685
101686 /*
101687 ** Perform a shift action.
101688 */
101689 static void yy_shift(
101690   yyParser *yypParser,          /* The parser to be shifted */
101691   int yyNewState,               /* The new state to shift in */
101692   int yyMajor,                  /* The major token to shift in */
101693   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
101694 ){
101695   yyStackEntry *yytos;
101696   yypParser->yyidx++;
101697 #ifdef YYTRACKMAXSTACKDEPTH
101698   if( yypParser->yyidx>yypParser->yyidxMax ){
101699     yypParser->yyidxMax = yypParser->yyidx;
101700   }
101701 #endif
101702 #if YYSTACKDEPTH>0 
101703   if( yypParser->yyidx>=YYSTACKDEPTH ){
101704     yyStackOverflow(yypParser, yypMinor);
101705     return;
101706   }
101707 #else
101708   if( yypParser->yyidx>=yypParser->yystksz ){
101709     yyGrowStack(yypParser);
101710     if( yypParser->yyidx>=yypParser->yystksz ){
101711       yyStackOverflow(yypParser, yypMinor);
101712       return;
101713     }
101714   }
101715 #endif
101716   yytos = &yypParser->yystack[yypParser->yyidx];
101717   yytos->stateno = (YYACTIONTYPE)yyNewState;
101718   yytos->major = (YYCODETYPE)yyMajor;
101719   yytos->minor = *yypMinor;
101720 #ifndef NDEBUG
101721   if( yyTraceFILE && yypParser->yyidx>0 ){
101722     int i;
101723     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
101724     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
101725     for(i=1; i<=yypParser->yyidx; i++)
101726       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
101727     fprintf(yyTraceFILE,"\n");
101728   }
101729 #endif
101730 }
101731
101732 /* The following table contains information about every rule that
101733 ** is used during the reduce.
101734 */
101735 static const struct {
101736   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
101737   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
101738 } yyRuleInfo[] = {
101739   { 142, 1 },
101740   { 143, 2 },
101741   { 143, 1 },
101742   { 144, 1 },
101743   { 144, 3 },
101744   { 145, 0 },
101745   { 145, 1 },
101746   { 145, 3 },
101747   { 146, 1 },
101748   { 147, 3 },
101749   { 149, 0 },
101750   { 149, 1 },
101751   { 149, 2 },
101752   { 148, 0 },
101753   { 148, 1 },
101754   { 148, 1 },
101755   { 148, 1 },
101756   { 147, 2 },
101757   { 147, 2 },
101758   { 147, 2 },
101759   { 151, 1 },
101760   { 151, 0 },
101761   { 147, 2 },
101762   { 147, 3 },
101763   { 147, 5 },
101764   { 147, 2 },
101765   { 152, 6 },
101766   { 154, 1 },
101767   { 156, 0 },
101768   { 156, 3 },
101769   { 155, 1 },
101770   { 155, 0 },
101771   { 153, 4 },
101772   { 153, 2 },
101773   { 158, 3 },
101774   { 158, 1 },
101775   { 161, 3 },
101776   { 162, 1 },
101777   { 165, 1 },
101778   { 165, 1 },
101779   { 166, 1 },
101780   { 150, 1 },
101781   { 150, 1 },
101782   { 150, 1 },
101783   { 163, 0 },
101784   { 163, 1 },
101785   { 167, 1 },
101786   { 167, 4 },
101787   { 167, 6 },
101788   { 168, 1 },
101789   { 168, 2 },
101790   { 169, 1 },
101791   { 169, 1 },
101792   { 164, 2 },
101793   { 164, 0 },
101794   { 172, 3 },
101795   { 172, 1 },
101796   { 173, 2 },
101797   { 173, 4 },
101798   { 173, 3 },
101799   { 173, 3 },
101800   { 173, 2 },
101801   { 173, 2 },
101802   { 173, 3 },
101803   { 173, 5 },
101804   { 173, 2 },
101805   { 173, 4 },
101806   { 173, 4 },
101807   { 173, 1 },
101808   { 173, 2 },
101809   { 178, 0 },
101810   { 178, 1 },
101811   { 180, 0 },
101812   { 180, 2 },
101813   { 182, 2 },
101814   { 182, 3 },
101815   { 182, 3 },
101816   { 182, 3 },
101817   { 183, 2 },
101818   { 183, 2 },
101819   { 183, 1 },
101820   { 183, 1 },
101821   { 183, 2 },
101822   { 181, 3 },
101823   { 181, 2 },
101824   { 184, 0 },
101825   { 184, 2 },
101826   { 184, 2 },
101827   { 159, 0 },
101828   { 159, 2 },
101829   { 185, 3 },
101830   { 185, 2 },
101831   { 185, 1 },
101832   { 186, 2 },
101833   { 186, 7 },
101834   { 186, 5 },
101835   { 186, 5 },
101836   { 186, 10 },
101837   { 188, 0 },
101838   { 188, 1 },
101839   { 176, 0 },
101840   { 176, 3 },
101841   { 189, 0 },
101842   { 189, 2 },
101843   { 190, 1 },
101844   { 190, 1 },
101845   { 190, 1 },
101846   { 147, 4 },
101847   { 192, 2 },
101848   { 192, 0 },
101849   { 147, 8 },
101850   { 147, 4 },
101851   { 147, 1 },
101852   { 160, 1 },
101853   { 160, 3 },
101854   { 195, 1 },
101855   { 195, 2 },
101856   { 195, 1 },
101857   { 194, 9 },
101858   { 196, 1 },
101859   { 196, 1 },
101860   { 196, 0 },
101861   { 204, 2 },
101862   { 204, 0 },
101863   { 197, 3 },
101864   { 197, 2 },
101865   { 197, 4 },
101866   { 205, 2 },
101867   { 205, 1 },
101868   { 205, 0 },
101869   { 198, 0 },
101870   { 198, 2 },
101871   { 207, 2 },
101872   { 207, 0 },
101873   { 206, 7 },
101874   { 206, 7 },
101875   { 206, 7 },
101876   { 157, 0 },
101877   { 157, 2 },
101878   { 193, 2 },
101879   { 208, 1 },
101880   { 208, 2 },
101881   { 208, 3 },
101882   { 208, 4 },
101883   { 210, 2 },
101884   { 210, 0 },
101885   { 209, 0 },
101886   { 209, 3 },
101887   { 209, 2 },
101888   { 211, 4 },
101889   { 211, 0 },
101890   { 202, 0 },
101891   { 202, 3 },
101892   { 214, 4 },
101893   { 214, 2 },
101894   { 215, 1 },
101895   { 177, 1 },
101896   { 177, 1 },
101897   { 177, 0 },
101898   { 200, 0 },
101899   { 200, 3 },
101900   { 201, 0 },
101901   { 201, 2 },
101902   { 203, 0 },
101903   { 203, 2 },
101904   { 203, 4 },
101905   { 203, 4 },
101906   { 147, 5 },
101907   { 199, 0 },
101908   { 199, 2 },
101909   { 147, 7 },
101910   { 217, 5 },
101911   { 217, 3 },
101912   { 147, 8 },
101913   { 147, 5 },
101914   { 147, 6 },
101915   { 218, 2 },
101916   { 218, 1 },
101917   { 220, 3 },
101918   { 220, 1 },
101919   { 219, 0 },
101920   { 219, 3 },
101921   { 213, 3 },
101922   { 213, 1 },
101923   { 175, 1 },
101924   { 175, 3 },
101925   { 174, 1 },
101926   { 175, 1 },
101927   { 175, 1 },
101928   { 175, 3 },
101929   { 175, 5 },
101930   { 174, 1 },
101931   { 174, 1 },
101932   { 175, 1 },
101933   { 175, 1 },
101934   { 175, 3 },
101935   { 175, 6 },
101936   { 175, 5 },
101937   { 175, 4 },
101938   { 174, 1 },
101939   { 175, 3 },
101940   { 175, 3 },
101941   { 175, 3 },
101942   { 175, 3 },
101943   { 175, 3 },
101944   { 175, 3 },
101945   { 175, 3 },
101946   { 175, 3 },
101947   { 222, 1 },
101948   { 222, 2 },
101949   { 222, 1 },
101950   { 222, 2 },
101951   { 175, 3 },
101952   { 175, 5 },
101953   { 175, 2 },
101954   { 175, 3 },
101955   { 175, 3 },
101956   { 175, 4 },
101957   { 175, 2 },
101958   { 175, 2 },
101959   { 175, 2 },
101960   { 175, 2 },
101961   { 223, 1 },
101962   { 223, 2 },
101963   { 175, 5 },
101964   { 224, 1 },
101965   { 224, 2 },
101966   { 175, 5 },
101967   { 175, 3 },
101968   { 175, 5 },
101969   { 175, 4 },
101970   { 175, 4 },
101971   { 175, 5 },
101972   { 226, 5 },
101973   { 226, 4 },
101974   { 227, 2 },
101975   { 227, 0 },
101976   { 225, 1 },
101977   { 225, 0 },
101978   { 221, 1 },
101979   { 221, 0 },
101980   { 216, 3 },
101981   { 216, 1 },
101982   { 147, 11 },
101983   { 228, 1 },
101984   { 228, 0 },
101985   { 179, 0 },
101986   { 179, 3 },
101987   { 187, 5 },
101988   { 187, 3 },
101989   { 229, 0 },
101990   { 229, 2 },
101991   { 147, 4 },
101992   { 147, 1 },
101993   { 147, 2 },
101994   { 147, 3 },
101995   { 147, 5 },
101996   { 147, 6 },
101997   { 147, 5 },
101998   { 147, 6 },
101999   { 230, 1 },
102000   { 230, 1 },
102001   { 230, 1 },
102002   { 230, 1 },
102003   { 230, 1 },
102004   { 170, 2 },
102005   { 171, 2 },
102006   { 232, 1 },
102007   { 231, 1 },
102008   { 231, 0 },
102009   { 147, 5 },
102010   { 233, 11 },
102011   { 235, 1 },
102012   { 235, 1 },
102013   { 235, 2 },
102014   { 235, 0 },
102015   { 236, 1 },
102016   { 236, 1 },
102017   { 236, 3 },
102018   { 237, 0 },
102019   { 237, 3 },
102020   { 238, 0 },
102021   { 238, 2 },
102022   { 234, 3 },
102023   { 234, 2 },
102024   { 240, 1 },
102025   { 240, 3 },
102026   { 241, 0 },
102027   { 241, 3 },
102028   { 241, 2 },
102029   { 239, 7 },
102030   { 239, 8 },
102031   { 239, 5 },
102032   { 239, 5 },
102033   { 239, 1 },
102034   { 175, 4 },
102035   { 175, 6 },
102036   { 191, 1 },
102037   { 191, 1 },
102038   { 191, 1 },
102039   { 147, 4 },
102040   { 147, 6 },
102041   { 147, 3 },
102042   { 243, 0 },
102043   { 243, 2 },
102044   { 242, 1 },
102045   { 242, 0 },
102046   { 147, 1 },
102047   { 147, 3 },
102048   { 147, 1 },
102049   { 147, 3 },
102050   { 147, 6 },
102051   { 147, 6 },
102052   { 244, 1 },
102053   { 245, 0 },
102054   { 245, 1 },
102055   { 147, 1 },
102056   { 147, 4 },
102057   { 246, 7 },
102058   { 247, 1 },
102059   { 247, 3 },
102060   { 248, 0 },
102061   { 248, 2 },
102062   { 249, 1 },
102063   { 249, 3 },
102064   { 250, 1 },
102065   { 251, 0 },
102066   { 251, 4 },
102067   { 251, 2 },
102068 };
102069
102070 static void yy_accept(yyParser*);  /* Forward Declaration */
102071
102072 /*
102073 ** Perform a reduce action and the shift that must immediately
102074 ** follow the reduce.
102075 */
102076 static void yy_reduce(
102077   yyParser *yypParser,         /* The parser */
102078   int yyruleno                 /* Number of the rule by which to reduce */
102079 ){
102080   int yygoto;                     /* The next state */
102081   int yyact;                      /* The next action */
102082   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
102083   yyStackEntry *yymsp;            /* The top of the parser's stack */
102084   int yysize;                     /* Amount to pop the stack */
102085   sqlite3ParserARG_FETCH;
102086   yymsp = &yypParser->yystack[yypParser->yyidx];
102087 #ifndef NDEBUG
102088   if( yyTraceFILE && yyruleno>=0 
102089         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
102090     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
102091       yyRuleName[yyruleno]);
102092   }
102093 #endif /* NDEBUG */
102094
102095   /* Silence complaints from purify about yygotominor being uninitialized
102096   ** in some cases when it is copied into the stack after the following
102097   ** switch.  yygotominor is uninitialized when a rule reduces that does
102098   ** not set the value of its left-hand side nonterminal.  Leaving the
102099   ** value of the nonterminal uninitialized is utterly harmless as long
102100   ** as the value is never used.  So really the only thing this code
102101   ** accomplishes is to quieten purify.  
102102   **
102103   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
102104   ** without this code, their parser segfaults.  I'm not sure what there
102105   ** parser is doing to make this happen.  This is the second bug report
102106   ** from wireshark this week.  Clearly they are stressing Lemon in ways
102107   ** that it has not been previously stressed...  (SQLite ticket #2172)
102108   */
102109   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
102110   yygotominor = yyzerominor;
102111
102112
102113   switch( yyruleno ){
102114   /* Beginning here are the reduction cases.  A typical example
102115   ** follows:
102116   **   case 0:
102117   **  #line <lineno> <grammarfile>
102118   **     { ... }           // User supplied code
102119   **  #line <lineno> <thisfile>
102120   **     break;
102121   */
102122       case 5: /* explain ::= */
102123 { sqlite3BeginParse(pParse, 0); }
102124         break;
102125       case 6: /* explain ::= EXPLAIN */
102126 { sqlite3BeginParse(pParse, 1); }
102127         break;
102128       case 7: /* explain ::= EXPLAIN QUERY PLAN */
102129 { sqlite3BeginParse(pParse, 2); }
102130         break;
102131       case 8: /* cmdx ::= cmd */
102132 { sqlite3FinishCoding(pParse); }
102133         break;
102134       case 9: /* cmd ::= BEGIN transtype trans_opt */
102135 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
102136         break;
102137       case 13: /* transtype ::= */
102138 {yygotominor.yy4 = TK_DEFERRED;}
102139         break;
102140       case 14: /* transtype ::= DEFERRED */
102141       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
102142       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
102143       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
102144       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
102145 {yygotominor.yy4 = yymsp[0].major;}
102146         break;
102147       case 17: /* cmd ::= COMMIT trans_opt */
102148       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
102149 {sqlite3CommitTransaction(pParse);}
102150         break;
102151       case 19: /* cmd ::= ROLLBACK trans_opt */
102152 {sqlite3RollbackTransaction(pParse);}
102153         break;
102154       case 22: /* cmd ::= SAVEPOINT nm */
102155 {
102156   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
102157 }
102158         break;
102159       case 23: /* cmd ::= RELEASE savepoint_opt nm */
102160 {
102161   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
102162 }
102163         break;
102164       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
102165 {
102166   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
102167 }
102168         break;
102169       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
102170 {
102171    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
102172 }
102173         break;
102174       case 27: /* createkw ::= CREATE */
102175 {
102176   pParse->db->lookaside.bEnabled = 0;
102177   yygotominor.yy0 = yymsp[0].minor.yy0;
102178 }
102179         break;
102180       case 28: /* ifnotexists ::= */
102181       case 31: /* temp ::= */ yytestcase(yyruleno==31);
102182       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
102183       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
102184       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
102185       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
102186       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
102187       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
102188       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
102189       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
102190       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
102191       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
102192 {yygotominor.yy4 = 0;}
102193         break;
102194       case 29: /* ifnotexists ::= IF NOT EXISTS */
102195       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
102196       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
102197       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
102198       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
102199       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
102200       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
102201       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
102202 {yygotominor.yy4 = 1;}
102203         break;
102204       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
102205 {
102206   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
102207 }
102208         break;
102209       case 33: /* create_table_args ::= AS select */
102210 {
102211   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
102212   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
102213 }
102214         break;
102215       case 36: /* column ::= columnid type carglist */
102216 {
102217   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
102218   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
102219 }
102220         break;
102221       case 37: /* columnid ::= nm */
102222 {
102223   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
102224   yygotominor.yy0 = yymsp[0].minor.yy0;
102225 }
102226         break;
102227       case 38: /* id ::= ID */
102228       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
102229       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
102230       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
102231       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
102232       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
102233       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
102234       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
102235       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
102236       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
102237       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
102238       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
102239       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
102240       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
102241       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
102242       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
102243       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
102244       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
102245       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
102246       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
102247       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
102248       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
102249 {yygotominor.yy0 = yymsp[0].minor.yy0;}
102250         break;
102251       case 45: /* type ::= typetoken */
102252 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
102253         break;
102254       case 47: /* typetoken ::= typename LP signed RP */
102255 {
102256   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
102257   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
102258 }
102259         break;
102260       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
102261 {
102262   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
102263   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
102264 }
102265         break;
102266       case 50: /* typename ::= typename ids */
102267 {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);}
102268         break;
102269       case 57: /* ccons ::= DEFAULT term */
102270       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
102271 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
102272         break;
102273       case 58: /* ccons ::= DEFAULT LP expr RP */
102274 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
102275         break;
102276       case 60: /* ccons ::= DEFAULT MINUS term */
102277 {
102278   ExprSpan v;
102279   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
102280   v.zStart = yymsp[-1].minor.yy0.z;
102281   v.zEnd = yymsp[0].minor.yy118.zEnd;
102282   sqlite3AddDefaultValue(pParse,&v);
102283 }
102284         break;
102285       case 61: /* ccons ::= DEFAULT id */
102286 {
102287   ExprSpan v;
102288   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
102289   sqlite3AddDefaultValue(pParse,&v);
102290 }
102291         break;
102292       case 63: /* ccons ::= NOT NULL onconf */
102293 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
102294         break;
102295       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
102296 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
102297         break;
102298       case 65: /* ccons ::= UNIQUE onconf */
102299 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
102300         break;
102301       case 66: /* ccons ::= CHECK LP expr RP */
102302 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
102303         break;
102304       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
102305 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
102306         break;
102307       case 68: /* ccons ::= defer_subclause */
102308 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
102309         break;
102310       case 69: /* ccons ::= COLLATE ids */
102311 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
102312         break;
102313       case 72: /* refargs ::= */
102314 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
102315         break;
102316       case 73: /* refargs ::= refargs refarg */
102317 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
102318         break;
102319       case 74: /* refarg ::= MATCH nm */
102320       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
102321 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
102322         break;
102323       case 76: /* refarg ::= ON DELETE refact */
102324 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
102325         break;
102326       case 77: /* refarg ::= ON UPDATE refact */
102327 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
102328         break;
102329       case 78: /* refact ::= SET NULL */
102330 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
102331         break;
102332       case 79: /* refact ::= SET DEFAULT */
102333 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
102334         break;
102335       case 80: /* refact ::= CASCADE */
102336 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
102337         break;
102338       case 81: /* refact ::= RESTRICT */
102339 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
102340         break;
102341       case 82: /* refact ::= NO ACTION */
102342 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
102343         break;
102344       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
102345       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
102346       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
102347       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
102348 {yygotominor.yy4 = yymsp[0].minor.yy4;}
102349         break;
102350       case 88: /* conslist_opt ::= */
102351 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
102352         break;
102353       case 89: /* conslist_opt ::= COMMA conslist */
102354 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
102355         break;
102356       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
102357 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
102358         break;
102359       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
102360 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
102361         break;
102362       case 96: /* tcons ::= CHECK LP expr RP onconf */
102363 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
102364         break;
102365       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
102366 {
102367     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
102368     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
102369 }
102370         break;
102371       case 100: /* onconf ::= */
102372 {yygotominor.yy4 = OE_Default;}
102373         break;
102374       case 102: /* orconf ::= */
102375 {yygotominor.yy210 = OE_Default;}
102376         break;
102377       case 103: /* orconf ::= OR resolvetype */
102378 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
102379         break;
102380       case 105: /* resolvetype ::= IGNORE */
102381 {yygotominor.yy4 = OE_Ignore;}
102382         break;
102383       case 106: /* resolvetype ::= REPLACE */
102384 {yygotominor.yy4 = OE_Replace;}
102385         break;
102386       case 107: /* cmd ::= DROP TABLE ifexists fullname */
102387 {
102388   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
102389 }
102390         break;
102391       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
102392 {
102393   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);
102394 }
102395         break;
102396       case 111: /* cmd ::= DROP VIEW ifexists fullname */
102397 {
102398   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
102399 }
102400         break;
102401       case 112: /* cmd ::= select */
102402 {
102403   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
102404   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
102405   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
102406 }
102407         break;
102408       case 113: /* select ::= oneselect */
102409 {yygotominor.yy387 = yymsp[0].minor.yy387;}
102410         break;
102411       case 114: /* select ::= select multiselect_op oneselect */
102412 {
102413   if( yymsp[0].minor.yy387 ){
102414     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
102415     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
102416   }else{
102417     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
102418   }
102419   yygotominor.yy387 = yymsp[0].minor.yy387;
102420 }
102421         break;
102422       case 116: /* multiselect_op ::= UNION ALL */
102423 {yygotominor.yy4 = TK_ALL;}
102424         break;
102425       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
102426 {
102427   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);
102428 }
102429         break;
102430       case 122: /* sclp ::= selcollist COMMA */
102431       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
102432 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
102433         break;
102434       case 123: /* sclp ::= */
102435       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
102436       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
102437       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
102438       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
102439 {yygotominor.yy322 = 0;}
102440         break;
102441       case 124: /* selcollist ::= sclp expr as */
102442 {
102443    yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
102444    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
102445    sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
102446 }
102447         break;
102448       case 125: /* selcollist ::= sclp STAR */
102449 {
102450   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
102451   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
102452 }
102453         break;
102454       case 126: /* selcollist ::= sclp nm DOT STAR */
102455 {
102456   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
102457   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
102458   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
102459   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
102460 }
102461         break;
102462       case 129: /* as ::= */
102463 {yygotominor.yy0.n = 0;}
102464         break;
102465       case 130: /* from ::= */
102466 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
102467         break;
102468       case 131: /* from ::= FROM seltablist */
102469 {
102470   yygotominor.yy259 = yymsp[0].minor.yy259;
102471   sqlite3SrcListShiftJoinType(yygotominor.yy259);
102472 }
102473         break;
102474       case 132: /* stl_prefix ::= seltablist joinop */
102475 {
102476    yygotominor.yy259 = yymsp[-1].minor.yy259;
102477    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
102478 }
102479         break;
102480       case 133: /* stl_prefix ::= */
102481 {yygotominor.yy259 = 0;}
102482         break;
102483       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
102484 {
102485   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);
102486   sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
102487 }
102488         break;
102489       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
102490 {
102491     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);
102492   }
102493         break;
102494       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
102495 {
102496     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
102497       yygotominor.yy259 = yymsp[-4].minor.yy259;
102498     }else{
102499       Select *pSubquery;
102500       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
102501       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
102502       yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
102503     }
102504   }
102505         break;
102506       case 137: /* dbnm ::= */
102507       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
102508 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
102509         break;
102510       case 139: /* fullname ::= nm dbnm */
102511 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
102512         break;
102513       case 140: /* joinop ::= COMMA|JOIN */
102514 { yygotominor.yy4 = JT_INNER; }
102515         break;
102516       case 141: /* joinop ::= JOIN_KW JOIN */
102517 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
102518         break;
102519       case 142: /* joinop ::= JOIN_KW nm JOIN */
102520 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
102521         break;
102522       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
102523 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
102524         break;
102525       case 144: /* on_opt ::= ON expr */
102526       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
102527       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
102528       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
102529       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
102530       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
102531 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
102532         break;
102533       case 145: /* on_opt ::= */
102534       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
102535       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
102536       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
102537       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
102538 {yygotominor.yy314 = 0;}
102539         break;
102540       case 148: /* indexed_opt ::= NOT INDEXED */
102541 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
102542         break;
102543       case 149: /* using_opt ::= USING LP inscollist RP */
102544       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
102545 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
102546         break;
102547       case 150: /* using_opt ::= */
102548       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
102549 {yygotominor.yy384 = 0;}
102550         break;
102551       case 152: /* orderby_opt ::= ORDER BY sortlist */
102552       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
102553       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
102554 {yygotominor.yy322 = yymsp[0].minor.yy322;}
102555         break;
102556       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
102557 {
102558   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
102559   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
102560 }
102561         break;
102562       case 154: /* sortlist ::= sortitem sortorder */
102563 {
102564   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
102565   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
102566 }
102567         break;
102568       case 156: /* sortorder ::= ASC */
102569       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
102570 {yygotominor.yy4 = SQLITE_SO_ASC;}
102571         break;
102572       case 157: /* sortorder ::= DESC */
102573 {yygotominor.yy4 = SQLITE_SO_DESC;}
102574         break;
102575       case 163: /* limit_opt ::= */
102576 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
102577         break;
102578       case 164: /* limit_opt ::= LIMIT expr */
102579 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
102580         break;
102581       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
102582 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
102583         break;
102584       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
102585 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
102586         break;
102587       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
102588 {
102589   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
102590   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
102591 }
102592         break;
102593       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
102594 {
102595   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
102596   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list"); 
102597   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
102598 }
102599         break;
102600       case 171: /* setlist ::= setlist COMMA nm EQ expr */
102601 {
102602   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
102603   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
102604 }
102605         break;
102606       case 172: /* setlist ::= nm EQ expr */
102607 {
102608   yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
102609   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
102610 }
102611         break;
102612       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
102613 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
102614         break;
102615       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
102616 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
102617         break;
102618       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
102619 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
102620         break;
102621       case 176: /* insert_cmd ::= INSERT orconf */
102622 {yygotominor.yy210 = yymsp[0].minor.yy210;}
102623         break;
102624       case 177: /* insert_cmd ::= REPLACE */
102625 {yygotominor.yy210 = OE_Replace;}
102626         break;
102627       case 178: /* itemlist ::= itemlist COMMA expr */
102628       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
102629 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
102630         break;
102631       case 179: /* itemlist ::= expr */
102632       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
102633 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
102634         break;
102635       case 182: /* inscollist ::= inscollist COMMA nm */
102636 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
102637         break;
102638       case 183: /* inscollist ::= nm */
102639 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
102640         break;
102641       case 184: /* expr ::= term */
102642 {yygotominor.yy118 = yymsp[0].minor.yy118;}
102643         break;
102644       case 185: /* expr ::= LP expr RP */
102645 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
102646         break;
102647       case 186: /* term ::= NULL */
102648       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
102649       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
102650 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
102651         break;
102652       case 187: /* expr ::= id */
102653       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
102654 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
102655         break;
102656       case 189: /* expr ::= nm DOT nm */
102657 {
102658   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
102659   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
102660   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
102661   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
102662 }
102663         break;
102664       case 190: /* expr ::= nm DOT nm DOT nm */
102665 {
102666   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
102667   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
102668   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
102669   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
102670   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
102671   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
102672 }
102673         break;
102674       case 193: /* expr ::= REGISTER */
102675 {
102676   /* When doing a nested parse, one can include terms in an expression
102677   ** that look like this:   #1 #2 ...  These terms refer to registers
102678   ** in the virtual machine.  #N is the N-th register. */
102679   if( pParse->nested==0 ){
102680     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
102681     yygotominor.yy118.pExpr = 0;
102682   }else{
102683     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
102684     if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
102685   }
102686   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
102687 }
102688         break;
102689       case 194: /* expr ::= VARIABLE */
102690 {
102691   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
102692   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
102693   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
102694 }
102695         break;
102696       case 195: /* expr ::= expr COLLATE ids */
102697 {
102698   yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
102699   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
102700   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102701 }
102702         break;
102703       case 196: /* expr ::= CAST LP expr AS typetoken RP */
102704 {
102705   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
102706   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
102707 }
102708         break;
102709       case 197: /* expr ::= ID LP distinct exprlist RP */
102710 {
102711   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
102712     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
102713   }
102714   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
102715   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
102716   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
102717     yygotominor.yy118.pExpr->flags |= EP_Distinct;
102718   }
102719 }
102720         break;
102721       case 198: /* expr ::= ID LP STAR RP */
102722 {
102723   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
102724   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
102725 }
102726         break;
102727       case 199: /* term ::= CTIME_KW */
102728 {
102729   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
102730   ** treated as functions that return constants */
102731   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
102732   if( yygotominor.yy118.pExpr ){
102733     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;  
102734   }
102735   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
102736 }
102737         break;
102738       case 200: /* expr ::= expr AND expr */
102739       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
102740       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
102741       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
102742       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
102743       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
102744       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
102745       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
102746 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
102747         break;
102748       case 208: /* likeop ::= LIKE_KW */
102749       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
102750 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
102751         break;
102752       case 209: /* likeop ::= NOT LIKE_KW */
102753       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
102754 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
102755         break;
102756       case 212: /* expr ::= expr likeop expr */
102757 {
102758   ExprList *pList;
102759   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
102760   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
102761   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
102762   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102763   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
102764   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
102765   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
102766 }
102767         break;
102768       case 213: /* expr ::= expr likeop expr ESCAPE expr */
102769 {
102770   ExprList *pList;
102771   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
102772   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
102773   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
102774   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
102775   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102776   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
102777   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
102778   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
102779 }
102780         break;
102781       case 214: /* expr ::= expr ISNULL|NOTNULL */
102782 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
102783         break;
102784       case 215: /* expr ::= expr NOT NULL */
102785 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
102786         break;
102787       case 216: /* expr ::= expr IS expr */
102788 {
102789   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
102790   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
102791 }
102792         break;
102793       case 217: /* expr ::= expr IS NOT expr */
102794 {
102795   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
102796   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
102797 }
102798         break;
102799       case 218: /* expr ::= NOT expr */
102800       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
102801 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
102802         break;
102803       case 220: /* expr ::= MINUS expr */
102804 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
102805         break;
102806       case 221: /* expr ::= PLUS expr */
102807 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
102808         break;
102809       case 224: /* expr ::= expr between_op expr AND expr */
102810 {
102811   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
102812   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
102813   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
102814   if( yygotominor.yy118.pExpr ){
102815     yygotominor.yy118.pExpr->x.pList = pList;
102816   }else{
102817     sqlite3ExprListDelete(pParse->db, pList);
102818   } 
102819   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102820   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
102821   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
102822 }
102823         break;
102824       case 227: /* expr ::= expr in_op LP exprlist RP */
102825 {
102826     if( yymsp[-1].minor.yy322==0 ){
102827       /* Expressions of the form
102828       **
102829       **      expr1 IN ()
102830       **      expr1 NOT IN ()
102831       **
102832       ** simplify to constants 0 (false) and 1 (true), respectively,
102833       ** regardless of the value of expr1.
102834       */
102835       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
102836       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
102837     }else{
102838       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
102839       if( yygotominor.yy118.pExpr ){
102840         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
102841         sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
102842       }else{
102843         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
102844       }
102845       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102846     }
102847     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
102848     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102849   }
102850         break;
102851       case 228: /* expr ::= LP select RP */
102852 {
102853     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
102854     if( yygotominor.yy118.pExpr ){
102855       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
102856       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
102857       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
102858     }else{
102859       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
102860     }
102861     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
102862     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102863   }
102864         break;
102865       case 229: /* expr ::= expr in_op LP select RP */
102866 {
102867     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
102868     if( yygotominor.yy118.pExpr ){
102869       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
102870       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
102871       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
102872     }else{
102873       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
102874     }
102875     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102876     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
102877     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102878   }
102879         break;
102880       case 230: /* expr ::= expr in_op nm dbnm */
102881 {
102882     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
102883     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
102884     if( yygotominor.yy118.pExpr ){
102885       yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
102886       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
102887       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
102888     }else{
102889       sqlite3SrcListDelete(pParse->db, pSrc);
102890     }
102891     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
102892     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
102893     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];
102894   }
102895         break;
102896       case 231: /* expr ::= EXISTS LP select RP */
102897 {
102898     Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
102899     if( p ){
102900       p->x.pSelect = yymsp[-1].minor.yy387;
102901       ExprSetProperty(p, EP_xIsSelect);
102902       sqlite3ExprSetHeight(pParse, p);
102903     }else{
102904       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
102905     }
102906     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
102907     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102908   }
102909         break;
102910       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
102911 {
102912   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
102913   if( yygotominor.yy118.pExpr ){
102914     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
102915     sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
102916   }else{
102917     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
102918   }
102919   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
102920   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
102921 }
102922         break;
102923       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
102924 {
102925   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
102926   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
102927 }
102928         break;
102929       case 234: /* case_exprlist ::= WHEN expr THEN expr */
102930 {
102931   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
102932   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
102933 }
102934         break;
102935       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
102936 {
102937   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
102938                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
102939                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
102940 }
102941         break;
102942       case 244: /* uniqueflag ::= UNIQUE */
102943       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
102944 {yygotominor.yy4 = OE_Abort;}
102945         break;
102946       case 245: /* uniqueflag ::= */
102947 {yygotominor.yy4 = OE_None;}
102948         break;
102949       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
102950 {
102951   Expr *p = 0;
102952   if( yymsp[-1].minor.yy0.n>0 ){
102953     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
102954     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
102955   }
102956   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
102957   sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
102958   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
102959   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
102960 }
102961         break;
102962       case 249: /* idxlist ::= nm collate sortorder */
102963 {
102964   Expr *p = 0;
102965   if( yymsp[-1].minor.yy0.n>0 ){
102966     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
102967     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
102968   }
102969   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
102970   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
102971   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
102972   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
102973 }
102974         break;
102975       case 250: /* collate ::= */
102976 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
102977         break;
102978       case 252: /* cmd ::= DROP INDEX ifexists fullname */
102979 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
102980         break;
102981       case 253: /* cmd ::= VACUUM */
102982       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
102983 {sqlite3Vacuum(pParse);}
102984         break;
102985       case 255: /* cmd ::= PRAGMA nm dbnm */
102986 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
102987         break;
102988       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
102989 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
102990         break;
102991       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
102992 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
102993         break;
102994       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
102995 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
102996         break;
102997       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
102998 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
102999         break;
103000       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
103001 {
103002   Token all;
103003   all.z = yymsp[-3].minor.yy0.z;
103004   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
103005   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
103006 }
103007         break;
103008       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
103009 {
103010   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);
103011   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
103012 }
103013         break;
103014       case 272: /* trigger_time ::= BEFORE */
103015       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
103016 { yygotominor.yy4 = TK_BEFORE; }
103017         break;
103018       case 273: /* trigger_time ::= AFTER */
103019 { yygotominor.yy4 = TK_AFTER;  }
103020         break;
103021       case 274: /* trigger_time ::= INSTEAD OF */
103022 { yygotominor.yy4 = TK_INSTEAD;}
103023         break;
103024       case 276: /* trigger_event ::= DELETE|INSERT */
103025       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
103026 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
103027         break;
103028       case 278: /* trigger_event ::= UPDATE OF inscollist */
103029 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
103030         break;
103031       case 281: /* when_clause ::= */
103032       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
103033 { yygotominor.yy314 = 0; }
103034         break;
103035       case 282: /* when_clause ::= WHEN expr */
103036       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
103037 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
103038         break;
103039       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
103040 {
103041   assert( yymsp[-2].minor.yy203!=0 );
103042   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
103043   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
103044   yygotominor.yy203 = yymsp[-2].minor.yy203;
103045 }
103046         break;
103047       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
103048
103049   assert( yymsp[-1].minor.yy203!=0 );
103050   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
103051   yygotominor.yy203 = yymsp[-1].minor.yy203;
103052 }
103053         break;
103054       case 286: /* trnm ::= nm DOT nm */
103055 {
103056   yygotominor.yy0 = yymsp[0].minor.yy0;
103057   sqlite3ErrorMsg(pParse, 
103058         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
103059         "statements within triggers");
103060 }
103061         break;
103062       case 288: /* tridxby ::= INDEXED BY nm */
103063 {
103064   sqlite3ErrorMsg(pParse,
103065         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
103066         "within triggers");
103067 }
103068         break;
103069       case 289: /* tridxby ::= NOT INDEXED */
103070 {
103071   sqlite3ErrorMsg(pParse,
103072         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
103073         "within triggers");
103074 }
103075         break;
103076       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
103077 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
103078         break;
103079       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
103080 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
103081         break;
103082       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
103083 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
103084         break;
103085       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
103086 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
103087         break;
103088       case 294: /* trigger_cmd ::= select */
103089 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
103090         break;
103091       case 295: /* expr ::= RAISE LP IGNORE RP */
103092 {
103093   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
103094   if( yygotominor.yy118.pExpr ){
103095     yygotominor.yy118.pExpr->affinity = OE_Ignore;
103096   }
103097   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
103098   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
103099 }
103100         break;
103101       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
103102 {
103103   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
103104   if( yygotominor.yy118.pExpr ) {
103105     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
103106   }
103107   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
103108   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
103109 }
103110         break;
103111       case 297: /* raisetype ::= ROLLBACK */
103112 {yygotominor.yy4 = OE_Rollback;}
103113         break;
103114       case 299: /* raisetype ::= FAIL */
103115 {yygotominor.yy4 = OE_Fail;}
103116         break;
103117       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
103118 {
103119   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
103120 }
103121         break;
103122       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
103123 {
103124   sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
103125 }
103126         break;
103127       case 302: /* cmd ::= DETACH database_kw_opt expr */
103128 {
103129   sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
103130 }
103131         break;
103132       case 307: /* cmd ::= REINDEX */
103133 {sqlite3Reindex(pParse, 0, 0);}
103134         break;
103135       case 308: /* cmd ::= REINDEX nm dbnm */
103136 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
103137         break;
103138       case 309: /* cmd ::= ANALYZE */
103139 {sqlite3Analyze(pParse, 0, 0);}
103140         break;
103141       case 310: /* cmd ::= ANALYZE nm dbnm */
103142 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
103143         break;
103144       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
103145 {
103146   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
103147 }
103148         break;
103149       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
103150 {
103151   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
103152 }
103153         break;
103154       case 313: /* add_column_fullname ::= fullname */
103155 {
103156   pParse->db->lookaside.bEnabled = 0;
103157   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
103158 }
103159         break;
103160       case 316: /* cmd ::= create_vtab */
103161 {sqlite3VtabFinishParse(pParse,0);}
103162         break;
103163       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
103164 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
103165         break;
103166       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
103167 {
103168     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
103169 }
103170         break;
103171       case 321: /* vtabarg ::= */
103172 {sqlite3VtabArgInit(pParse);}
103173         break;
103174       case 323: /* vtabargtoken ::= ANY */
103175       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
103176       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
103177 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
103178         break;
103179       default:
103180       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
103181       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
103182       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
103183       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
103184       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
103185       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
103186       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
103187       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
103188       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
103189       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
103190       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
103191       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
103192       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
103193       /* (44) type ::= */ yytestcase(yyruleno==44);
103194       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
103195       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
103196       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
103197       /* (54) carglist ::= */ yytestcase(yyruleno==54);
103198       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
103199       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
103200       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
103201       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
103202       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
103203       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
103204       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
103205       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
103206       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
103207       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
103208       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
103209       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
103210       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
103211       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
103212       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
103213       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
103214       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
103215       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
103216       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
103217       /* (326) anylist ::= */ yytestcase(yyruleno==326);
103218       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
103219       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
103220         break;
103221   };
103222   yygoto = yyRuleInfo[yyruleno].lhs;
103223   yysize = yyRuleInfo[yyruleno].nrhs;
103224   yypParser->yyidx -= yysize;
103225   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
103226   if( yyact < YYNSTATE ){
103227 #ifdef NDEBUG
103228     /* If we are not debugging and the reduce action popped at least
103229     ** one element off the stack, then we can push the new element back
103230     ** onto the stack here, and skip the stack overflow test in yy_shift().
103231     ** That gives a significant speed improvement. */
103232     if( yysize ){
103233       yypParser->yyidx++;
103234       yymsp -= yysize-1;
103235       yymsp->stateno = (YYACTIONTYPE)yyact;
103236       yymsp->major = (YYCODETYPE)yygoto;
103237       yymsp->minor = yygotominor;
103238     }else
103239 #endif
103240     {
103241       yy_shift(yypParser,yyact,yygoto,&yygotominor);
103242     }
103243   }else{
103244     assert( yyact == YYNSTATE + YYNRULE + 1 );
103245     yy_accept(yypParser);
103246   }
103247 }
103248
103249 /*
103250 ** The following code executes when the parse fails
103251 */
103252 #ifndef YYNOERRORRECOVERY
103253 static void yy_parse_failed(
103254   yyParser *yypParser           /* The parser */
103255 ){
103256   sqlite3ParserARG_FETCH;
103257 #ifndef NDEBUG
103258   if( yyTraceFILE ){
103259     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
103260   }
103261 #endif
103262   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
103263   /* Here code is inserted which will be executed whenever the
103264   ** parser fails */
103265   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
103266 }
103267 #endif /* YYNOERRORRECOVERY */
103268
103269 /*
103270 ** The following code executes when a syntax error first occurs.
103271 */
103272 static void yy_syntax_error(
103273   yyParser *yypParser,           /* The parser */
103274   int yymajor,                   /* The major type of the error token */
103275   YYMINORTYPE yyminor            /* The minor type of the error token */
103276 ){
103277   sqlite3ParserARG_FETCH;
103278 #define TOKEN (yyminor.yy0)
103279
103280   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
103281   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
103282   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
103283   pParse->parseError = 1;
103284   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
103285 }
103286
103287 /*
103288 ** The following is executed when the parser accepts
103289 */
103290 static void yy_accept(
103291   yyParser *yypParser           /* The parser */
103292 ){
103293   sqlite3ParserARG_FETCH;
103294 #ifndef NDEBUG
103295   if( yyTraceFILE ){
103296     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
103297   }
103298 #endif
103299   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
103300   /* Here code is inserted which will be executed whenever the
103301   ** parser accepts */
103302   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
103303 }
103304
103305 /* The main parser program.
103306 ** The first argument is a pointer to a structure obtained from
103307 ** "sqlite3ParserAlloc" which describes the current state of the parser.
103308 ** The second argument is the major token number.  The third is
103309 ** the minor token.  The fourth optional argument is whatever the
103310 ** user wants (and specified in the grammar) and is available for
103311 ** use by the action routines.
103312 **
103313 ** Inputs:
103314 ** <ul>
103315 ** <li> A pointer to the parser (an opaque structure.)
103316 ** <li> The major token number.
103317 ** <li> The minor token number.
103318 ** <li> An option argument of a grammar-specified type.
103319 ** </ul>
103320 **
103321 ** Outputs:
103322 ** None.
103323 */
103324 SQLITE_PRIVATE void sqlite3Parser(
103325   void *yyp,                   /* The parser */
103326   int yymajor,                 /* The major token code number */
103327   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
103328   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
103329 ){
103330   YYMINORTYPE yyminorunion;
103331   int yyact;            /* The parser action. */
103332   int yyendofinput;     /* True if we are at the end of input */
103333 #ifdef YYERRORSYMBOL
103334   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
103335 #endif
103336   yyParser *yypParser;  /* The parser */
103337
103338   /* (re)initialize the parser, if necessary */
103339   yypParser = (yyParser*)yyp;
103340   if( yypParser->yyidx<0 ){
103341 #if YYSTACKDEPTH<=0
103342     if( yypParser->yystksz <=0 ){
103343       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
103344       yyminorunion = yyzerominor;
103345       yyStackOverflow(yypParser, &yyminorunion);
103346       return;
103347     }
103348 #endif
103349     yypParser->yyidx = 0;
103350     yypParser->yyerrcnt = -1;
103351     yypParser->yystack[0].stateno = 0;
103352     yypParser->yystack[0].major = 0;
103353   }
103354   yyminorunion.yy0 = yyminor;
103355   yyendofinput = (yymajor==0);
103356   sqlite3ParserARG_STORE;
103357
103358 #ifndef NDEBUG
103359   if( yyTraceFILE ){
103360     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
103361   }
103362 #endif
103363
103364   do{
103365     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
103366     if( yyact<YYNSTATE ){
103367       assert( !yyendofinput );  /* Impossible to shift the $ token */
103368       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
103369       yypParser->yyerrcnt--;
103370       yymajor = YYNOCODE;
103371     }else if( yyact < YYNSTATE + YYNRULE ){
103372       yy_reduce(yypParser,yyact-YYNSTATE);
103373     }else{
103374       assert( yyact == YY_ERROR_ACTION );
103375 #ifdef YYERRORSYMBOL
103376       int yymx;
103377 #endif
103378 #ifndef NDEBUG
103379       if( yyTraceFILE ){
103380         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
103381       }
103382 #endif
103383 #ifdef YYERRORSYMBOL
103384       /* A syntax error has occurred.
103385       ** The response to an error depends upon whether or not the
103386       ** grammar defines an error token "ERROR".  
103387       **
103388       ** This is what we do if the grammar does define ERROR:
103389       **
103390       **  * Call the %syntax_error function.
103391       **
103392       **  * Begin popping the stack until we enter a state where
103393       **    it is legal to shift the error symbol, then shift
103394       **    the error symbol.
103395       **
103396       **  * Set the error count to three.
103397       **
103398       **  * Begin accepting and shifting new tokens.  No new error
103399       **    processing will occur until three tokens have been
103400       **    shifted successfully.
103401       **
103402       */
103403       if( yypParser->yyerrcnt<0 ){
103404         yy_syntax_error(yypParser,yymajor,yyminorunion);
103405       }
103406       yymx = yypParser->yystack[yypParser->yyidx].major;
103407       if( yymx==YYERRORSYMBOL || yyerrorhit ){
103408 #ifndef NDEBUG
103409         if( yyTraceFILE ){
103410           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
103411              yyTracePrompt,yyTokenName[yymajor]);
103412         }
103413 #endif
103414         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
103415         yymajor = YYNOCODE;
103416       }else{
103417          while(
103418           yypParser->yyidx >= 0 &&
103419           yymx != YYERRORSYMBOL &&
103420           (yyact = yy_find_reduce_action(
103421                         yypParser->yystack[yypParser->yyidx].stateno,
103422                         YYERRORSYMBOL)) >= YYNSTATE
103423         ){
103424           yy_pop_parser_stack(yypParser);
103425         }
103426         if( yypParser->yyidx < 0 || yymajor==0 ){
103427           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
103428           yy_parse_failed(yypParser);
103429           yymajor = YYNOCODE;
103430         }else if( yymx!=YYERRORSYMBOL ){
103431           YYMINORTYPE u2;
103432           u2.YYERRSYMDT = 0;
103433           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
103434         }
103435       }
103436       yypParser->yyerrcnt = 3;
103437       yyerrorhit = 1;
103438 #elif defined(YYNOERRORRECOVERY)
103439       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
103440       ** do any kind of error recovery.  Instead, simply invoke the syntax
103441       ** error routine and continue going as if nothing had happened.
103442       **
103443       ** Applications can set this macro (for example inside %include) if
103444       ** they intend to abandon the parse upon the first syntax error seen.
103445       */
103446       yy_syntax_error(yypParser,yymajor,yyminorunion);
103447       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
103448       yymajor = YYNOCODE;
103449       
103450 #else  /* YYERRORSYMBOL is not defined */
103451       /* This is what we do if the grammar does not define ERROR:
103452       **
103453       **  * Report an error message, and throw away the input token.
103454       **
103455       **  * If the input token is $, then fail the parse.
103456       **
103457       ** As before, subsequent error messages are suppressed until
103458       ** three input tokens have been successfully shifted.
103459       */
103460       if( yypParser->yyerrcnt<=0 ){
103461         yy_syntax_error(yypParser,yymajor,yyminorunion);
103462       }
103463       yypParser->yyerrcnt = 3;
103464       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
103465       if( yyendofinput ){
103466         yy_parse_failed(yypParser);
103467       }
103468       yymajor = YYNOCODE;
103469 #endif
103470     }
103471   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
103472   return;
103473 }
103474
103475 /************** End of parse.c ***********************************************/
103476 /************** Begin file tokenize.c ****************************************/
103477 /*
103478 ** 2001 September 15
103479 **
103480 ** The author disclaims copyright to this source code.  In place of
103481 ** a legal notice, here is a blessing:
103482 **
103483 **    May you do good and not evil.
103484 **    May you find forgiveness for yourself and forgive others.
103485 **    May you share freely, never taking more than you give.
103486 **
103487 *************************************************************************
103488 ** An tokenizer for SQL
103489 **
103490 ** This file contains C code that splits an SQL input string up into
103491 ** individual tokens and sends those tokens one-by-one over to the
103492 ** parser for analysis.
103493 */
103494
103495 /*
103496 ** The charMap() macro maps alphabetic characters into their
103497 ** lower-case ASCII equivalent.  On ASCII machines, this is just
103498 ** an upper-to-lower case map.  On EBCDIC machines we also need
103499 ** to adjust the encoding.  Only alphabetic characters and underscores
103500 ** need to be translated.
103501 */
103502 #ifdef SQLITE_ASCII
103503 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
103504 #endif
103505 #ifdef SQLITE_EBCDIC
103506 # define charMap(X) ebcdicToAscii[(unsigned char)X]
103507 const unsigned char ebcdicToAscii[] = {
103508 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
103509    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
103510    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
103511    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
103512    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
103513    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
103514    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
103515    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
103516    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
103517    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
103518    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
103519    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
103520    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
103521    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
103522    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
103523    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
103524    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
103525 };
103526 #endif
103527
103528 /*
103529 ** The sqlite3KeywordCode function looks up an identifier to determine if
103530 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
103531 ** returned.  If the input is not a keyword, TK_ID is returned.
103532 **
103533 ** The implementation of this routine was generated by a program,
103534 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
103535 ** The output of the mkkeywordhash.c program is written into a file
103536 ** named keywordhash.h and then included into this source file by
103537 ** the #include below.
103538 */
103539 /************** Include keywordhash.h in the middle of tokenize.c ************/
103540 /************** Begin file keywordhash.h *************************************/
103541 /***** This file contains automatically generated code ******
103542 **
103543 ** The code in this file has been automatically generated by
103544 **
103545 **   sqlite/tool/mkkeywordhash.c
103546 **
103547 ** The code in this file implements a function that determines whether
103548 ** or not a given identifier is really an SQL keyword.  The same thing
103549 ** might be implemented more directly using a hand-written hash table.
103550 ** But by using this automatically generated code, the size of the code
103551 ** is substantially reduced.  This is important for embedded applications
103552 ** on platforms with limited memory.
103553 */
103554 /* Hash score: 175 */
103555 static int keywordCode(const char *z, int n){
103556   /* zText[] encodes 811 bytes of keywords in 541 bytes */
103557   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
103558   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
103559   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
103560   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
103561   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
103562   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
103563   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
103564   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
103565   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
103566   /*   INITIALLY                                                          */
103567   static const char zText[540] = {
103568     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
103569     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
103570     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
103571     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
103572     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
103573     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
103574     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
103575     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
103576     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
103577     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
103578     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
103579     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
103580     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
103581     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
103582     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
103583     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
103584     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
103585     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
103586     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
103587     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
103588     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
103589     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
103590     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
103591     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
103592     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
103593     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
103594     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
103595     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
103596     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
103597     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
103598   };
103599   static const unsigned char aHash[127] = {
103600       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
103601       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
103602      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
103603        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
103604        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
103605       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
103606       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
103607       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
103608       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
103609       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
103610   };
103611   static const unsigned char aNext[121] = {
103612        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
103613        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
103614        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
103615        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
103616        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
103617       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
103618       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
103619        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
103620      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
103621       35,  64,   0,   0,
103622   };
103623   static const unsigned char aLen[121] = {
103624        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
103625        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
103626       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
103627        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
103628        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
103629        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
103630        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
103631        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
103632        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
103633        6,   4,   9,   3,
103634   };
103635   static const unsigned short int aOffset[121] = {
103636        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
103637       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
103638       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
103639      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
103640      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
103641      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
103642      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
103643      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
103644      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
103645      521, 527, 531, 536,
103646   };
103647   static const unsigned char aCode[121] = {
103648     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
103649     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
103650     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
103651     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
103652     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
103653     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
103654     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
103655     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
103656     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
103657     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
103658     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
103659     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
103660     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
103661     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
103662     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
103663     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
103664     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
103665     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
103666     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
103667     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
103668     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
103669     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
103670     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
103671     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
103672     TK_ALL,        
103673   };
103674   int h, i;
103675   if( n<2 ) return TK_ID;
103676   h = ((charMap(z[0])*4) ^
103677       (charMap(z[n-1])*3) ^
103678       n) % 127;
103679   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
103680     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
103681       testcase( i==0 ); /* REINDEX */
103682       testcase( i==1 ); /* INDEXED */
103683       testcase( i==2 ); /* INDEX */
103684       testcase( i==3 ); /* DESC */
103685       testcase( i==4 ); /* ESCAPE */
103686       testcase( i==5 ); /* EACH */
103687       testcase( i==6 ); /* CHECK */
103688       testcase( i==7 ); /* KEY */
103689       testcase( i==8 ); /* BEFORE */
103690       testcase( i==9 ); /* FOREIGN */
103691       testcase( i==10 ); /* FOR */
103692       testcase( i==11 ); /* IGNORE */
103693       testcase( i==12 ); /* REGEXP */
103694       testcase( i==13 ); /* EXPLAIN */
103695       testcase( i==14 ); /* INSTEAD */
103696       testcase( i==15 ); /* ADD */
103697       testcase( i==16 ); /* DATABASE */
103698       testcase( i==17 ); /* AS */
103699       testcase( i==18 ); /* SELECT */
103700       testcase( i==19 ); /* TABLE */
103701       testcase( i==20 ); /* LEFT */
103702       testcase( i==21 ); /* THEN */
103703       testcase( i==22 ); /* END */
103704       testcase( i==23 ); /* DEFERRABLE */
103705       testcase( i==24 ); /* ELSE */
103706       testcase( i==25 ); /* EXCEPT */
103707       testcase( i==26 ); /* TRANSACTION */
103708       testcase( i==27 ); /* ACTION */
103709       testcase( i==28 ); /* ON */
103710       testcase( i==29 ); /* NATURAL */
103711       testcase( i==30 ); /* ALTER */
103712       testcase( i==31 ); /* RAISE */
103713       testcase( i==32 ); /* EXCLUSIVE */
103714       testcase( i==33 ); /* EXISTS */
103715       testcase( i==34 ); /* SAVEPOINT */
103716       testcase( i==35 ); /* INTERSECT */
103717       testcase( i==36 ); /* TRIGGER */
103718       testcase( i==37 ); /* REFERENCES */
103719       testcase( i==38 ); /* CONSTRAINT */
103720       testcase( i==39 ); /* INTO */
103721       testcase( i==40 ); /* OFFSET */
103722       testcase( i==41 ); /* OF */
103723       testcase( i==42 ); /* SET */
103724       testcase( i==43 ); /* TEMPORARY */
103725       testcase( i==44 ); /* TEMP */
103726       testcase( i==45 ); /* OR */
103727       testcase( i==46 ); /* UNIQUE */
103728       testcase( i==47 ); /* QUERY */
103729       testcase( i==48 ); /* ATTACH */
103730       testcase( i==49 ); /* HAVING */
103731       testcase( i==50 ); /* GROUP */
103732       testcase( i==51 ); /* UPDATE */
103733       testcase( i==52 ); /* BEGIN */
103734       testcase( i==53 ); /* INNER */
103735       testcase( i==54 ); /* RELEASE */
103736       testcase( i==55 ); /* BETWEEN */
103737       testcase( i==56 ); /* NOTNULL */
103738       testcase( i==57 ); /* NOT */
103739       testcase( i==58 ); /* NO */
103740       testcase( i==59 ); /* NULL */
103741       testcase( i==60 ); /* LIKE */
103742       testcase( i==61 ); /* CASCADE */
103743       testcase( i==62 ); /* ASC */
103744       testcase( i==63 ); /* DELETE */
103745       testcase( i==64 ); /* CASE */
103746       testcase( i==65 ); /* COLLATE */
103747       testcase( i==66 ); /* CREATE */
103748       testcase( i==67 ); /* CURRENT_DATE */
103749       testcase( i==68 ); /* DETACH */
103750       testcase( i==69 ); /* IMMEDIATE */
103751       testcase( i==70 ); /* JOIN */
103752       testcase( i==71 ); /* INSERT */
103753       testcase( i==72 ); /* MATCH */
103754       testcase( i==73 ); /* PLAN */
103755       testcase( i==74 ); /* ANALYZE */
103756       testcase( i==75 ); /* PRAGMA */
103757       testcase( i==76 ); /* ABORT */
103758       testcase( i==77 ); /* VALUES */
103759       testcase( i==78 ); /* VIRTUAL */
103760       testcase( i==79 ); /* LIMIT */
103761       testcase( i==80 ); /* WHEN */
103762       testcase( i==81 ); /* WHERE */
103763       testcase( i==82 ); /* RENAME */
103764       testcase( i==83 ); /* AFTER */
103765       testcase( i==84 ); /* REPLACE */
103766       testcase( i==85 ); /* AND */
103767       testcase( i==86 ); /* DEFAULT */
103768       testcase( i==87 ); /* AUTOINCREMENT */
103769       testcase( i==88 ); /* TO */
103770       testcase( i==89 ); /* IN */
103771       testcase( i==90 ); /* CAST */
103772       testcase( i==91 ); /* COLUMN */
103773       testcase( i==92 ); /* COMMIT */
103774       testcase( i==93 ); /* CONFLICT */
103775       testcase( i==94 ); /* CROSS */
103776       testcase( i==95 ); /* CURRENT_TIMESTAMP */
103777       testcase( i==96 ); /* CURRENT_TIME */
103778       testcase( i==97 ); /* PRIMARY */
103779       testcase( i==98 ); /* DEFERRED */
103780       testcase( i==99 ); /* DISTINCT */
103781       testcase( i==100 ); /* IS */
103782       testcase( i==101 ); /* DROP */
103783       testcase( i==102 ); /* FAIL */
103784       testcase( i==103 ); /* FROM */
103785       testcase( i==104 ); /* FULL */
103786       testcase( i==105 ); /* GLOB */
103787       testcase( i==106 ); /* BY */
103788       testcase( i==107 ); /* IF */
103789       testcase( i==108 ); /* ISNULL */
103790       testcase( i==109 ); /* ORDER */
103791       testcase( i==110 ); /* RESTRICT */
103792       testcase( i==111 ); /* OUTER */
103793       testcase( i==112 ); /* RIGHT */
103794       testcase( i==113 ); /* ROLLBACK */
103795       testcase( i==114 ); /* ROW */
103796       testcase( i==115 ); /* UNION */
103797       testcase( i==116 ); /* USING */
103798       testcase( i==117 ); /* VACUUM */
103799       testcase( i==118 ); /* VIEW */
103800       testcase( i==119 ); /* INITIALLY */
103801       testcase( i==120 ); /* ALL */
103802       return aCode[i];
103803     }
103804   }
103805   return TK_ID;
103806 }
103807 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
103808   return keywordCode((char*)z, n);
103809 }
103810 #define SQLITE_N_KEYWORD 121
103811
103812 /************** End of keywordhash.h *****************************************/
103813 /************** Continuing where we left off in tokenize.c *******************/
103814
103815
103816 /*
103817 ** If X is a character that can be used in an identifier then
103818 ** IdChar(X) will be true.  Otherwise it is false.
103819 **
103820 ** For ASCII, any character with the high-order bit set is
103821 ** allowed in an identifier.  For 7-bit characters, 
103822 ** sqlite3IsIdChar[X] must be 1.
103823 **
103824 ** For EBCDIC, the rules are more complex but have the same
103825 ** end result.
103826 **
103827 ** Ticket #1066.  the SQL standard does not allow '$' in the
103828 ** middle of identfiers.  But many SQL implementations do. 
103829 ** SQLite will allow '$' in identifiers for compatibility.
103830 ** But the feature is undocumented.
103831 */
103832 #ifdef SQLITE_ASCII
103833 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
103834 #endif
103835 #ifdef SQLITE_EBCDIC
103836 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
103837 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
103838     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
103839     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
103840     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
103841     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
103842     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
103843     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
103844     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
103845     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
103846     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
103847     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
103848     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
103849     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
103850 };
103851 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
103852 #endif
103853
103854
103855 /*
103856 ** Return the length of the token that begins at z[0]. 
103857 ** Store the token type in *tokenType before returning.
103858 */
103859 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
103860   int i, c;
103861   switch( *z ){
103862     case ' ': case '\t': case '\n': case '\f': case '\r': {
103863       testcase( z[0]==' ' );
103864       testcase( z[0]=='\t' );
103865       testcase( z[0]=='\n' );
103866       testcase( z[0]=='\f' );
103867       testcase( z[0]=='\r' );
103868       for(i=1; sqlite3Isspace(z[i]); i++){}
103869       *tokenType = TK_SPACE;
103870       return i;
103871     }
103872     case '-': {
103873       if( z[1]=='-' ){
103874         /* IMP: R-15891-05542 -- syntax diagram for comments */
103875         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
103876         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
103877         return i;
103878       }
103879       *tokenType = TK_MINUS;
103880       return 1;
103881     }
103882     case '(': {
103883       *tokenType = TK_LP;
103884       return 1;
103885     }
103886     case ')': {
103887       *tokenType = TK_RP;
103888       return 1;
103889     }
103890     case ';': {
103891       *tokenType = TK_SEMI;
103892       return 1;
103893     }
103894     case '+': {
103895       *tokenType = TK_PLUS;
103896       return 1;
103897     }
103898     case '*': {
103899       *tokenType = TK_STAR;
103900       return 1;
103901     }
103902     case '/': {
103903       if( z[1]!='*' || z[2]==0 ){
103904         *tokenType = TK_SLASH;
103905         return 1;
103906       }
103907       /* IMP: R-15891-05542 -- syntax diagram for comments */
103908       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
103909       if( c ) i++;
103910       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
103911       return i;
103912     }
103913     case '%': {
103914       *tokenType = TK_REM;
103915       return 1;
103916     }
103917     case '=': {
103918       *tokenType = TK_EQ;
103919       return 1 + (z[1]=='=');
103920     }
103921     case '<': {
103922       if( (c=z[1])=='=' ){
103923         *tokenType = TK_LE;
103924         return 2;
103925       }else if( c=='>' ){
103926         *tokenType = TK_NE;
103927         return 2;
103928       }else if( c=='<' ){
103929         *tokenType = TK_LSHIFT;
103930         return 2;
103931       }else{
103932         *tokenType = TK_LT;
103933         return 1;
103934       }
103935     }
103936     case '>': {
103937       if( (c=z[1])=='=' ){
103938         *tokenType = TK_GE;
103939         return 2;
103940       }else if( c=='>' ){
103941         *tokenType = TK_RSHIFT;
103942         return 2;
103943       }else{
103944         *tokenType = TK_GT;
103945         return 1;
103946       }
103947     }
103948     case '!': {
103949       if( z[1]!='=' ){
103950         *tokenType = TK_ILLEGAL;
103951         return 2;
103952       }else{
103953         *tokenType = TK_NE;
103954         return 2;
103955       }
103956     }
103957     case '|': {
103958       if( z[1]!='|' ){
103959         *tokenType = TK_BITOR;
103960         return 1;
103961       }else{
103962         *tokenType = TK_CONCAT;
103963         return 2;
103964       }
103965     }
103966     case ',': {
103967       *tokenType = TK_COMMA;
103968       return 1;
103969     }
103970     case '&': {
103971       *tokenType = TK_BITAND;
103972       return 1;
103973     }
103974     case '~': {
103975       *tokenType = TK_BITNOT;
103976       return 1;
103977     }
103978     case '`':
103979     case '\'':
103980     case '"': {
103981       int delim = z[0];
103982       testcase( delim=='`' );
103983       testcase( delim=='\'' );
103984       testcase( delim=='"' );
103985       for(i=1; (c=z[i])!=0; i++){
103986         if( c==delim ){
103987           if( z[i+1]==delim ){
103988             i++;
103989           }else{
103990             break;
103991           }
103992         }
103993       }
103994       if( c=='\'' ){
103995         *tokenType = TK_STRING;
103996         return i+1;
103997       }else if( c!=0 ){
103998         *tokenType = TK_ID;
103999         return i+1;
104000       }else{
104001         *tokenType = TK_ILLEGAL;
104002         return i;
104003       }
104004     }
104005     case '.': {
104006 #ifndef SQLITE_OMIT_FLOATING_POINT
104007       if( !sqlite3Isdigit(z[1]) )
104008 #endif
104009       {
104010         *tokenType = TK_DOT;
104011         return 1;
104012       }
104013       /* If the next character is a digit, this is a floating point
104014       ** number that begins with ".".  Fall thru into the next case */
104015     }
104016     case '0': case '1': case '2': case '3': case '4':
104017     case '5': case '6': case '7': case '8': case '9': {
104018       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
104019       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
104020       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
104021       testcase( z[0]=='9' );
104022       *tokenType = TK_INTEGER;
104023       for(i=0; sqlite3Isdigit(z[i]); i++){}
104024 #ifndef SQLITE_OMIT_FLOATING_POINT
104025       if( z[i]=='.' ){
104026         i++;
104027         while( sqlite3Isdigit(z[i]) ){ i++; }
104028         *tokenType = TK_FLOAT;
104029       }
104030       if( (z[i]=='e' || z[i]=='E') &&
104031            ( sqlite3Isdigit(z[i+1]) 
104032             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
104033            )
104034       ){
104035         i += 2;
104036         while( sqlite3Isdigit(z[i]) ){ i++; }
104037         *tokenType = TK_FLOAT;
104038       }
104039 #endif
104040       while( IdChar(z[i]) ){
104041         *tokenType = TK_ILLEGAL;
104042         i++;
104043       }
104044       return i;
104045     }
104046     case '[': {
104047       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
104048       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
104049       return i;
104050     }
104051     case '?': {
104052       *tokenType = TK_VARIABLE;
104053       for(i=1; sqlite3Isdigit(z[i]); i++){}
104054       return i;
104055     }
104056     case '#': {
104057       for(i=1; sqlite3Isdigit(z[i]); i++){}
104058       if( i>1 ){
104059         /* Parameters of the form #NNN (where NNN is a number) are used
104060         ** internally by sqlite3NestedParse.  */
104061         *tokenType = TK_REGISTER;
104062         return i;
104063       }
104064       /* Fall through into the next case if the '#' is not followed by
104065       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
104066     }
104067 #ifndef SQLITE_OMIT_TCL_VARIABLE
104068     case '$':
104069 #endif
104070     case '@':  /* For compatibility with MS SQL Server */
104071     case ':': {
104072       int n = 0;
104073       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
104074       *tokenType = TK_VARIABLE;
104075       for(i=1; (c=z[i])!=0; i++){
104076         if( IdChar(c) ){
104077           n++;
104078 #ifndef SQLITE_OMIT_TCL_VARIABLE
104079         }else if( c=='(' && n>0 ){
104080           do{
104081             i++;
104082           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
104083           if( c==')' ){
104084             i++;
104085           }else{
104086             *tokenType = TK_ILLEGAL;
104087           }
104088           break;
104089         }else if( c==':' && z[i+1]==':' ){
104090           i++;
104091 #endif
104092         }else{
104093           break;
104094         }
104095       }
104096       if( n==0 ) *tokenType = TK_ILLEGAL;
104097       return i;
104098     }
104099 #ifndef SQLITE_OMIT_BLOB_LITERAL
104100     case 'x': case 'X': {
104101       testcase( z[0]=='x' ); testcase( z[0]=='X' );
104102       if( z[1]=='\'' ){
104103         *tokenType = TK_BLOB;
104104         for(i=2; (c=z[i])!=0 && c!='\''; i++){
104105           if( !sqlite3Isxdigit(c) ){
104106             *tokenType = TK_ILLEGAL;
104107           }
104108         }
104109         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
104110         if( c ) i++;
104111         return i;
104112       }
104113       /* Otherwise fall through to the next case */
104114     }
104115 #endif
104116     default: {
104117       if( !IdChar(*z) ){
104118         break;
104119       }
104120       for(i=1; IdChar(z[i]); i++){}
104121       *tokenType = keywordCode((char*)z, i);
104122       return i;
104123     }
104124   }
104125   *tokenType = TK_ILLEGAL;
104126   return 1;
104127 }
104128
104129 /*
104130 ** Run the parser on the given SQL string.  The parser structure is
104131 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
104132 ** then an and attempt is made to write an error message into 
104133 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
104134 ** error message.
104135 */
104136 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
104137   int nErr = 0;                   /* Number of errors encountered */
104138   int i;                          /* Loop counter */
104139   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
104140   int tokenType;                  /* type of the next token */
104141   int lastTokenParsed = -1;       /* type of the previous token */
104142   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
104143   sqlite3 *db = pParse->db;       /* The database connection */
104144   int mxSqlLen;                   /* Max length of an SQL string */
104145
104146
104147   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
104148   if( db->activeVdbeCnt==0 ){
104149     db->u1.isInterrupted = 0;
104150   }
104151   pParse->rc = SQLITE_OK;
104152   pParse->zTail = zSql;
104153   i = 0;
104154   assert( pzErrMsg!=0 );
104155   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
104156   if( pEngine==0 ){
104157     db->mallocFailed = 1;
104158     return SQLITE_NOMEM;
104159   }
104160   assert( pParse->pNewTable==0 );
104161   assert( pParse->pNewTrigger==0 );
104162   assert( pParse->nVar==0 );
104163   assert( pParse->nVarExpr==0 );
104164   assert( pParse->nVarExprAlloc==0 );
104165   assert( pParse->apVarExpr==0 );
104166   enableLookaside = db->lookaside.bEnabled;
104167   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
104168   while( !db->mallocFailed && zSql[i]!=0 ){
104169     assert( i>=0 );
104170     pParse->sLastToken.z = &zSql[i];
104171     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
104172     i += pParse->sLastToken.n;
104173     if( i>mxSqlLen ){
104174       pParse->rc = SQLITE_TOOBIG;
104175       break;
104176     }
104177     switch( tokenType ){
104178       case TK_SPACE: {
104179         if( db->u1.isInterrupted ){
104180           sqlite3ErrorMsg(pParse, "interrupt");
104181           pParse->rc = SQLITE_INTERRUPT;
104182           goto abort_parse;
104183         }
104184         break;
104185       }
104186       case TK_ILLEGAL: {
104187         sqlite3DbFree(db, *pzErrMsg);
104188         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
104189                         &pParse->sLastToken);
104190         nErr++;
104191         goto abort_parse;
104192       }
104193       case TK_SEMI: {
104194         pParse->zTail = &zSql[i];
104195         /* Fall thru into the default case */
104196       }
104197       default: {
104198         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
104199         lastTokenParsed = tokenType;
104200         if( pParse->rc!=SQLITE_OK ){
104201           goto abort_parse;
104202         }
104203         break;
104204       }
104205     }
104206   }
104207 abort_parse:
104208   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
104209     if( lastTokenParsed!=TK_SEMI ){
104210       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
104211       pParse->zTail = &zSql[i];
104212     }
104213     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
104214   }
104215 #ifdef YYTRACKMAXSTACKDEPTH
104216   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
104217       sqlite3ParserStackPeak(pEngine)
104218   );
104219 #endif /* YYDEBUG */
104220   sqlite3ParserFree(pEngine, sqlite3_free);
104221   db->lookaside.bEnabled = enableLookaside;
104222   if( db->mallocFailed ){
104223     pParse->rc = SQLITE_NOMEM;
104224   }
104225   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
104226     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
104227   }
104228   assert( pzErrMsg!=0 );
104229   if( pParse->zErrMsg ){
104230     *pzErrMsg = pParse->zErrMsg;
104231     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
104232     pParse->zErrMsg = 0;
104233     nErr++;
104234   }
104235   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
104236     sqlite3VdbeDelete(pParse->pVdbe);
104237     pParse->pVdbe = 0;
104238   }
104239 #ifndef SQLITE_OMIT_SHARED_CACHE
104240   if( pParse->nested==0 ){
104241     sqlite3DbFree(db, pParse->aTableLock);
104242     pParse->aTableLock = 0;
104243     pParse->nTableLock = 0;
104244   }
104245 #endif
104246 #ifndef SQLITE_OMIT_VIRTUALTABLE
104247   sqlite3_free(pParse->apVtabLock);
104248 #endif
104249
104250   if( !IN_DECLARE_VTAB ){
104251     /* If the pParse->declareVtab flag is set, do not delete any table 
104252     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
104253     ** will take responsibility for freeing the Table structure.
104254     */
104255     sqlite3DeleteTable(db, pParse->pNewTable);
104256   }
104257
104258   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
104259   sqlite3DbFree(db, pParse->apVarExpr);
104260   sqlite3DbFree(db, pParse->aAlias);
104261   while( pParse->pAinc ){
104262     AutoincInfo *p = pParse->pAinc;
104263     pParse->pAinc = p->pNext;
104264     sqlite3DbFree(db, p);
104265   }
104266   while( pParse->pZombieTab ){
104267     Table *p = pParse->pZombieTab;
104268     pParse->pZombieTab = p->pNextZombie;
104269     sqlite3DeleteTable(db, p);
104270   }
104271   if( nErr>0 && pParse->rc==SQLITE_OK ){
104272     pParse->rc = SQLITE_ERROR;
104273   }
104274   return nErr;
104275 }
104276
104277 /************** End of tokenize.c ********************************************/
104278 /************** Begin file complete.c ****************************************/
104279 /*
104280 ** 2001 September 15
104281 **
104282 ** The author disclaims copyright to this source code.  In place of
104283 ** a legal notice, here is a blessing:
104284 **
104285 **    May you do good and not evil.
104286 **    May you find forgiveness for yourself and forgive others.
104287 **    May you share freely, never taking more than you give.
104288 **
104289 *************************************************************************
104290 ** An tokenizer for SQL
104291 **
104292 ** This file contains C code that implements the sqlite3_complete() API.
104293 ** This code used to be part of the tokenizer.c source file.  But by
104294 ** separating it out, the code will be automatically omitted from
104295 ** static links that do not use it.
104296 */
104297 #ifndef SQLITE_OMIT_COMPLETE
104298
104299 /*
104300 ** This is defined in tokenize.c.  We just have to import the definition.
104301 */
104302 #ifndef SQLITE_AMALGAMATION
104303 #ifdef SQLITE_ASCII
104304 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
104305 #endif
104306 #ifdef SQLITE_EBCDIC
104307 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
104308 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
104309 #endif
104310 #endif /* SQLITE_AMALGAMATION */
104311
104312
104313 /*
104314 ** Token types used by the sqlite3_complete() routine.  See the header
104315 ** comments on that procedure for additional information.
104316 */
104317 #define tkSEMI    0
104318 #define tkWS      1
104319 #define tkOTHER   2
104320 #ifndef SQLITE_OMIT_TRIGGER
104321 #define tkEXPLAIN 3
104322 #define tkCREATE  4
104323 #define tkTEMP    5
104324 #define tkTRIGGER 6
104325 #define tkEND     7
104326 #endif
104327
104328 /*
104329 ** Return TRUE if the given SQL string ends in a semicolon.
104330 **
104331 ** Special handling is require for CREATE TRIGGER statements.
104332 ** Whenever the CREATE TRIGGER keywords are seen, the statement
104333 ** must end with ";END;".
104334 **
104335 ** This implementation uses a state machine with 8 states:
104336 **
104337 **   (0) INVALID   We have not yet seen a non-whitespace character.
104338 **
104339 **   (1) START     At the beginning or end of an SQL statement.  This routine
104340 **                 returns 1 if it ends in the START state and 0 if it ends
104341 **                 in any other state.
104342 **
104343 **   (2) NORMAL    We are in the middle of statement which ends with a single
104344 **                 semicolon.
104345 **
104346 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
104347 **                 a statement.
104348 **
104349 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
104350 **                 statement, possibly preceeded by EXPLAIN and/or followed by
104351 **                 TEMP or TEMPORARY
104352 **
104353 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
104354 **                 ended by a semicolon, the keyword END, and another semicolon.
104355 **
104356 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
104357 **                 the end of a trigger definition.
104358 **
104359 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
104360 **                 of a trigger difinition.
104361 **
104362 ** Transitions between states above are determined by tokens extracted
104363 ** from the input.  The following tokens are significant:
104364 **
104365 **   (0) tkSEMI      A semicolon.
104366 **   (1) tkWS        Whitespace.
104367 **   (2) tkOTHER     Any other SQL token.
104368 **   (3) tkEXPLAIN   The "explain" keyword.
104369 **   (4) tkCREATE    The "create" keyword.
104370 **   (5) tkTEMP      The "temp" or "temporary" keyword.
104371 **   (6) tkTRIGGER   The "trigger" keyword.
104372 **   (7) tkEND       The "end" keyword.
104373 **
104374 ** Whitespace never causes a state transition and is always ignored.
104375 ** This means that a SQL string of all whitespace is invalid.
104376 **
104377 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
104378 ** to recognize the end of a trigger can be omitted.  All we have to do
104379 ** is look for a semicolon that is not part of an string or comment.
104380 */
104381 SQLITE_API int sqlite3_complete(const char *zSql){
104382   u8 state = 0;   /* Current state, using numbers defined in header comment */
104383   u8 token;       /* Value of the next token */
104384
104385 #ifndef SQLITE_OMIT_TRIGGER
104386   /* A complex statement machine used to detect the end of a CREATE TRIGGER
104387   ** statement.  This is the normal case.
104388   */
104389   static const u8 trans[8][8] = {
104390                      /* Token:                                                */
104391      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
104392      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
104393      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
104394      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
104395      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
104396      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
104397      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
104398      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
104399      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
104400   };
104401 #else
104402   /* If triggers are not supported by this compile then the statement machine
104403   ** used to detect the end of a statement is much simplier
104404   */
104405   static const u8 trans[3][3] = {
104406                      /* Token:           */
104407      /* State:       **  SEMI  WS  OTHER */
104408      /* 0 INVALID: */ {    1,  0,     2, },
104409      /* 1   START: */ {    1,  1,     2, },
104410      /* 2  NORMAL: */ {    1,  2,     2, },
104411   };
104412 #endif /* SQLITE_OMIT_TRIGGER */
104413
104414   while( *zSql ){
104415     switch( *zSql ){
104416       case ';': {  /* A semicolon */
104417         token = tkSEMI;
104418         break;
104419       }
104420       case ' ':
104421       case '\r':
104422       case '\t':
104423       case '\n':
104424       case '\f': {  /* White space is ignored */
104425         token = tkWS;
104426         break;
104427       }
104428       case '/': {   /* C-style comments */
104429         if( zSql[1]!='*' ){
104430           token = tkOTHER;
104431           break;
104432         }
104433         zSql += 2;
104434         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
104435         if( zSql[0]==0 ) return 0;
104436         zSql++;
104437         token = tkWS;
104438         break;
104439       }
104440       case '-': {   /* SQL-style comments from "--" to end of line */
104441         if( zSql[1]!='-' ){
104442           token = tkOTHER;
104443           break;
104444         }
104445         while( *zSql && *zSql!='\n' ){ zSql++; }
104446         if( *zSql==0 ) return state==1;
104447         token = tkWS;
104448         break;
104449       }
104450       case '[': {   /* Microsoft-style identifiers in [...] */
104451         zSql++;
104452         while( *zSql && *zSql!=']' ){ zSql++; }
104453         if( *zSql==0 ) return 0;
104454         token = tkOTHER;
104455         break;
104456       }
104457       case '`':     /* Grave-accent quoted symbols used by MySQL */
104458       case '"':     /* single- and double-quoted strings */
104459       case '\'': {
104460         int c = *zSql;
104461         zSql++;
104462         while( *zSql && *zSql!=c ){ zSql++; }
104463         if( *zSql==0 ) return 0;
104464         token = tkOTHER;
104465         break;
104466       }
104467       default: {
104468 #ifdef SQLITE_EBCDIC
104469         unsigned char c;
104470 #endif
104471         if( IdChar((u8)*zSql) ){
104472           /* Keywords and unquoted identifiers */
104473           int nId;
104474           for(nId=1; IdChar(zSql[nId]); nId++){}
104475 #ifdef SQLITE_OMIT_TRIGGER
104476           token = tkOTHER;
104477 #else
104478           switch( *zSql ){
104479             case 'c': case 'C': {
104480               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
104481                 token = tkCREATE;
104482               }else{
104483                 token = tkOTHER;
104484               }
104485               break;
104486             }
104487             case 't': case 'T': {
104488               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
104489                 token = tkTRIGGER;
104490               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
104491                 token = tkTEMP;
104492               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
104493                 token = tkTEMP;
104494               }else{
104495                 token = tkOTHER;
104496               }
104497               break;
104498             }
104499             case 'e':  case 'E': {
104500               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
104501                 token = tkEND;
104502               }else
104503 #ifndef SQLITE_OMIT_EXPLAIN
104504               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
104505                 token = tkEXPLAIN;
104506               }else
104507 #endif
104508               {
104509                 token = tkOTHER;
104510               }
104511               break;
104512             }
104513             default: {
104514               token = tkOTHER;
104515               break;
104516             }
104517           }
104518 #endif /* SQLITE_OMIT_TRIGGER */
104519           zSql += nId-1;
104520         }else{
104521           /* Operators and special symbols */
104522           token = tkOTHER;
104523         }
104524         break;
104525       }
104526     }
104527     state = trans[state][token];
104528     zSql++;
104529   }
104530   return state==1;
104531 }
104532
104533 #ifndef SQLITE_OMIT_UTF16
104534 /*
104535 ** This routine is the same as the sqlite3_complete() routine described
104536 ** above, except that the parameter is required to be UTF-16 encoded, not
104537 ** UTF-8.
104538 */
104539 SQLITE_API int sqlite3_complete16(const void *zSql){
104540   sqlite3_value *pVal;
104541   char const *zSql8;
104542   int rc = SQLITE_NOMEM;
104543
104544 #ifndef SQLITE_OMIT_AUTOINIT
104545   rc = sqlite3_initialize();
104546   if( rc ) return rc;
104547 #endif
104548   pVal = sqlite3ValueNew(0);
104549   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
104550   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
104551   if( zSql8 ){
104552     rc = sqlite3_complete(zSql8);
104553   }else{
104554     rc = SQLITE_NOMEM;
104555   }
104556   sqlite3ValueFree(pVal);
104557   return sqlite3ApiExit(0, rc);
104558 }
104559 #endif /* SQLITE_OMIT_UTF16 */
104560 #endif /* SQLITE_OMIT_COMPLETE */
104561
104562 /************** End of complete.c ********************************************/
104563 /************** Begin file main.c ********************************************/
104564 /*
104565 ** 2001 September 15
104566 **
104567 ** The author disclaims copyright to this source code.  In place of
104568 ** a legal notice, here is a blessing:
104569 **
104570 **    May you do good and not evil.
104571 **    May you find forgiveness for yourself and forgive others.
104572 **    May you share freely, never taking more than you give.
104573 **
104574 *************************************************************************
104575 ** Main file for the SQLite library.  The routines in this file
104576 ** implement the programmer interface to the library.  Routines in
104577 ** other files are for internal use by SQLite and should not be
104578 ** accessed by users of the library.
104579 */
104580
104581 #ifdef SQLITE_ENABLE_FTS3
104582 /************** Include fts3.h in the middle of main.c ***********************/
104583 /************** Begin file fts3.h ********************************************/
104584 /*
104585 ** 2006 Oct 10
104586 **
104587 ** The author disclaims copyright to this source code.  In place of
104588 ** a legal notice, here is a blessing:
104589 **
104590 **    May you do good and not evil.
104591 **    May you find forgiveness for yourself and forgive others.
104592 **    May you share freely, never taking more than you give.
104593 **
104594 ******************************************************************************
104595 **
104596 ** This header file is used by programs that want to link against the
104597 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
104598 */
104599
104600 #if 0
104601 extern "C" {
104602 #endif  /* __cplusplus */
104603
104604 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
104605
104606 #if 0
104607 }  /* extern "C" */
104608 #endif  /* __cplusplus */
104609
104610 /************** End of fts3.h ************************************************/
104611 /************** Continuing where we left off in main.c ***********************/
104612 #endif
104613 #ifdef SQLITE_ENABLE_RTREE
104614 /************** Include rtree.h in the middle of main.c **********************/
104615 /************** Begin file rtree.h *******************************************/
104616 /*
104617 ** 2008 May 26
104618 **
104619 ** The author disclaims copyright to this source code.  In place of
104620 ** a legal notice, here is a blessing:
104621 **
104622 **    May you do good and not evil.
104623 **    May you find forgiveness for yourself and forgive others.
104624 **    May you share freely, never taking more than you give.
104625 **
104626 ******************************************************************************
104627 **
104628 ** This header file is used by programs that want to link against the
104629 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
104630 */
104631
104632 #if 0
104633 extern "C" {
104634 #endif  /* __cplusplus */
104635
104636 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
104637
104638 #if 0
104639 }  /* extern "C" */
104640 #endif  /* __cplusplus */
104641
104642 /************** End of rtree.h ***********************************************/
104643 /************** Continuing where we left off in main.c ***********************/
104644 #endif
104645 #ifdef SQLITE_ENABLE_ICU
104646 /************** Include sqliteicu.h in the middle of main.c ******************/
104647 /************** Begin file sqliteicu.h ***************************************/
104648 /*
104649 ** 2008 May 26
104650 **
104651 ** The author disclaims copyright to this source code.  In place of
104652 ** a legal notice, here is a blessing:
104653 **
104654 **    May you do good and not evil.
104655 **    May you find forgiveness for yourself and forgive others.
104656 **    May you share freely, never taking more than you give.
104657 **
104658 ******************************************************************************
104659 **
104660 ** This header file is used by programs that want to link against the
104661 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
104662 */
104663
104664 #if 0
104665 extern "C" {
104666 #endif  /* __cplusplus */
104667
104668 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
104669
104670 #if 0
104671 }  /* extern "C" */
104672 #endif  /* __cplusplus */
104673
104674
104675 /************** End of sqliteicu.h *******************************************/
104676 /************** Continuing where we left off in main.c ***********************/
104677 #endif
104678
104679 #ifndef SQLITE_AMALGAMATION
104680 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
104681 ** contains the text of SQLITE_VERSION macro. 
104682 */
104683 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
104684 #endif
104685
104686 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
104687 ** a pointer to the to the sqlite3_version[] string constant. 
104688 */
104689 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
104690
104691 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
104692 ** pointer to a string constant whose value is the same as the
104693 ** SQLITE_SOURCE_ID C preprocessor macro. 
104694 */
104695 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
104696
104697 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
104698 ** returns an integer equal to SQLITE_VERSION_NUMBER.
104699 */
104700 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
104701
104702 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
104703 ** zero if and only if SQLite was compiled mutexing code omitted due to
104704 ** the SQLITE_THREADSAFE compile-time option being set to 0.
104705 */
104706 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
104707
104708 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
104709 /*
104710 ** If the following function pointer is not NULL and if
104711 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
104712 ** I/O active are written using this function.  These messages
104713 ** are intended for debugging activity only.
104714 */
104715 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
104716 #endif
104717
104718 /*
104719 ** If the following global variable points to a string which is the
104720 ** name of a directory, then that directory will be used to store
104721 ** temporary files.
104722 **
104723 ** See also the "PRAGMA temp_store_directory" SQL command.
104724 */
104725 SQLITE_API char *sqlite3_temp_directory = 0;
104726
104727 /*
104728 ** Initialize SQLite.  
104729 **
104730 ** This routine must be called to initialize the memory allocation,
104731 ** VFS, and mutex subsystems prior to doing any serious work with
104732 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
104733 ** this routine will be called automatically by key routines such as
104734 ** sqlite3_open().  
104735 **
104736 ** This routine is a no-op except on its very first call for the process,
104737 ** or for the first call after a call to sqlite3_shutdown.
104738 **
104739 ** The first thread to call this routine runs the initialization to
104740 ** completion.  If subsequent threads call this routine before the first
104741 ** thread has finished the initialization process, then the subsequent
104742 ** threads must block until the first thread finishes with the initialization.
104743 **
104744 ** The first thread might call this routine recursively.  Recursive
104745 ** calls to this routine should not block, of course.  Otherwise the
104746 ** initialization process would never complete.
104747 **
104748 ** Let X be the first thread to enter this routine.  Let Y be some other
104749 ** thread.  Then while the initial invocation of this routine by X is
104750 ** incomplete, it is required that:
104751 **
104752 **    *  Calls to this routine from Y must block until the outer-most
104753 **       call by X completes.
104754 **
104755 **    *  Recursive calls to this routine from thread X return immediately
104756 **       without blocking.
104757 */
104758 SQLITE_API int sqlite3_initialize(void){
104759   sqlite3_mutex *pMaster;                      /* The main static mutex */
104760   int rc;                                      /* Result code */
104761
104762 #ifdef SQLITE_OMIT_WSD
104763   rc = sqlite3_wsd_init(4096, 24);
104764   if( rc!=SQLITE_OK ){
104765     return rc;
104766   }
104767 #endif
104768
104769   /* If SQLite is already completely initialized, then this call
104770   ** to sqlite3_initialize() should be a no-op.  But the initialization
104771   ** must be complete.  So isInit must not be set until the very end
104772   ** of this routine.
104773   */
104774   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
104775
104776   /* Make sure the mutex subsystem is initialized.  If unable to 
104777   ** initialize the mutex subsystem, return early with the error.
104778   ** If the system is so sick that we are unable to allocate a mutex,
104779   ** there is not much SQLite is going to be able to do.
104780   **
104781   ** The mutex subsystem must take care of serializing its own
104782   ** initialization.
104783   */
104784   rc = sqlite3MutexInit();
104785   if( rc ) return rc;
104786
104787   /* Initialize the malloc() system and the recursive pInitMutex mutex.
104788   ** This operation is protected by the STATIC_MASTER mutex.  Note that
104789   ** MutexAlloc() is called for a static mutex prior to initializing the
104790   ** malloc subsystem - this implies that the allocation of a static
104791   ** mutex must not require support from the malloc subsystem.
104792   */
104793   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
104794   sqlite3_mutex_enter(pMaster);
104795   sqlite3GlobalConfig.isMutexInit = 1;
104796   if( !sqlite3GlobalConfig.isMallocInit ){
104797     rc = sqlite3MallocInit();
104798   }
104799   if( rc==SQLITE_OK ){
104800     sqlite3GlobalConfig.isMallocInit = 1;
104801     if( !sqlite3GlobalConfig.pInitMutex ){
104802       sqlite3GlobalConfig.pInitMutex =
104803            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
104804       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
104805         rc = SQLITE_NOMEM;
104806       }
104807     }
104808   }
104809   if( rc==SQLITE_OK ){
104810     sqlite3GlobalConfig.nRefInitMutex++;
104811   }
104812   sqlite3_mutex_leave(pMaster);
104813
104814   /* If rc is not SQLITE_OK at this point, then either the malloc
104815   ** subsystem could not be initialized or the system failed to allocate
104816   ** the pInitMutex mutex. Return an error in either case.  */
104817   if( rc!=SQLITE_OK ){
104818     return rc;
104819   }
104820
104821   /* Do the rest of the initialization under the recursive mutex so
104822   ** that we will be able to handle recursive calls into
104823   ** sqlite3_initialize().  The recursive calls normally come through
104824   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
104825   ** recursive calls might also be possible.
104826   **
104827   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
104828   ** to the xInit method, so the xInit method need not be threadsafe.
104829   **
104830   ** The following mutex is what serializes access to the appdef pcache xInit
104831   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
104832   ** call to sqlite3PcacheInitialize().
104833   */
104834   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
104835   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
104836     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
104837     sqlite3GlobalConfig.inProgress = 1;
104838     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
104839     sqlite3RegisterGlobalFunctions();
104840     if( sqlite3GlobalConfig.isPCacheInit==0 ){
104841       rc = sqlite3PcacheInitialize();
104842     }
104843     if( rc==SQLITE_OK ){
104844       sqlite3GlobalConfig.isPCacheInit = 1;
104845       rc = sqlite3OsInit();
104846     }
104847     if( rc==SQLITE_OK ){
104848       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
104849           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
104850       sqlite3GlobalConfig.isInit = 1;
104851     }
104852     sqlite3GlobalConfig.inProgress = 0;
104853   }
104854   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
104855
104856   /* Go back under the static mutex and clean up the recursive
104857   ** mutex to prevent a resource leak.
104858   */
104859   sqlite3_mutex_enter(pMaster);
104860   sqlite3GlobalConfig.nRefInitMutex--;
104861   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
104862     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
104863     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
104864     sqlite3GlobalConfig.pInitMutex = 0;
104865   }
104866   sqlite3_mutex_leave(pMaster);
104867
104868   /* The following is just a sanity check to make sure SQLite has
104869   ** been compiled correctly.  It is important to run this code, but
104870   ** we don't want to run it too often and soak up CPU cycles for no
104871   ** reason.  So we run it once during initialization.
104872   */
104873 #ifndef NDEBUG
104874 #ifndef SQLITE_OMIT_FLOATING_POINT
104875   /* This section of code's only "output" is via assert() statements. */
104876   if ( rc==SQLITE_OK ){
104877     u64 x = (((u64)1)<<63)-1;
104878     double y;
104879     assert(sizeof(x)==8);
104880     assert(sizeof(x)==sizeof(y));
104881     memcpy(&y, &x, 8);
104882     assert( sqlite3IsNaN(y) );
104883   }
104884 #endif
104885 #endif
104886
104887   return rc;
104888 }
104889
104890 /*
104891 ** Undo the effects of sqlite3_initialize().  Must not be called while
104892 ** there are outstanding database connections or memory allocations or
104893 ** while any part of SQLite is otherwise in use in any thread.  This
104894 ** routine is not threadsafe.  But it is safe to invoke this routine
104895 ** on when SQLite is already shut down.  If SQLite is already shut down
104896 ** when this routine is invoked, then this routine is a harmless no-op.
104897 */
104898 SQLITE_API int sqlite3_shutdown(void){
104899   if( sqlite3GlobalConfig.isInit ){
104900     sqlite3_os_end();
104901     sqlite3_reset_auto_extension();
104902     sqlite3GlobalConfig.isInit = 0;
104903   }
104904   if( sqlite3GlobalConfig.isPCacheInit ){
104905     sqlite3PcacheShutdown();
104906     sqlite3GlobalConfig.isPCacheInit = 0;
104907   }
104908   if( sqlite3GlobalConfig.isMallocInit ){
104909     sqlite3MallocEnd();
104910     sqlite3GlobalConfig.isMallocInit = 0;
104911   }
104912   if( sqlite3GlobalConfig.isMutexInit ){
104913     sqlite3MutexEnd();
104914     sqlite3GlobalConfig.isMutexInit = 0;
104915   }
104916
104917   return SQLITE_OK;
104918 }
104919
104920 /*
104921 ** This API allows applications to modify the global configuration of
104922 ** the SQLite library at run-time.
104923 **
104924 ** This routine should only be called when there are no outstanding
104925 ** database connections or memory allocations.  This routine is not
104926 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
104927 ** behavior.
104928 */
104929 SQLITE_API int sqlite3_config(int op, ...){
104930   va_list ap;
104931   int rc = SQLITE_OK;
104932
104933   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
104934   ** the SQLite library is in use. */
104935   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
104936
104937   va_start(ap, op);
104938   switch( op ){
104939
104940     /* Mutex configuration options are only available in a threadsafe
104941     ** compile. 
104942     */
104943 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
104944     case SQLITE_CONFIG_SINGLETHREAD: {
104945       /* Disable all mutexing */
104946       sqlite3GlobalConfig.bCoreMutex = 0;
104947       sqlite3GlobalConfig.bFullMutex = 0;
104948       break;
104949     }
104950     case SQLITE_CONFIG_MULTITHREAD: {
104951       /* Disable mutexing of database connections */
104952       /* Enable mutexing of core data structures */
104953       sqlite3GlobalConfig.bCoreMutex = 1;
104954       sqlite3GlobalConfig.bFullMutex = 0;
104955       break;
104956     }
104957     case SQLITE_CONFIG_SERIALIZED: {
104958       /* Enable all mutexing */
104959       sqlite3GlobalConfig.bCoreMutex = 1;
104960       sqlite3GlobalConfig.bFullMutex = 1;
104961       break;
104962     }
104963     case SQLITE_CONFIG_MUTEX: {
104964       /* Specify an alternative mutex implementation */
104965       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
104966       break;
104967     }
104968     case SQLITE_CONFIG_GETMUTEX: {
104969       /* Retrieve the current mutex implementation */
104970       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
104971       break;
104972     }
104973 #endif
104974
104975
104976     case SQLITE_CONFIG_MALLOC: {
104977       /* Specify an alternative malloc implementation */
104978       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
104979       break;
104980     }
104981     case SQLITE_CONFIG_GETMALLOC: {
104982       /* Retrieve the current malloc() implementation */
104983       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
104984       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
104985       break;
104986     }
104987     case SQLITE_CONFIG_MEMSTATUS: {
104988       /* Enable or disable the malloc status collection */
104989       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
104990       break;
104991     }
104992     case SQLITE_CONFIG_SCRATCH: {
104993       /* Designate a buffer for scratch memory space */
104994       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
104995       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
104996       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
104997       break;
104998     }
104999     case SQLITE_CONFIG_PAGECACHE: {
105000       /* Designate a buffer for page cache memory space */
105001       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
105002       sqlite3GlobalConfig.szPage = va_arg(ap, int);
105003       sqlite3GlobalConfig.nPage = va_arg(ap, int);
105004       break;
105005     }
105006
105007     case SQLITE_CONFIG_PCACHE: {
105008       /* Specify an alternative page cache implementation */
105009       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
105010       break;
105011     }
105012
105013     case SQLITE_CONFIG_GETPCACHE: {
105014       if( sqlite3GlobalConfig.pcache.xInit==0 ){
105015         sqlite3PCacheSetDefault();
105016       }
105017       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
105018       break;
105019     }
105020
105021 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
105022     case SQLITE_CONFIG_HEAP: {
105023       /* Designate a buffer for heap memory space */
105024       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
105025       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
105026       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
105027
105028       if( sqlite3GlobalConfig.pHeap==0 ){
105029         /* If the heap pointer is NULL, then restore the malloc implementation
105030         ** back to NULL pointers too.  This will cause the malloc to go
105031         ** back to its default implementation when sqlite3_initialize() is
105032         ** run.
105033         */
105034         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
105035       }else{
105036         /* The heap pointer is not NULL, then install one of the
105037         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
105038         ** ENABLE_MEMSYS5 is defined, return an error.
105039         */
105040 #ifdef SQLITE_ENABLE_MEMSYS3
105041         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
105042 #endif
105043 #ifdef SQLITE_ENABLE_MEMSYS5
105044         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
105045 #endif
105046       }
105047       break;
105048     }
105049 #endif
105050
105051     case SQLITE_CONFIG_LOOKASIDE: {
105052       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
105053       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
105054       break;
105055     }
105056     
105057     /* Record a pointer to the logger funcction and its first argument.
105058     ** The default is NULL.  Logging is disabled if the function pointer is
105059     ** NULL.
105060     */
105061     case SQLITE_CONFIG_LOG: {
105062       /* MSVC is picky about pulling func ptrs from va lists.
105063       ** http://support.microsoft.com/kb/47961
105064       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
105065       */
105066       typedef void(*LOGFUNC_t)(void*,int,const char*);
105067       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
105068       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
105069       break;
105070     }
105071
105072     default: {
105073       rc = SQLITE_ERROR;
105074       break;
105075     }
105076   }
105077   va_end(ap);
105078   return rc;
105079 }
105080
105081 /*
105082 ** Set up the lookaside buffers for a database connection.
105083 ** Return SQLITE_OK on success.  
105084 ** If lookaside is already active, return SQLITE_BUSY.
105085 **
105086 ** The sz parameter is the number of bytes in each lookaside slot.
105087 ** The cnt parameter is the number of slots.  If pStart is NULL the
105088 ** space for the lookaside memory is obtained from sqlite3_malloc().
105089 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
105090 ** the lookaside memory.
105091 */
105092 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
105093   void *pStart;
105094   if( db->lookaside.nOut ){
105095     return SQLITE_BUSY;
105096   }
105097   /* Free any existing lookaside buffer for this handle before
105098   ** allocating a new one so we don't have to have space for 
105099   ** both at the same time.
105100   */
105101   if( db->lookaside.bMalloced ){
105102     sqlite3_free(db->lookaside.pStart);
105103   }
105104   /* The size of a lookaside slot needs to be larger than a pointer
105105   ** to be useful.
105106   */
105107   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
105108   if( cnt<0 ) cnt = 0;
105109   if( sz==0 || cnt==0 ){
105110     sz = 0;
105111     pStart = 0;
105112   }else if( pBuf==0 ){
105113     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
105114     sqlite3BeginBenignMalloc();
105115     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
105116     sqlite3EndBenignMalloc();
105117   }else{
105118     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
105119     pStart = pBuf;
105120   }
105121   db->lookaside.pStart = pStart;
105122   db->lookaside.pFree = 0;
105123   db->lookaside.sz = (u16)sz;
105124   if( pStart ){
105125     int i;
105126     LookasideSlot *p;
105127     assert( sz > (int)sizeof(LookasideSlot*) );
105128     p = (LookasideSlot*)pStart;
105129     for(i=cnt-1; i>=0; i--){
105130       p->pNext = db->lookaside.pFree;
105131       db->lookaside.pFree = p;
105132       p = (LookasideSlot*)&((u8*)p)[sz];
105133     }
105134     db->lookaside.pEnd = p;
105135     db->lookaside.bEnabled = 1;
105136     db->lookaside.bMalloced = pBuf==0 ?1:0;
105137   }else{
105138     db->lookaside.pEnd = 0;
105139     db->lookaside.bEnabled = 0;
105140     db->lookaside.bMalloced = 0;
105141   }
105142   return SQLITE_OK;
105143 }
105144
105145 /*
105146 ** Return the mutex associated with a database connection.
105147 */
105148 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
105149   return db->mutex;
105150 }
105151
105152 /*
105153 ** Configuration settings for an individual database connection
105154 */
105155 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
105156   va_list ap;
105157   int rc;
105158   va_start(ap, op);
105159   switch( op ){
105160     case SQLITE_DBCONFIG_LOOKASIDE: {
105161       void *pBuf = va_arg(ap, void*); /* IMP: R-21112-12275 */
105162       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
105163       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
105164       rc = setupLookaside(db, pBuf, sz, cnt);
105165       break;
105166     }
105167     default: {
105168       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
105169       break;
105170     }
105171   }
105172   va_end(ap);
105173   return rc;
105174 }
105175
105176
105177 /*
105178 ** Return true if the buffer z[0..n-1] contains all spaces.
105179 */
105180 static int allSpaces(const char *z, int n){
105181   while( n>0 && z[n-1]==' ' ){ n--; }
105182   return n==0;
105183 }
105184
105185 /*
105186 ** This is the default collating function named "BINARY" which is always
105187 ** available.
105188 **
105189 ** If the padFlag argument is not NULL then space padding at the end
105190 ** of strings is ignored.  This implements the RTRIM collation.
105191 */
105192 static int binCollFunc(
105193   void *padFlag,
105194   int nKey1, const void *pKey1,
105195   int nKey2, const void *pKey2
105196 ){
105197   int rc, n;
105198   n = nKey1<nKey2 ? nKey1 : nKey2;
105199   rc = memcmp(pKey1, pKey2, n);
105200   if( rc==0 ){
105201     if( padFlag
105202      && allSpaces(((char*)pKey1)+n, nKey1-n)
105203      && allSpaces(((char*)pKey2)+n, nKey2-n)
105204     ){
105205       /* Leave rc unchanged at 0 */
105206     }else{
105207       rc = nKey1 - nKey2;
105208     }
105209   }
105210   return rc;
105211 }
105212
105213 /*
105214 ** Another built-in collating sequence: NOCASE. 
105215 **
105216 ** This collating sequence is intended to be used for "case independant
105217 ** comparison". SQLite's knowledge of upper and lower case equivalents
105218 ** extends only to the 26 characters used in the English language.
105219 **
105220 ** At the moment there is only a UTF-8 implementation.
105221 */
105222 static int nocaseCollatingFunc(
105223   void *NotUsed,
105224   int nKey1, const void *pKey1,
105225   int nKey2, const void *pKey2
105226 ){
105227   int r = sqlite3StrNICmp(
105228       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
105229   UNUSED_PARAMETER(NotUsed);
105230   if( 0==r ){
105231     r = nKey1-nKey2;
105232   }
105233   return r;
105234 }
105235
105236 /*
105237 ** Return the ROWID of the most recent insert
105238 */
105239 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
105240   return db->lastRowid;
105241 }
105242
105243 /*
105244 ** Return the number of changes in the most recent call to sqlite3_exec().
105245 */
105246 SQLITE_API int sqlite3_changes(sqlite3 *db){
105247   return db->nChange;
105248 }
105249
105250 /*
105251 ** Return the number of changes since the database handle was opened.
105252 */
105253 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
105254   return db->nTotalChange;
105255 }
105256
105257 /*
105258 ** Close all open savepoints. This function only manipulates fields of the
105259 ** database handle object, it does not close any savepoints that may be open
105260 ** at the b-tree/pager level.
105261 */
105262 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
105263   while( db->pSavepoint ){
105264     Savepoint *pTmp = db->pSavepoint;
105265     db->pSavepoint = pTmp->pNext;
105266     sqlite3DbFree(db, pTmp);
105267   }
105268   db->nSavepoint = 0;
105269   db->nStatement = 0;
105270   db->isTransactionSavepoint = 0;
105271 }
105272
105273 /*
105274 ** Invoke the destructor function associated with FuncDef p, if any. Except,
105275 ** if this is not the last copy of the function, do not invoke it. Multiple
105276 ** copies of a single function are created when create_function() is called
105277 ** with SQLITE_ANY as the encoding.
105278 */
105279 static void functionDestroy(sqlite3 *db, FuncDef *p){
105280   FuncDestructor *pDestructor = p->pDestructor;
105281   if( pDestructor ){
105282     pDestructor->nRef--;
105283     if( pDestructor->nRef==0 ){
105284       pDestructor->xDestroy(pDestructor->pUserData);
105285       sqlite3DbFree(db, pDestructor);
105286     }
105287   }
105288 }
105289
105290 /*
105291 ** Close an existing SQLite database
105292 */
105293 SQLITE_API int sqlite3_close(sqlite3 *db){
105294   HashElem *i;                    /* Hash table iterator */
105295   int j;
105296
105297   if( !db ){
105298     return SQLITE_OK;
105299   }
105300   if( !sqlite3SafetyCheckSickOrOk(db) ){
105301     return SQLITE_MISUSE_BKPT;
105302   }
105303   sqlite3_mutex_enter(db->mutex);
105304
105305   sqlite3ResetInternalSchema(db, 0);
105306
105307   /* If a transaction is open, the ResetInternalSchema() call above
105308   ** will not have called the xDisconnect() method on any virtual
105309   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
105310   ** call will do so. We need to do this before the check for active
105311   ** SQL statements below, as the v-table implementation may be storing
105312   ** some prepared statements internally.
105313   */
105314   sqlite3VtabRollback(db);
105315
105316   /* If there are any outstanding VMs, return SQLITE_BUSY. */
105317   if( db->pVdbe ){
105318     sqlite3Error(db, SQLITE_BUSY, 
105319         "unable to close due to unfinalised statements");
105320     sqlite3_mutex_leave(db->mutex);
105321     return SQLITE_BUSY;
105322   }
105323   assert( sqlite3SafetyCheckSickOrOk(db) );
105324
105325   for(j=0; j<db->nDb; j++){
105326     Btree *pBt = db->aDb[j].pBt;
105327     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
105328       sqlite3Error(db, SQLITE_BUSY, 
105329           "unable to close due to unfinished backup operation");
105330       sqlite3_mutex_leave(db->mutex);
105331       return SQLITE_BUSY;
105332     }
105333   }
105334
105335   /* Free any outstanding Savepoint structures. */
105336   sqlite3CloseSavepoints(db);
105337
105338   for(j=0; j<db->nDb; j++){
105339     struct Db *pDb = &db->aDb[j];
105340     if( pDb->pBt ){
105341       sqlite3BtreeClose(pDb->pBt);
105342       pDb->pBt = 0;
105343       if( j!=1 ){
105344         pDb->pSchema = 0;
105345       }
105346     }
105347   }
105348   sqlite3ResetInternalSchema(db, 0);
105349
105350   /* Tell the code in notify.c that the connection no longer holds any
105351   ** locks and does not require any further unlock-notify callbacks.
105352   */
105353   sqlite3ConnectionClosed(db);
105354
105355   assert( db->nDb<=2 );
105356   assert( db->aDb==db->aDbStatic );
105357   for(j=0; j<ArraySize(db->aFunc.a); j++){
105358     FuncDef *pNext, *pHash, *p;
105359     for(p=db->aFunc.a[j]; p; p=pHash){
105360       pHash = p->pHash;
105361       while( p ){
105362         functionDestroy(db, p);
105363         pNext = p->pNext;
105364         sqlite3DbFree(db, p);
105365         p = pNext;
105366       }
105367     }
105368   }
105369   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
105370     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
105371     /* Invoke any destructors registered for collation sequence user data. */
105372     for(j=0; j<3; j++){
105373       if( pColl[j].xDel ){
105374         pColl[j].xDel(pColl[j].pUser);
105375       }
105376     }
105377     sqlite3DbFree(db, pColl);
105378   }
105379   sqlite3HashClear(&db->aCollSeq);
105380 #ifndef SQLITE_OMIT_VIRTUALTABLE
105381   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
105382     Module *pMod = (Module *)sqliteHashData(i);
105383     if( pMod->xDestroy ){
105384       pMod->xDestroy(pMod->pAux);
105385     }
105386     sqlite3DbFree(db, pMod);
105387   }
105388   sqlite3HashClear(&db->aModule);
105389 #endif
105390
105391   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
105392   if( db->pErr ){
105393     sqlite3ValueFree(db->pErr);
105394   }
105395   sqlite3CloseExtensions(db);
105396
105397   db->magic = SQLITE_MAGIC_ERROR;
105398
105399   /* The temp-database schema is allocated differently from the other schema
105400   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
105401   ** So it needs to be freed here. Todo: Why not roll the temp schema into
105402   ** the same sqliteMalloc() as the one that allocates the database 
105403   ** structure?
105404   */
105405   sqlite3DbFree(db, db->aDb[1].pSchema);
105406   sqlite3_mutex_leave(db->mutex);
105407   db->magic = SQLITE_MAGIC_CLOSED;
105408   sqlite3_mutex_free(db->mutex);
105409   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
105410   if( db->lookaside.bMalloced ){
105411     sqlite3_free(db->lookaside.pStart);
105412   }
105413   sqlite3_free(db);
105414   return SQLITE_OK;
105415 }
105416
105417 /*
105418 ** Rollback all database files.
105419 */
105420 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
105421   int i;
105422   int inTrans = 0;
105423   assert( sqlite3_mutex_held(db->mutex) );
105424   sqlite3BeginBenignMalloc();
105425   for(i=0; i<db->nDb; i++){
105426     if( db->aDb[i].pBt ){
105427       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
105428         inTrans = 1;
105429       }
105430       sqlite3BtreeRollback(db->aDb[i].pBt);
105431       db->aDb[i].inTrans = 0;
105432     }
105433   }
105434   sqlite3VtabRollback(db);
105435   sqlite3EndBenignMalloc();
105436
105437   if( db->flags&SQLITE_InternChanges ){
105438     sqlite3ExpirePreparedStatements(db);
105439     sqlite3ResetInternalSchema(db, 0);
105440   }
105441
105442   /* Any deferred constraint violations have now been resolved. */
105443   db->nDeferredCons = 0;
105444
105445   /* If one has been configured, invoke the rollback-hook callback */
105446   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
105447     db->xRollbackCallback(db->pRollbackArg);
105448   }
105449 }
105450
105451 /*
105452 ** Return a static string that describes the kind of error specified in the
105453 ** argument.
105454 */
105455 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
105456   static const char* const aMsg[] = {
105457     /* SQLITE_OK          */ "not an error",
105458     /* SQLITE_ERROR       */ "SQL logic error or missing database",
105459     /* SQLITE_INTERNAL    */ 0,
105460     /* SQLITE_PERM        */ "access permission denied",
105461     /* SQLITE_ABORT       */ "callback requested query abort",
105462     /* SQLITE_BUSY        */ "database is locked",
105463     /* SQLITE_LOCKED      */ "database table is locked",
105464     /* SQLITE_NOMEM       */ "out of memory",
105465     /* SQLITE_READONLY    */ "attempt to write a readonly database",
105466     /* SQLITE_INTERRUPT   */ "interrupted",
105467     /* SQLITE_IOERR       */ "disk I/O error",
105468     /* SQLITE_CORRUPT     */ "database disk image is malformed",
105469     /* SQLITE_NOTFOUND    */ 0,
105470     /* SQLITE_FULL        */ "database or disk is full",
105471     /* SQLITE_CANTOPEN    */ "unable to open database file",
105472     /* SQLITE_PROTOCOL    */ "locking protocol",
105473     /* SQLITE_EMPTY       */ "table contains no data",
105474     /* SQLITE_SCHEMA      */ "database schema has changed",
105475     /* SQLITE_TOOBIG      */ "string or blob too big",
105476     /* SQLITE_CONSTRAINT  */ "constraint failed",
105477     /* SQLITE_MISMATCH    */ "datatype mismatch",
105478     /* SQLITE_MISUSE      */ "library routine called out of sequence",
105479     /* SQLITE_NOLFS       */ "large file support is disabled",
105480     /* SQLITE_AUTH        */ "authorization denied",
105481     /* SQLITE_FORMAT      */ "auxiliary database format error",
105482     /* SQLITE_RANGE       */ "bind or column index out of range",
105483     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
105484   };
105485   rc &= 0xff;
105486   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
105487     return aMsg[rc];
105488   }else{
105489     return "unknown error";
105490   }
105491 }
105492
105493 /*
105494 ** This routine implements a busy callback that sleeps and tries
105495 ** again until a timeout value is reached.  The timeout value is
105496 ** an integer number of milliseconds passed in as the first
105497 ** argument.
105498 */
105499 static int sqliteDefaultBusyCallback(
105500  void *ptr,               /* Database connection */
105501  int count                /* Number of times table has been busy */
105502 ){
105503 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
105504   static const u8 delays[] =
105505      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
105506   static const u8 totals[] =
105507      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
105508 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
105509   sqlite3 *db = (sqlite3 *)ptr;
105510   int timeout = db->busyTimeout;
105511   int delay, prior;
105512
105513   assert( count>=0 );
105514   if( count < NDELAY ){
105515     delay = delays[count];
105516     prior = totals[count];
105517   }else{
105518     delay = delays[NDELAY-1];
105519     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
105520   }
105521   if( prior + delay > timeout ){
105522     delay = timeout - prior;
105523     if( delay<=0 ) return 0;
105524   }
105525   sqlite3OsSleep(db->pVfs, delay*1000);
105526   return 1;
105527 #else
105528   sqlite3 *db = (sqlite3 *)ptr;
105529   int timeout = ((sqlite3 *)ptr)->busyTimeout;
105530   if( (count+1)*1000 > timeout ){
105531     return 0;
105532   }
105533   sqlite3OsSleep(db->pVfs, 1000000);
105534   return 1;
105535 #endif
105536 }
105537
105538 /*
105539 ** Invoke the given busy handler.
105540 **
105541 ** This routine is called when an operation failed with a lock.
105542 ** If this routine returns non-zero, the lock is retried.  If it
105543 ** returns 0, the operation aborts with an SQLITE_BUSY error.
105544 */
105545 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
105546   int rc;
105547   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
105548   rc = p->xFunc(p->pArg, p->nBusy);
105549   if( rc==0 ){
105550     p->nBusy = -1;
105551   }else{
105552     p->nBusy++;
105553   }
105554   return rc; 
105555 }
105556
105557 /*
105558 ** This routine sets the busy callback for an Sqlite database to the
105559 ** given callback function with the given argument.
105560 */
105561 SQLITE_API int sqlite3_busy_handler(
105562   sqlite3 *db,
105563   int (*xBusy)(void*,int),
105564   void *pArg
105565 ){
105566   sqlite3_mutex_enter(db->mutex);
105567   db->busyHandler.xFunc = xBusy;
105568   db->busyHandler.pArg = pArg;
105569   db->busyHandler.nBusy = 0;
105570   sqlite3_mutex_leave(db->mutex);
105571   return SQLITE_OK;
105572 }
105573
105574 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
105575 /*
105576 ** This routine sets the progress callback for an Sqlite database to the
105577 ** given callback function with the given argument. The progress callback will
105578 ** be invoked every nOps opcodes.
105579 */
105580 SQLITE_API void sqlite3_progress_handler(
105581   sqlite3 *db, 
105582   int nOps,
105583   int (*xProgress)(void*), 
105584   void *pArg
105585 ){
105586   sqlite3_mutex_enter(db->mutex);
105587   if( nOps>0 ){
105588     db->xProgress = xProgress;
105589     db->nProgressOps = nOps;
105590     db->pProgressArg = pArg;
105591   }else{
105592     db->xProgress = 0;
105593     db->nProgressOps = 0;
105594     db->pProgressArg = 0;
105595   }
105596   sqlite3_mutex_leave(db->mutex);
105597 }
105598 #endif
105599
105600
105601 /*
105602 ** This routine installs a default busy handler that waits for the
105603 ** specified number of milliseconds before returning 0.
105604 */
105605 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
105606   if( ms>0 ){
105607     db->busyTimeout = ms;
105608     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
105609   }else{
105610     sqlite3_busy_handler(db, 0, 0);
105611   }
105612   return SQLITE_OK;
105613 }
105614
105615 /*
105616 ** Cause any pending operation to stop at its earliest opportunity.
105617 */
105618 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
105619   db->u1.isInterrupted = 1;
105620 }
105621
105622
105623 /*
105624 ** This function is exactly the same as sqlite3_create_function(), except
105625 ** that it is designed to be called by internal code. The difference is
105626 ** that if a malloc() fails in sqlite3_create_function(), an error code
105627 ** is returned and the mallocFailed flag cleared. 
105628 */
105629 SQLITE_PRIVATE int sqlite3CreateFunc(
105630   sqlite3 *db,
105631   const char *zFunctionName,
105632   int nArg,
105633   int enc,
105634   void *pUserData,
105635   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
105636   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
105637   void (*xFinal)(sqlite3_context*),
105638   FuncDestructor *pDestructor
105639 ){
105640   FuncDef *p;
105641   int nName;
105642
105643   assert( sqlite3_mutex_held(db->mutex) );
105644   if( zFunctionName==0 ||
105645       (xFunc && (xFinal || xStep)) || 
105646       (!xFunc && (xFinal && !xStep)) ||
105647       (!xFunc && (!xFinal && xStep)) ||
105648       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
105649       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
105650     return SQLITE_MISUSE_BKPT;
105651   }
105652   
105653 #ifndef SQLITE_OMIT_UTF16
105654   /* If SQLITE_UTF16 is specified as the encoding type, transform this
105655   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
105656   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
105657   **
105658   ** If SQLITE_ANY is specified, add three versions of the function
105659   ** to the hash table.
105660   */
105661   if( enc==SQLITE_UTF16 ){
105662     enc = SQLITE_UTF16NATIVE;
105663   }else if( enc==SQLITE_ANY ){
105664     int rc;
105665     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
105666          pUserData, xFunc, xStep, xFinal, pDestructor);
105667     if( rc==SQLITE_OK ){
105668       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
105669           pUserData, xFunc, xStep, xFinal, pDestructor);
105670     }
105671     if( rc!=SQLITE_OK ){
105672       return rc;
105673     }
105674     enc = SQLITE_UTF16BE;
105675   }
105676 #else
105677   enc = SQLITE_UTF8;
105678 #endif
105679   
105680   /* Check if an existing function is being overridden or deleted. If so,
105681   ** and there are active VMs, then return SQLITE_BUSY. If a function
105682   ** is being overridden/deleted but there are no active VMs, allow the
105683   ** operation to continue but invalidate all precompiled statements.
105684   */
105685   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
105686   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
105687     if( db->activeVdbeCnt ){
105688       sqlite3Error(db, SQLITE_BUSY, 
105689         "unable to delete/modify user-function due to active statements");
105690       assert( !db->mallocFailed );
105691       return SQLITE_BUSY;
105692     }else{
105693       sqlite3ExpirePreparedStatements(db);
105694     }
105695   }
105696
105697   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
105698   assert(p || db->mallocFailed);
105699   if( !p ){
105700     return SQLITE_NOMEM;
105701   }
105702
105703   /* If an older version of the function with a configured destructor is
105704   ** being replaced invoke the destructor function here. */
105705   functionDestroy(db, p);
105706
105707   if( pDestructor ){
105708     pDestructor->nRef++;
105709   }
105710   p->pDestructor = pDestructor;
105711   p->flags = 0;
105712   p->xFunc = xFunc;
105713   p->xStep = xStep;
105714   p->xFinalize = xFinal;
105715   p->pUserData = pUserData;
105716   p->nArg = (u16)nArg;
105717   return SQLITE_OK;
105718 }
105719
105720 /*
105721 ** Create new user functions.
105722 */
105723 SQLITE_API int sqlite3_create_function(
105724   sqlite3 *db,
105725   const char *zFunc,
105726   int nArg,
105727   int enc,
105728   void *p,
105729   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
105730   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
105731   void (*xFinal)(sqlite3_context*)
105732 ){
105733   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
105734                                     xFinal, 0);
105735 }
105736
105737 SQLITE_API int sqlite3_create_function_v2(
105738   sqlite3 *db,
105739   const char *zFunc,
105740   int nArg,
105741   int enc,
105742   void *p,
105743   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
105744   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
105745   void (*xFinal)(sqlite3_context*),
105746   void (*xDestroy)(void *)
105747 ){
105748   int rc = SQLITE_ERROR;
105749   FuncDestructor *pArg = 0;
105750   sqlite3_mutex_enter(db->mutex);
105751   if( xDestroy ){
105752     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
105753     if( !pArg ){
105754       xDestroy(p);
105755       goto out;
105756     }
105757     pArg->xDestroy = xDestroy;
105758     pArg->pUserData = p;
105759   }
105760   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
105761   if( pArg && pArg->nRef==0 ){
105762     assert( rc!=SQLITE_OK );
105763     xDestroy(p);
105764     sqlite3DbFree(db, pArg);
105765   }
105766
105767  out:
105768   rc = sqlite3ApiExit(db, rc);
105769   sqlite3_mutex_leave(db->mutex);
105770   return rc;
105771 }
105772
105773 #ifndef SQLITE_OMIT_UTF16
105774 SQLITE_API int sqlite3_create_function16(
105775   sqlite3 *db,
105776   const void *zFunctionName,
105777   int nArg,
105778   int eTextRep,
105779   void *p,
105780   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
105781   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
105782   void (*xFinal)(sqlite3_context*)
105783 ){
105784   int rc;
105785   char *zFunc8;
105786   sqlite3_mutex_enter(db->mutex);
105787   assert( !db->mallocFailed );
105788   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
105789   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
105790   sqlite3DbFree(db, zFunc8);
105791   rc = sqlite3ApiExit(db, rc);
105792   sqlite3_mutex_leave(db->mutex);
105793   return rc;
105794 }
105795 #endif
105796
105797
105798 /*
105799 ** Declare that a function has been overloaded by a virtual table.
105800 **
105801 ** If the function already exists as a regular global function, then
105802 ** this routine is a no-op.  If the function does not exist, then create
105803 ** a new one that always throws a run-time error.  
105804 **
105805 ** When virtual tables intend to provide an overloaded function, they
105806 ** should call this routine to make sure the global function exists.
105807 ** A global function must exist in order for name resolution to work
105808 ** properly.
105809 */
105810 SQLITE_API int sqlite3_overload_function(
105811   sqlite3 *db,
105812   const char *zName,
105813   int nArg
105814 ){
105815   int nName = sqlite3Strlen30(zName);
105816   int rc;
105817   sqlite3_mutex_enter(db->mutex);
105818   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
105819     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
105820                       0, sqlite3InvalidFunction, 0, 0, 0);
105821   }
105822   rc = sqlite3ApiExit(db, SQLITE_OK);
105823   sqlite3_mutex_leave(db->mutex);
105824   return rc;
105825 }
105826
105827 #ifndef SQLITE_OMIT_TRACE
105828 /*
105829 ** Register a trace function.  The pArg from the previously registered trace
105830 ** is returned.  
105831 **
105832 ** A NULL trace function means that no tracing is executes.  A non-NULL
105833 ** trace is a pointer to a function that is invoked at the start of each
105834 ** SQL statement.
105835 */
105836 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
105837   void *pOld;
105838   sqlite3_mutex_enter(db->mutex);
105839   pOld = db->pTraceArg;
105840   db->xTrace = xTrace;
105841   db->pTraceArg = pArg;
105842   sqlite3_mutex_leave(db->mutex);
105843   return pOld;
105844 }
105845 /*
105846 ** Register a profile function.  The pArg from the previously registered 
105847 ** profile function is returned.  
105848 **
105849 ** A NULL profile function means that no profiling is executes.  A non-NULL
105850 ** profile is a pointer to a function that is invoked at the conclusion of
105851 ** each SQL statement that is run.
105852 */
105853 SQLITE_API void *sqlite3_profile(
105854   sqlite3 *db,
105855   void (*xProfile)(void*,const char*,sqlite_uint64),
105856   void *pArg
105857 ){
105858   void *pOld;
105859   sqlite3_mutex_enter(db->mutex);
105860   pOld = db->pProfileArg;
105861   db->xProfile = xProfile;
105862   db->pProfileArg = pArg;
105863   sqlite3_mutex_leave(db->mutex);
105864   return pOld;
105865 }
105866 #endif /* SQLITE_OMIT_TRACE */
105867
105868 /*** EXPERIMENTAL ***
105869 **
105870 ** Register a function to be invoked when a transaction comments.
105871 ** If the invoked function returns non-zero, then the commit becomes a
105872 ** rollback.
105873 */
105874 SQLITE_API void *sqlite3_commit_hook(
105875   sqlite3 *db,              /* Attach the hook to this database */
105876   int (*xCallback)(void*),  /* Function to invoke on each commit */
105877   void *pArg                /* Argument to the function */
105878 ){
105879   void *pOld;
105880   sqlite3_mutex_enter(db->mutex);
105881   pOld = db->pCommitArg;
105882   db->xCommitCallback = xCallback;
105883   db->pCommitArg = pArg;
105884   sqlite3_mutex_leave(db->mutex);
105885   return pOld;
105886 }
105887
105888 /*
105889 ** Register a callback to be invoked each time a row is updated,
105890 ** inserted or deleted using this database connection.
105891 */
105892 SQLITE_API void *sqlite3_update_hook(
105893   sqlite3 *db,              /* Attach the hook to this database */
105894   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
105895   void *pArg                /* Argument to the function */
105896 ){
105897   void *pRet;
105898   sqlite3_mutex_enter(db->mutex);
105899   pRet = db->pUpdateArg;
105900   db->xUpdateCallback = xCallback;
105901   db->pUpdateArg = pArg;
105902   sqlite3_mutex_leave(db->mutex);
105903   return pRet;
105904 }
105905
105906 /*
105907 ** Register a callback to be invoked each time a transaction is rolled
105908 ** back by this database connection.
105909 */
105910 SQLITE_API void *sqlite3_rollback_hook(
105911   sqlite3 *db,              /* Attach the hook to this database */
105912   void (*xCallback)(void*), /* Callback function */
105913   void *pArg                /* Argument to the function */
105914 ){
105915   void *pRet;
105916   sqlite3_mutex_enter(db->mutex);
105917   pRet = db->pRollbackArg;
105918   db->xRollbackCallback = xCallback;
105919   db->pRollbackArg = pArg;
105920   sqlite3_mutex_leave(db->mutex);
105921   return pRet;
105922 }
105923
105924 #ifndef SQLITE_OMIT_WAL
105925 /*
105926 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
105927 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
105928 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
105929 ** wal_autocheckpoint()).
105930 */ 
105931 SQLITE_PRIVATE int sqlite3WalDefaultHook(
105932   void *pClientData,     /* Argument */
105933   sqlite3 *db,           /* Connection */
105934   const char *zDb,       /* Database */
105935   int nFrame             /* Size of WAL */
105936 ){
105937   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
105938     sqlite3BeginBenignMalloc();
105939     sqlite3_wal_checkpoint(db, zDb);
105940     sqlite3EndBenignMalloc();
105941   }
105942   return SQLITE_OK;
105943 }
105944 #endif /* SQLITE_OMIT_WAL */
105945
105946 /*
105947 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
105948 ** a database after committing a transaction if there are nFrame or
105949 ** more frames in the log file. Passing zero or a negative value as the
105950 ** nFrame parameter disables automatic checkpoints entirely.
105951 **
105952 ** The callback registered by this function replaces any existing callback
105953 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
105954 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
105955 ** configured by this function.
105956 */
105957 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
105958 #ifdef SQLITE_OMIT_WAL
105959   UNUSED_PARAMETER(db);
105960   UNUSED_PARAMETER(nFrame);
105961 #else
105962   if( nFrame>0 ){
105963     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
105964   }else{
105965     sqlite3_wal_hook(db, 0, 0);
105966   }
105967 #endif
105968   return SQLITE_OK;
105969 }
105970
105971 /*
105972 ** Register a callback to be invoked each time a transaction is written
105973 ** into the write-ahead-log by this database connection.
105974 */
105975 SQLITE_API void *sqlite3_wal_hook(
105976   sqlite3 *db,                    /* Attach the hook to this db handle */
105977   int(*xCallback)(void *, sqlite3*, const char*, int),
105978   void *pArg                      /* First argument passed to xCallback() */
105979 ){
105980 #ifndef SQLITE_OMIT_WAL
105981   void *pRet;
105982   sqlite3_mutex_enter(db->mutex);
105983   pRet = db->pWalArg;
105984   db->xWalCallback = xCallback;
105985   db->pWalArg = pArg;
105986   sqlite3_mutex_leave(db->mutex);
105987   return pRet;
105988 #else
105989   return 0;
105990 #endif
105991 }
105992
105993
105994 /*
105995 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
105996 ** to contains a zero-length string, all attached databases are 
105997 ** checkpointed.
105998 */
105999 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
106000 #ifdef SQLITE_OMIT_WAL
106001   return SQLITE_OK;
106002 #else
106003   int rc;                         /* Return code */
106004   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
106005
106006   sqlite3_mutex_enter(db->mutex);
106007   if( zDb && zDb[0] ){
106008     iDb = sqlite3FindDbName(db, zDb);
106009   }
106010   if( iDb<0 ){
106011     rc = SQLITE_ERROR;
106012     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
106013   }else{
106014     rc = sqlite3Checkpoint(db, iDb);
106015     sqlite3Error(db, rc, 0);
106016   }
106017   rc = sqlite3ApiExit(db, rc);
106018   sqlite3_mutex_leave(db->mutex);
106019   return rc;
106020 #endif
106021 }
106022
106023 #ifndef SQLITE_OMIT_WAL
106024 /*
106025 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
106026 ** not currently open in WAL mode.
106027 **
106028 ** If a transaction is open on the database being checkpointed, this 
106029 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
106030 ** an error occurs while running the checkpoint, an SQLite error code is 
106031 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
106032 **
106033 ** The mutex on database handle db should be held by the caller. The mutex
106034 ** associated with the specific b-tree being checkpointed is taken by
106035 ** this function while the checkpoint is running.
106036 **
106037 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
106038 ** checkpointed. If an error is encountered it is returned immediately -
106039 ** no attempt is made to checkpoint any remaining databases.
106040 */
106041 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb){
106042   int rc = SQLITE_OK;             /* Return code */
106043   int i;                          /* Used to iterate through attached dbs */
106044
106045   assert( sqlite3_mutex_held(db->mutex) );
106046
106047   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
106048     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
106049       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt);
106050     }
106051   }
106052
106053   return rc;
106054 }
106055 #endif /* SQLITE_OMIT_WAL */
106056
106057 /*
106058 ** This function returns true if main-memory should be used instead of
106059 ** a temporary file for transient pager files and statement journals.
106060 ** The value returned depends on the value of db->temp_store (runtime
106061 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
106062 ** following table describes the relationship between these two values
106063 ** and this functions return value.
106064 **
106065 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
106066 **   -----------------     --------------     ------------------------------
106067 **   0                     any                file      (return 0)
106068 **   1                     1                  file      (return 0)
106069 **   1                     2                  memory    (return 1)
106070 **   1                     0                  file      (return 0)
106071 **   2                     1                  file      (return 0)
106072 **   2                     2                  memory    (return 1)
106073 **   2                     0                  memory    (return 1)
106074 **   3                     any                memory    (return 1)
106075 */
106076 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
106077 #if SQLITE_TEMP_STORE==1
106078   return ( db->temp_store==2 );
106079 #endif
106080 #if SQLITE_TEMP_STORE==2
106081   return ( db->temp_store!=1 );
106082 #endif
106083 #if SQLITE_TEMP_STORE==3
106084   return 1;
106085 #endif
106086 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
106087   return 0;
106088 #endif
106089 }
106090
106091 /*
106092 ** Return UTF-8 encoded English language explanation of the most recent
106093 ** error.
106094 */
106095 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
106096   const char *z;
106097   if( !db ){
106098     return sqlite3ErrStr(SQLITE_NOMEM);
106099   }
106100   if( !sqlite3SafetyCheckSickOrOk(db) ){
106101     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
106102   }
106103   sqlite3_mutex_enter(db->mutex);
106104   if( db->mallocFailed ){
106105     z = sqlite3ErrStr(SQLITE_NOMEM);
106106   }else{
106107     z = (char*)sqlite3_value_text(db->pErr);
106108     assert( !db->mallocFailed );
106109     if( z==0 ){
106110       z = sqlite3ErrStr(db->errCode);
106111     }
106112   }
106113   sqlite3_mutex_leave(db->mutex);
106114   return z;
106115 }
106116
106117 #ifndef SQLITE_OMIT_UTF16
106118 /*
106119 ** Return UTF-16 encoded English language explanation of the most recent
106120 ** error.
106121 */
106122 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
106123   static const u16 outOfMem[] = {
106124     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
106125   };
106126   static const u16 misuse[] = {
106127     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
106128     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
106129     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
106130     'o', 'u', 't', ' ', 
106131     'o', 'f', ' ', 
106132     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
106133   };
106134
106135   const void *z;
106136   if( !db ){
106137     return (void *)outOfMem;
106138   }
106139   if( !sqlite3SafetyCheckSickOrOk(db) ){
106140     return (void *)misuse;
106141   }
106142   sqlite3_mutex_enter(db->mutex);
106143   if( db->mallocFailed ){
106144     z = (void *)outOfMem;
106145   }else{
106146     z = sqlite3_value_text16(db->pErr);
106147     if( z==0 ){
106148       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
106149            SQLITE_UTF8, SQLITE_STATIC);
106150       z = sqlite3_value_text16(db->pErr);
106151     }
106152     /* A malloc() may have failed within the call to sqlite3_value_text16()
106153     ** above. If this is the case, then the db->mallocFailed flag needs to
106154     ** be cleared before returning. Do this directly, instead of via
106155     ** sqlite3ApiExit(), to avoid setting the database handle error message.
106156     */
106157     db->mallocFailed = 0;
106158   }
106159   sqlite3_mutex_leave(db->mutex);
106160   return z;
106161 }
106162 #endif /* SQLITE_OMIT_UTF16 */
106163
106164 /*
106165 ** Return the most recent error code generated by an SQLite routine. If NULL is
106166 ** passed to this function, we assume a malloc() failed during sqlite3_open().
106167 */
106168 SQLITE_API int sqlite3_errcode(sqlite3 *db){
106169   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
106170     return SQLITE_MISUSE_BKPT;
106171   }
106172   if( !db || db->mallocFailed ){
106173     return SQLITE_NOMEM;
106174   }
106175   return db->errCode & db->errMask;
106176 }
106177 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
106178   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
106179     return SQLITE_MISUSE_BKPT;
106180   }
106181   if( !db || db->mallocFailed ){
106182     return SQLITE_NOMEM;
106183   }
106184   return db->errCode;
106185 }
106186
106187 /*
106188 ** Create a new collating function for database "db".  The name is zName
106189 ** and the encoding is enc.
106190 */
106191 static int createCollation(
106192   sqlite3* db,
106193   const char *zName, 
106194   u8 enc,
106195   u8 collType,
106196   void* pCtx,
106197   int(*xCompare)(void*,int,const void*,int,const void*),
106198   void(*xDel)(void*)
106199 ){
106200   CollSeq *pColl;
106201   int enc2;
106202   int nName = sqlite3Strlen30(zName);
106203   
106204   assert( sqlite3_mutex_held(db->mutex) );
106205
106206   /* If SQLITE_UTF16 is specified as the encoding type, transform this
106207   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
106208   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
106209   */
106210   enc2 = enc;
106211   testcase( enc2==SQLITE_UTF16 );
106212   testcase( enc2==SQLITE_UTF16_ALIGNED );
106213   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
106214     enc2 = SQLITE_UTF16NATIVE;
106215   }
106216   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
106217     return SQLITE_MISUSE_BKPT;
106218   }
106219
106220   /* Check if this call is removing or replacing an existing collation 
106221   ** sequence. If so, and there are active VMs, return busy. If there
106222   ** are no active VMs, invalidate any pre-compiled statements.
106223   */
106224   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
106225   if( pColl && pColl->xCmp ){
106226     if( db->activeVdbeCnt ){
106227       sqlite3Error(db, SQLITE_BUSY, 
106228         "unable to delete/modify collation sequence due to active statements");
106229       return SQLITE_BUSY;
106230     }
106231     sqlite3ExpirePreparedStatements(db);
106232
106233     /* If collation sequence pColl was created directly by a call to
106234     ** sqlite3_create_collation, and not generated by synthCollSeq(),
106235     ** then any copies made by synthCollSeq() need to be invalidated.
106236     ** Also, collation destructor - CollSeq.xDel() - function may need
106237     ** to be called.
106238     */ 
106239     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
106240       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
106241       int j;
106242       for(j=0; j<3; j++){
106243         CollSeq *p = &aColl[j];
106244         if( p->enc==pColl->enc ){
106245           if( p->xDel ){
106246             p->xDel(p->pUser);
106247           }
106248           p->xCmp = 0;
106249         }
106250       }
106251     }
106252   }
106253
106254   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
106255   if( pColl==0 ) return SQLITE_NOMEM;
106256   pColl->xCmp = xCompare;
106257   pColl->pUser = pCtx;
106258   pColl->xDel = xDel;
106259   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
106260   pColl->type = collType;
106261   sqlite3Error(db, SQLITE_OK, 0);
106262   return SQLITE_OK;
106263 }
106264
106265
106266 /*
106267 ** This array defines hard upper bounds on limit values.  The
106268 ** initializer must be kept in sync with the SQLITE_LIMIT_*
106269 ** #defines in sqlite3.h.
106270 */
106271 static const int aHardLimit[] = {
106272   SQLITE_MAX_LENGTH,
106273   SQLITE_MAX_SQL_LENGTH,
106274   SQLITE_MAX_COLUMN,
106275   SQLITE_MAX_EXPR_DEPTH,
106276   SQLITE_MAX_COMPOUND_SELECT,
106277   SQLITE_MAX_VDBE_OP,
106278   SQLITE_MAX_FUNCTION_ARG,
106279   SQLITE_MAX_ATTACHED,
106280   SQLITE_MAX_LIKE_PATTERN_LENGTH,
106281   SQLITE_MAX_VARIABLE_NUMBER,
106282   SQLITE_MAX_TRIGGER_DEPTH,
106283 };
106284
106285 /*
106286 ** Make sure the hard limits are set to reasonable values
106287 */
106288 #if SQLITE_MAX_LENGTH<100
106289 # error SQLITE_MAX_LENGTH must be at least 100
106290 #endif
106291 #if SQLITE_MAX_SQL_LENGTH<100
106292 # error SQLITE_MAX_SQL_LENGTH must be at least 100
106293 #endif
106294 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
106295 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
106296 #endif
106297 #if SQLITE_MAX_COMPOUND_SELECT<2
106298 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
106299 #endif
106300 #if SQLITE_MAX_VDBE_OP<40
106301 # error SQLITE_MAX_VDBE_OP must be at least 40
106302 #endif
106303 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
106304 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
106305 #endif
106306 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
106307 # error SQLITE_MAX_ATTACHED must be between 0 and 30
106308 #endif
106309 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
106310 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
106311 #endif
106312 #if SQLITE_MAX_COLUMN>32767
106313 # error SQLITE_MAX_COLUMN must not exceed 32767
106314 #endif
106315 #if SQLITE_MAX_TRIGGER_DEPTH<1
106316 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
106317 #endif
106318
106319
106320 /*
106321 ** Change the value of a limit.  Report the old value.
106322 ** If an invalid limit index is supplied, report -1.
106323 ** Make no changes but still report the old value if the
106324 ** new limit is negative.
106325 **
106326 ** A new lower limit does not shrink existing constructs.
106327 ** It merely prevents new constructs that exceed the limit
106328 ** from forming.
106329 */
106330 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
106331   int oldLimit;
106332
106333
106334   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
106335   ** there is a hard upper bound set at compile-time by a C preprocessor
106336   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
106337   ** "_MAX_".)
106338   */
106339   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
106340   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
106341   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
106342   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
106343   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
106344   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
106345   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
106346   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
106347   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
106348                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
106349   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
106350   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
106351   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
106352
106353
106354   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
106355     return -1;
106356   }
106357   oldLimit = db->aLimit[limitId];
106358   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
106359     if( newLimit>aHardLimit[limitId] ){
106360       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
106361     }
106362     db->aLimit[limitId] = newLimit;
106363   }
106364   return oldLimit;                     /* IMP: R-53341-35419 */
106365 }
106366
106367 /*
106368 ** This routine does the work of opening a database on behalf of
106369 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
106370 ** is UTF-8 encoded.
106371 */
106372 static int openDatabase(
106373   const char *zFilename, /* Database filename UTF-8 encoded */
106374   sqlite3 **ppDb,        /* OUT: Returned database handle */
106375   unsigned flags,        /* Operational flags */
106376   const char *zVfs       /* Name of the VFS to use */
106377 ){
106378   sqlite3 *db;
106379   int rc;
106380   int isThreadsafe;
106381
106382   *ppDb = 0;
106383 #ifndef SQLITE_OMIT_AUTOINIT
106384   rc = sqlite3_initialize();
106385   if( rc ) return rc;
106386 #endif
106387
106388   /* Only allow sensible combinations of bits in the flags argument.  
106389   ** Throw an error if any non-sense combination is used.  If we
106390   ** do not block illegal combinations here, it could trigger
106391   ** assert() statements in deeper layers.  Sensible combinations
106392   ** are:
106393   **
106394   **  1:  SQLITE_OPEN_READONLY
106395   **  2:  SQLITE_OPEN_READWRITE
106396   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
106397   */
106398   assert( SQLITE_OPEN_READONLY  == 0x01 );
106399   assert( SQLITE_OPEN_READWRITE == 0x02 );
106400   assert( SQLITE_OPEN_CREATE    == 0x04 );
106401   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
106402   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
106403   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
106404   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE;
106405
106406   if( sqlite3GlobalConfig.bCoreMutex==0 ){
106407     isThreadsafe = 0;
106408   }else if( flags & SQLITE_OPEN_NOMUTEX ){
106409     isThreadsafe = 0;
106410   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
106411     isThreadsafe = 1;
106412   }else{
106413     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
106414   }
106415   if( flags & SQLITE_OPEN_PRIVATECACHE ){
106416     flags &= ~SQLITE_OPEN_SHAREDCACHE;
106417   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
106418     flags |= SQLITE_OPEN_SHAREDCACHE;
106419   }
106420
106421   /* Remove harmful bits from the flags parameter
106422   **
106423   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
106424   ** dealt with in the previous code block.  Besides these, the only
106425   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
106426   ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
106427   ** off all other flags.
106428   */
106429   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
106430                SQLITE_OPEN_EXCLUSIVE |
106431                SQLITE_OPEN_MAIN_DB |
106432                SQLITE_OPEN_TEMP_DB | 
106433                SQLITE_OPEN_TRANSIENT_DB | 
106434                SQLITE_OPEN_MAIN_JOURNAL | 
106435                SQLITE_OPEN_TEMP_JOURNAL | 
106436                SQLITE_OPEN_SUBJOURNAL | 
106437                SQLITE_OPEN_MASTER_JOURNAL |
106438                SQLITE_OPEN_NOMUTEX |
106439                SQLITE_OPEN_FULLMUTEX |
106440                SQLITE_OPEN_WAL
106441              );
106442
106443   /* Allocate the sqlite data structure */
106444   db = sqlite3MallocZero( sizeof(sqlite3) );
106445   if( db==0 ) goto opendb_out;
106446   if( isThreadsafe ){
106447     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
106448     if( db->mutex==0 ){
106449       sqlite3_free(db);
106450       db = 0;
106451       goto opendb_out;
106452     }
106453   }
106454   sqlite3_mutex_enter(db->mutex);
106455   db->errMask = 0xff;
106456   db->nDb = 2;
106457   db->magic = SQLITE_MAGIC_BUSY;
106458   db->aDb = db->aDbStatic;
106459
106460   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
106461   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
106462   db->autoCommit = 1;
106463   db->nextAutovac = -1;
106464   db->nextPagesize = 0;
106465   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex
106466 #if SQLITE_DEFAULT_FILE_FORMAT<4
106467                  | SQLITE_LegacyFileFmt
106468 #endif
106469 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
106470                  | SQLITE_LoadExtension
106471 #endif
106472 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
106473                  | SQLITE_RecTriggers
106474 #endif
106475       ;
106476   sqlite3HashInit(&db->aCollSeq);
106477 #ifndef SQLITE_OMIT_VIRTUALTABLE
106478   sqlite3HashInit(&db->aModule);
106479 #endif
106480
106481   db->pVfs = sqlite3_vfs_find(zVfs);
106482   if( !db->pVfs ){
106483     rc = SQLITE_ERROR;
106484     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
106485     goto opendb_out;
106486   }
106487
106488   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
106489   ** and UTF-16, so add a version for each to avoid any unnecessary
106490   ** conversions. The only error that can occur here is a malloc() failure.
106491   */
106492   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
106493                   binCollFunc, 0);
106494   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
106495                   binCollFunc, 0);
106496   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
106497                   binCollFunc, 0);
106498   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
106499                   binCollFunc, 0);
106500   if( db->mallocFailed ){
106501     goto opendb_out;
106502   }
106503   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
106504   assert( db->pDfltColl!=0 );
106505
106506   /* Also add a UTF-8 case-insensitive collation sequence. */
106507   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
106508                   nocaseCollatingFunc, 0);
106509
106510   /* Open the backend database driver */
106511   db->openFlags = flags;
106512   rc = sqlite3BtreeOpen(zFilename, db, &db->aDb[0].pBt, 0,
106513                         flags | SQLITE_OPEN_MAIN_DB);
106514   if( rc!=SQLITE_OK ){
106515     if( rc==SQLITE_IOERR_NOMEM ){
106516       rc = SQLITE_NOMEM;
106517     }
106518     sqlite3Error(db, rc, 0);
106519     goto opendb_out;
106520   }
106521   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
106522   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
106523
106524
106525   /* The default safety_level for the main database is 'full'; for the temp
106526   ** database it is 'NONE'. This matches the pager layer defaults.  
106527   */
106528   db->aDb[0].zName = "main";
106529   db->aDb[0].safety_level = 3;
106530   db->aDb[1].zName = "temp";
106531   db->aDb[1].safety_level = 1;
106532
106533   db->magic = SQLITE_MAGIC_OPEN;
106534   if( db->mallocFailed ){
106535     goto opendb_out;
106536   }
106537
106538   /* Register all built-in functions, but do not attempt to read the
106539   ** database schema yet. This is delayed until the first time the database
106540   ** is accessed.
106541   */
106542   sqlite3Error(db, SQLITE_OK, 0);
106543   sqlite3RegisterBuiltinFunctions(db);
106544
106545   /* Load automatic extensions - extensions that have been registered
106546   ** using the sqlite3_automatic_extension() API.
106547   */
106548   sqlite3AutoLoadExtensions(db);
106549   rc = sqlite3_errcode(db);
106550   if( rc!=SQLITE_OK ){
106551     goto opendb_out;
106552   }
106553
106554 #ifdef SQLITE_ENABLE_FTS1
106555   if( !db->mallocFailed ){
106556     extern int sqlite3Fts1Init(sqlite3*);
106557     rc = sqlite3Fts1Init(db);
106558   }
106559 #endif
106560
106561 #ifdef SQLITE_ENABLE_FTS2
106562   if( !db->mallocFailed && rc==SQLITE_OK ){
106563     extern int sqlite3Fts2Init(sqlite3*);
106564     rc = sqlite3Fts2Init(db);
106565   }
106566 #endif
106567
106568 #ifdef SQLITE_ENABLE_FTS3
106569   if( !db->mallocFailed && rc==SQLITE_OK ){
106570     rc = sqlite3Fts3Init(db);
106571   }
106572 #endif
106573
106574 #ifdef SQLITE_ENABLE_ICU
106575   if( !db->mallocFailed && rc==SQLITE_OK ){
106576     rc = sqlite3IcuInit(db);
106577   }
106578 #endif
106579
106580 #ifdef SQLITE_ENABLE_RTREE
106581   if( !db->mallocFailed && rc==SQLITE_OK){
106582     rc = sqlite3RtreeInit(db);
106583   }
106584 #endif
106585
106586   sqlite3Error(db, rc, 0);
106587
106588   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
106589   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
106590   ** mode.  Doing nothing at all also makes NORMAL the default.
106591   */
106592 #ifdef SQLITE_DEFAULT_LOCKING_MODE
106593   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
106594   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
106595                           SQLITE_DEFAULT_LOCKING_MODE);
106596 #endif
106597
106598   /* Enable the lookaside-malloc subsystem */
106599   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
106600                         sqlite3GlobalConfig.nLookaside);
106601
106602   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
106603
106604 opendb_out:
106605   if( db ){
106606     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
106607     sqlite3_mutex_leave(db->mutex);
106608   }
106609   rc = sqlite3_errcode(db);
106610   if( rc==SQLITE_NOMEM ){
106611     sqlite3_close(db);
106612     db = 0;
106613   }else if( rc!=SQLITE_OK ){
106614     db->magic = SQLITE_MAGIC_SICK;
106615   }
106616   *ppDb = db;
106617   return sqlite3ApiExit(0, rc);
106618 }
106619
106620 /*
106621 ** Open a new database handle.
106622 */
106623 SQLITE_API int sqlite3_open(
106624   const char *zFilename, 
106625   sqlite3 **ppDb 
106626 ){
106627   return openDatabase(zFilename, ppDb,
106628                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
106629 }
106630 SQLITE_API int sqlite3_open_v2(
106631   const char *filename,   /* Database filename (UTF-8) */
106632   sqlite3 **ppDb,         /* OUT: SQLite db handle */
106633   int flags,              /* Flags */
106634   const char *zVfs        /* Name of VFS module to use */
106635 ){
106636   return openDatabase(filename, ppDb, flags, zVfs);
106637 }
106638
106639 #ifndef SQLITE_OMIT_UTF16
106640 /*
106641 ** Open a new database handle.
106642 */
106643 SQLITE_API int sqlite3_open16(
106644   const void *zFilename, 
106645   sqlite3 **ppDb
106646 ){
106647   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
106648   sqlite3_value *pVal;
106649   int rc;
106650
106651   assert( zFilename );
106652   assert( ppDb );
106653   *ppDb = 0;
106654 #ifndef SQLITE_OMIT_AUTOINIT
106655   rc = sqlite3_initialize();
106656   if( rc ) return rc;
106657 #endif
106658   pVal = sqlite3ValueNew(0);
106659   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
106660   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
106661   if( zFilename8 ){
106662     rc = openDatabase(zFilename8, ppDb,
106663                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
106664     assert( *ppDb || rc==SQLITE_NOMEM );
106665     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
106666       ENC(*ppDb) = SQLITE_UTF16NATIVE;
106667     }
106668   }else{
106669     rc = SQLITE_NOMEM;
106670   }
106671   sqlite3ValueFree(pVal);
106672
106673   return sqlite3ApiExit(0, rc);
106674 }
106675 #endif /* SQLITE_OMIT_UTF16 */
106676
106677 /*
106678 ** Register a new collation sequence with the database handle db.
106679 */
106680 SQLITE_API int sqlite3_create_collation(
106681   sqlite3* db, 
106682   const char *zName, 
106683   int enc, 
106684   void* pCtx,
106685   int(*xCompare)(void*,int,const void*,int,const void*)
106686 ){
106687   int rc;
106688   sqlite3_mutex_enter(db->mutex);
106689   assert( !db->mallocFailed );
106690   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
106691   rc = sqlite3ApiExit(db, rc);
106692   sqlite3_mutex_leave(db->mutex);
106693   return rc;
106694 }
106695
106696 /*
106697 ** Register a new collation sequence with the database handle db.
106698 */
106699 SQLITE_API int sqlite3_create_collation_v2(
106700   sqlite3* db, 
106701   const char *zName, 
106702   int enc, 
106703   void* pCtx,
106704   int(*xCompare)(void*,int,const void*,int,const void*),
106705   void(*xDel)(void*)
106706 ){
106707   int rc;
106708   sqlite3_mutex_enter(db->mutex);
106709   assert( !db->mallocFailed );
106710   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
106711   rc = sqlite3ApiExit(db, rc);
106712   sqlite3_mutex_leave(db->mutex);
106713   return rc;
106714 }
106715
106716 #ifndef SQLITE_OMIT_UTF16
106717 /*
106718 ** Register a new collation sequence with the database handle db.
106719 */
106720 SQLITE_API int sqlite3_create_collation16(
106721   sqlite3* db, 
106722   const void *zName,
106723   int enc, 
106724   void* pCtx,
106725   int(*xCompare)(void*,int,const void*,int,const void*)
106726 ){
106727   int rc = SQLITE_OK;
106728   char *zName8;
106729   sqlite3_mutex_enter(db->mutex);
106730   assert( !db->mallocFailed );
106731   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
106732   if( zName8 ){
106733     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
106734     sqlite3DbFree(db, zName8);
106735   }
106736   rc = sqlite3ApiExit(db, rc);
106737   sqlite3_mutex_leave(db->mutex);
106738   return rc;
106739 }
106740 #endif /* SQLITE_OMIT_UTF16 */
106741
106742 /*
106743 ** Register a collation sequence factory callback with the database handle
106744 ** db. Replace any previously installed collation sequence factory.
106745 */
106746 SQLITE_API int sqlite3_collation_needed(
106747   sqlite3 *db, 
106748   void *pCollNeededArg, 
106749   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
106750 ){
106751   sqlite3_mutex_enter(db->mutex);
106752   db->xCollNeeded = xCollNeeded;
106753   db->xCollNeeded16 = 0;
106754   db->pCollNeededArg = pCollNeededArg;
106755   sqlite3_mutex_leave(db->mutex);
106756   return SQLITE_OK;
106757 }
106758
106759 #ifndef SQLITE_OMIT_UTF16
106760 /*
106761 ** Register a collation sequence factory callback with the database handle
106762 ** db. Replace any previously installed collation sequence factory.
106763 */
106764 SQLITE_API int sqlite3_collation_needed16(
106765   sqlite3 *db, 
106766   void *pCollNeededArg, 
106767   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
106768 ){
106769   sqlite3_mutex_enter(db->mutex);
106770   db->xCollNeeded = 0;
106771   db->xCollNeeded16 = xCollNeeded16;
106772   db->pCollNeededArg = pCollNeededArg;
106773   sqlite3_mutex_leave(db->mutex);
106774   return SQLITE_OK;
106775 }
106776 #endif /* SQLITE_OMIT_UTF16 */
106777
106778 #ifndef SQLITE_OMIT_DEPRECATED
106779 /*
106780 ** This function is now an anachronism. It used to be used to recover from a
106781 ** malloc() failure, but SQLite now does this automatically.
106782 */
106783 SQLITE_API int sqlite3_global_recover(void){
106784   return SQLITE_OK;
106785 }
106786 #endif
106787
106788 /*
106789 ** Test to see whether or not the database connection is in autocommit
106790 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
106791 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
106792 ** by the next COMMIT or ROLLBACK.
106793 **
106794 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
106795 */
106796 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
106797   return db->autoCommit;
106798 }
106799
106800 /*
106801 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
106802 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
106803 ** constants.  They server two purposes:
106804 **
106805 **   1.  Serve as a convenient place to set a breakpoint in a debugger
106806 **       to detect when version error conditions occurs.
106807 **
106808 **   2.  Invoke sqlite3_log() to provide the source code location where
106809 **       a low-level error is first detected.
106810 */
106811 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
106812   testcase( sqlite3GlobalConfig.xLog!=0 );
106813   sqlite3_log(SQLITE_CORRUPT,
106814               "database corruption at line %d of [%.10s]",
106815               lineno, 20+sqlite3_sourceid());
106816   return SQLITE_CORRUPT;
106817 }
106818 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
106819   testcase( sqlite3GlobalConfig.xLog!=0 );
106820   sqlite3_log(SQLITE_MISUSE, 
106821               "misuse at line %d of [%.10s]",
106822               lineno, 20+sqlite3_sourceid());
106823   return SQLITE_MISUSE;
106824 }
106825 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
106826   testcase( sqlite3GlobalConfig.xLog!=0 );
106827   sqlite3_log(SQLITE_CANTOPEN, 
106828               "cannot open file at line %d of [%.10s]",
106829               lineno, 20+sqlite3_sourceid());
106830   return SQLITE_CANTOPEN;
106831 }
106832
106833
106834 #ifndef SQLITE_OMIT_DEPRECATED
106835 /*
106836 ** This is a convenience routine that makes sure that all thread-specific
106837 ** data for this thread has been deallocated.
106838 **
106839 ** SQLite no longer uses thread-specific data so this routine is now a
106840 ** no-op.  It is retained for historical compatibility.
106841 */
106842 SQLITE_API void sqlite3_thread_cleanup(void){
106843 }
106844 #endif
106845
106846 /*
106847 ** Return meta information about a specific column of a database table.
106848 ** See comment in sqlite3.h (sqlite.h.in) for details.
106849 */
106850 #ifdef SQLITE_ENABLE_COLUMN_METADATA
106851 SQLITE_API int sqlite3_table_column_metadata(
106852   sqlite3 *db,                /* Connection handle */
106853   const char *zDbName,        /* Database name or NULL */
106854   const char *zTableName,     /* Table name */
106855   const char *zColumnName,    /* Column name */
106856   char const **pzDataType,    /* OUTPUT: Declared data type */
106857   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
106858   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
106859   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
106860   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
106861 ){
106862   int rc;
106863   char *zErrMsg = 0;
106864   Table *pTab = 0;
106865   Column *pCol = 0;
106866   int iCol;
106867
106868   char const *zDataType = 0;
106869   char const *zCollSeq = 0;
106870   int notnull = 0;
106871   int primarykey = 0;
106872   int autoinc = 0;
106873
106874   /* Ensure the database schema has been loaded */
106875   sqlite3_mutex_enter(db->mutex);
106876   sqlite3BtreeEnterAll(db);
106877   rc = sqlite3Init(db, &zErrMsg);
106878   if( SQLITE_OK!=rc ){
106879     goto error_out;
106880   }
106881
106882   /* Locate the table in question */
106883   pTab = sqlite3FindTable(db, zTableName, zDbName);
106884   if( !pTab || pTab->pSelect ){
106885     pTab = 0;
106886     goto error_out;
106887   }
106888
106889   /* Find the column for which info is requested */
106890   if( sqlite3IsRowid(zColumnName) ){
106891     iCol = pTab->iPKey;
106892     if( iCol>=0 ){
106893       pCol = &pTab->aCol[iCol];
106894     }
106895   }else{
106896     for(iCol=0; iCol<pTab->nCol; iCol++){
106897       pCol = &pTab->aCol[iCol];
106898       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
106899         break;
106900       }
106901     }
106902     if( iCol==pTab->nCol ){
106903       pTab = 0;
106904       goto error_out;
106905     }
106906   }
106907
106908   /* The following block stores the meta information that will be returned
106909   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
106910   ** and autoinc. At this point there are two possibilities:
106911   ** 
106912   **     1. The specified column name was rowid", "oid" or "_rowid_" 
106913   **        and there is no explicitly declared IPK column. 
106914   **
106915   **     2. The table is not a view and the column name identified an 
106916   **        explicitly declared column. Copy meta information from *pCol.
106917   */ 
106918   if( pCol ){
106919     zDataType = pCol->zType;
106920     zCollSeq = pCol->zColl;
106921     notnull = pCol->notNull!=0;
106922     primarykey  = pCol->isPrimKey!=0;
106923     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
106924   }else{
106925     zDataType = "INTEGER";
106926     primarykey = 1;
106927   }
106928   if( !zCollSeq ){
106929     zCollSeq = "BINARY";
106930   }
106931
106932 error_out:
106933   sqlite3BtreeLeaveAll(db);
106934
106935   /* Whether the function call succeeded or failed, set the output parameters
106936   ** to whatever their local counterparts contain. If an error did occur,
106937   ** this has the effect of zeroing all output parameters.
106938   */
106939   if( pzDataType ) *pzDataType = zDataType;
106940   if( pzCollSeq ) *pzCollSeq = zCollSeq;
106941   if( pNotNull ) *pNotNull = notnull;
106942   if( pPrimaryKey ) *pPrimaryKey = primarykey;
106943   if( pAutoinc ) *pAutoinc = autoinc;
106944
106945   if( SQLITE_OK==rc && !pTab ){
106946     sqlite3DbFree(db, zErrMsg);
106947     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
106948         zColumnName);
106949     rc = SQLITE_ERROR;
106950   }
106951   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
106952   sqlite3DbFree(db, zErrMsg);
106953   rc = sqlite3ApiExit(db, rc);
106954   sqlite3_mutex_leave(db->mutex);
106955   return rc;
106956 }
106957 #endif
106958
106959 /*
106960 ** Sleep for a little while.  Return the amount of time slept.
106961 */
106962 SQLITE_API int sqlite3_sleep(int ms){
106963   sqlite3_vfs *pVfs;
106964   int rc;
106965   pVfs = sqlite3_vfs_find(0);
106966   if( pVfs==0 ) return 0;
106967
106968   /* This function works in milliseconds, but the underlying OsSleep() 
106969   ** API uses microseconds. Hence the 1000's.
106970   */
106971   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
106972   return rc;
106973 }
106974
106975 /*
106976 ** Enable or disable the extended result codes.
106977 */
106978 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
106979   sqlite3_mutex_enter(db->mutex);
106980   db->errMask = onoff ? 0xffffffff : 0xff;
106981   sqlite3_mutex_leave(db->mutex);
106982   return SQLITE_OK;
106983 }
106984
106985 /*
106986 ** Invoke the xFileControl method on a particular database.
106987 */
106988 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
106989   int rc = SQLITE_ERROR;
106990   int iDb;
106991   sqlite3_mutex_enter(db->mutex);
106992   if( zDbName==0 ){
106993     iDb = 0;
106994   }else{
106995     for(iDb=0; iDb<db->nDb; iDb++){
106996       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
106997     }
106998   }
106999   if( iDb<db->nDb ){
107000     Btree *pBtree = db->aDb[iDb].pBt;
107001     if( pBtree ){
107002       Pager *pPager;
107003       sqlite3_file *fd;
107004       sqlite3BtreeEnter(pBtree);
107005       pPager = sqlite3BtreePager(pBtree);
107006       assert( pPager!=0 );
107007       fd = sqlite3PagerFile(pPager);
107008       assert( fd!=0 );
107009       if( op==SQLITE_FCNTL_FILE_POINTER ){
107010         *(sqlite3_file**)pArg = fd;
107011         rc = SQLITE_OK;
107012       }else if( fd->pMethods ){
107013         rc = sqlite3OsFileControl(fd, op, pArg);
107014       }
107015       sqlite3BtreeLeave(pBtree);
107016     }
107017   }
107018   sqlite3_mutex_leave(db->mutex);
107019   return rc;   
107020 }
107021
107022 /*
107023 ** Interface to the testing logic.
107024 */
107025 SQLITE_API int sqlite3_test_control(int op, ...){
107026   int rc = 0;
107027 #ifndef SQLITE_OMIT_BUILTIN_TEST
107028   va_list ap;
107029   va_start(ap, op);
107030   switch( op ){
107031
107032     /*
107033     ** Save the current state of the PRNG.
107034     */
107035     case SQLITE_TESTCTRL_PRNG_SAVE: {
107036       sqlite3PrngSaveState();
107037       break;
107038     }
107039
107040     /*
107041     ** Restore the state of the PRNG to the last state saved using
107042     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
107043     ** this verb acts like PRNG_RESET.
107044     */
107045     case SQLITE_TESTCTRL_PRNG_RESTORE: {
107046       sqlite3PrngRestoreState();
107047       break;
107048     }
107049
107050     /*
107051     ** Reset the PRNG back to its uninitialized state.  The next call
107052     ** to sqlite3_randomness() will reseed the PRNG using a single call
107053     ** to the xRandomness method of the default VFS.
107054     */
107055     case SQLITE_TESTCTRL_PRNG_RESET: {
107056       sqlite3PrngResetState();
107057       break;
107058     }
107059
107060     /*
107061     **  sqlite3_test_control(BITVEC_TEST, size, program)
107062     **
107063     ** Run a test against a Bitvec object of size.  The program argument
107064     ** is an array of integers that defines the test.  Return -1 on a
107065     ** memory allocation error, 0 on success, or non-zero for an error.
107066     ** See the sqlite3BitvecBuiltinTest() for additional information.
107067     */
107068     case SQLITE_TESTCTRL_BITVEC_TEST: {
107069       int sz = va_arg(ap, int);
107070       int *aProg = va_arg(ap, int*);
107071       rc = sqlite3BitvecBuiltinTest(sz, aProg);
107072       break;
107073     }
107074
107075     /*
107076     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
107077     **
107078     ** Register hooks to call to indicate which malloc() failures 
107079     ** are benign.
107080     */
107081     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
107082       typedef void (*void_function)(void);
107083       void_function xBenignBegin;
107084       void_function xBenignEnd;
107085       xBenignBegin = va_arg(ap, void_function);
107086       xBenignEnd = va_arg(ap, void_function);
107087       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
107088       break;
107089     }
107090
107091     /*
107092     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
107093     **
107094     ** Set the PENDING byte to the value in the argument, if X>0.
107095     ** Make no changes if X==0.  Return the value of the pending byte
107096     ** as it existing before this routine was called.
107097     **
107098     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
107099     ** an incompatible database file format.  Changing the PENDING byte
107100     ** while any database connection is open results in undefined and
107101     ** dileterious behavior.
107102     */
107103     case SQLITE_TESTCTRL_PENDING_BYTE: {
107104       rc = PENDING_BYTE;
107105 #ifndef SQLITE_OMIT_WSD
107106       {
107107         unsigned int newVal = va_arg(ap, unsigned int);
107108         if( newVal ) sqlite3PendingByte = newVal;
107109       }
107110 #endif
107111       break;
107112     }
107113
107114     /*
107115     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
107116     **
107117     ** This action provides a run-time test to see whether or not
107118     ** assert() was enabled at compile-time.  If X is true and assert()
107119     ** is enabled, then the return value is true.  If X is true and
107120     ** assert() is disabled, then the return value is zero.  If X is
107121     ** false and assert() is enabled, then the assertion fires and the
107122     ** process aborts.  If X is false and assert() is disabled, then the
107123     ** return value is zero.
107124     */
107125     case SQLITE_TESTCTRL_ASSERT: {
107126       volatile int x = 0;
107127       assert( (x = va_arg(ap,int))!=0 );
107128       rc = x;
107129       break;
107130     }
107131
107132
107133     /*
107134     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
107135     **
107136     ** This action provides a run-time test to see how the ALWAYS and
107137     ** NEVER macros were defined at compile-time.
107138     **
107139     ** The return value is ALWAYS(X).  
107140     **
107141     ** The recommended test is X==2.  If the return value is 2, that means
107142     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
107143     ** default setting.  If the return value is 1, then ALWAYS() is either
107144     ** hard-coded to true or else it asserts if its argument is false.
107145     ** The first behavior (hard-coded to true) is the case if
107146     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
107147     ** behavior (assert if the argument to ALWAYS() is false) is the case if
107148     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
107149     **
107150     ** The run-time test procedure might look something like this:
107151     **
107152     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
107153     **      // ALWAYS() and NEVER() are no-op pass-through macros
107154     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
107155     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
107156     **    }else{
107157     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
107158     **    }
107159     */
107160     case SQLITE_TESTCTRL_ALWAYS: {
107161       int x = va_arg(ap,int);
107162       rc = ALWAYS(x);
107163       break;
107164     }
107165
107166     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
107167     **
107168     ** Set the nReserve size to N for the main database on the database
107169     ** connection db.
107170     */
107171     case SQLITE_TESTCTRL_RESERVE: {
107172       sqlite3 *db = va_arg(ap, sqlite3*);
107173       int x = va_arg(ap,int);
107174       sqlite3_mutex_enter(db->mutex);
107175       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
107176       sqlite3_mutex_leave(db->mutex);
107177       break;
107178     }
107179
107180     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
107181     **
107182     ** Enable or disable various optimizations for testing purposes.  The 
107183     ** argument N is a bitmask of optimizations to be disabled.  For normal
107184     ** operation N should be 0.  The idea is that a test program (like the
107185     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
107186     ** with various optimizations disabled to verify that the same answer
107187     ** is obtained in every case.
107188     */
107189     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
107190       sqlite3 *db = va_arg(ap, sqlite3*);
107191       int x = va_arg(ap,int);
107192       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
107193       break;
107194     }
107195
107196 #ifdef SQLITE_N_KEYWORD
107197     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
107198     **
107199     ** If zWord is a keyword recognized by the parser, then return the
107200     ** number of keywords.  Or if zWord is not a keyword, return 0.
107201     ** 
107202     ** This test feature is only available in the amalgamation since
107203     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
107204     ** is built using separate source files.
107205     */
107206     case SQLITE_TESTCTRL_ISKEYWORD: {
107207       const char *zWord = va_arg(ap, const char*);
107208       int n = sqlite3Strlen30(zWord);
107209       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
107210       break;
107211     }
107212 #endif 
107213
107214     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
107215     **
107216     ** Return the size of a pcache header in bytes.
107217     */
107218     case SQLITE_TESTCTRL_PGHDRSZ: {
107219       rc = sizeof(PgHdr);
107220       break;
107221     }
107222
107223     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
107224     **
107225     ** Pass pFree into sqlite3ScratchFree(). 
107226     ** If sz>0 then allocate a scratch buffer into pNew.  
107227     */
107228     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
107229       void *pFree, **ppNew;
107230       int sz;
107231       sz = va_arg(ap, int);
107232       ppNew = va_arg(ap, void**);
107233       pFree = va_arg(ap, void*);
107234       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
107235       sqlite3ScratchFree(pFree);
107236       break;
107237     }
107238
107239   }
107240   va_end(ap);
107241 #endif /* SQLITE_OMIT_BUILTIN_TEST */
107242   return rc;
107243 }
107244
107245 /************** End of main.c ************************************************/
107246 /************** Begin file notify.c ******************************************/
107247 /*
107248 ** 2009 March 3
107249 **
107250 ** The author disclaims copyright to this source code.  In place of
107251 ** a legal notice, here is a blessing:
107252 **
107253 **    May you do good and not evil.
107254 **    May you find forgiveness for yourself and forgive others.
107255 **    May you share freely, never taking more than you give.
107256 **
107257 *************************************************************************
107258 **
107259 ** This file contains the implementation of the sqlite3_unlock_notify()
107260 ** API method and its associated functionality.
107261 */
107262
107263 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
107264 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
107265
107266 /*
107267 ** Public interfaces:
107268 **
107269 **   sqlite3ConnectionBlocked()
107270 **   sqlite3ConnectionUnlocked()
107271 **   sqlite3ConnectionClosed()
107272 **   sqlite3_unlock_notify()
107273 */
107274
107275 #define assertMutexHeld() \
107276   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
107277
107278 /*
107279 ** Head of a linked list of all sqlite3 objects created by this process
107280 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
107281 ** is not NULL. This variable may only accessed while the STATIC_MASTER
107282 ** mutex is held.
107283 */
107284 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
107285
107286 #ifndef NDEBUG
107287 /*
107288 ** This function is a complex assert() that verifies the following 
107289 ** properties of the blocked connections list:
107290 **
107291 **   1) Each entry in the list has a non-NULL value for either 
107292 **      pUnlockConnection or pBlockingConnection, or both.
107293 **
107294 **   2) All entries in the list that share a common value for 
107295 **      xUnlockNotify are grouped together.
107296 **
107297 **   3) If the argument db is not NULL, then none of the entries in the
107298 **      blocked connections list have pUnlockConnection or pBlockingConnection
107299 **      set to db. This is used when closing connection db.
107300 */
107301 static void checkListProperties(sqlite3 *db){
107302   sqlite3 *p;
107303   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
107304     int seen = 0;
107305     sqlite3 *p2;
107306
107307     /* Verify property (1) */
107308     assert( p->pUnlockConnection || p->pBlockingConnection );
107309
107310     /* Verify property (2) */
107311     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
107312       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
107313       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
107314       assert( db==0 || p->pUnlockConnection!=db );
107315       assert( db==0 || p->pBlockingConnection!=db );
107316     }
107317   }
107318 }
107319 #else
107320 # define checkListProperties(x)
107321 #endif
107322
107323 /*
107324 ** Remove connection db from the blocked connections list. If connection
107325 ** db is not currently a part of the list, this function is a no-op.
107326 */
107327 static void removeFromBlockedList(sqlite3 *db){
107328   sqlite3 **pp;
107329   assertMutexHeld();
107330   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
107331     if( *pp==db ){
107332       *pp = (*pp)->pNextBlocked;
107333       break;
107334     }
107335   }
107336 }
107337
107338 /*
107339 ** Add connection db to the blocked connections list. It is assumed
107340 ** that it is not already a part of the list.
107341 */
107342 static void addToBlockedList(sqlite3 *db){
107343   sqlite3 **pp;
107344   assertMutexHeld();
107345   for(
107346     pp=&sqlite3BlockedList; 
107347     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
107348     pp=&(*pp)->pNextBlocked
107349   );
107350   db->pNextBlocked = *pp;
107351   *pp = db;
107352 }
107353
107354 /*
107355 ** Obtain the STATIC_MASTER mutex.
107356 */
107357 static void enterMutex(void){
107358   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
107359   checkListProperties(0);
107360 }
107361
107362 /*
107363 ** Release the STATIC_MASTER mutex.
107364 */
107365 static void leaveMutex(void){
107366   assertMutexHeld();
107367   checkListProperties(0);
107368   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
107369 }
107370
107371 /*
107372 ** Register an unlock-notify callback.
107373 **
107374 ** This is called after connection "db" has attempted some operation
107375 ** but has received an SQLITE_LOCKED error because another connection
107376 ** (call it pOther) in the same process was busy using the same shared
107377 ** cache.  pOther is found by looking at db->pBlockingConnection.
107378 **
107379 ** If there is no blocking connection, the callback is invoked immediately,
107380 ** before this routine returns.
107381 **
107382 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
107383 ** a deadlock.
107384 **
107385 ** Otherwise, make arrangements to invoke xNotify when pOther drops
107386 ** its locks.
107387 **
107388 ** Each call to this routine overrides any prior callbacks registered
107389 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
107390 ** cancelled.
107391 */
107392 SQLITE_API int sqlite3_unlock_notify(
107393   sqlite3 *db,
107394   void (*xNotify)(void **, int),
107395   void *pArg
107396 ){
107397   int rc = SQLITE_OK;
107398
107399   sqlite3_mutex_enter(db->mutex);
107400   enterMutex();
107401
107402   if( xNotify==0 ){
107403     removeFromBlockedList(db);
107404     db->pBlockingConnection = 0;
107405     db->pUnlockConnection = 0;
107406     db->xUnlockNotify = 0;
107407     db->pUnlockArg = 0;
107408   }else if( 0==db->pBlockingConnection ){
107409     /* The blocking transaction has been concluded. Or there never was a 
107410     ** blocking transaction. In either case, invoke the notify callback
107411     ** immediately. 
107412     */
107413     xNotify(&pArg, 1);
107414   }else{
107415     sqlite3 *p;
107416
107417     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
107418     if( p ){
107419       rc = SQLITE_LOCKED;              /* Deadlock detected. */
107420     }else{
107421       db->pUnlockConnection = db->pBlockingConnection;
107422       db->xUnlockNotify = xNotify;
107423       db->pUnlockArg = pArg;
107424       removeFromBlockedList(db);
107425       addToBlockedList(db);
107426     }
107427   }
107428
107429   leaveMutex();
107430   assert( !db->mallocFailed );
107431   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
107432   sqlite3_mutex_leave(db->mutex);
107433   return rc;
107434 }
107435
107436 /*
107437 ** This function is called while stepping or preparing a statement 
107438 ** associated with connection db. The operation will return SQLITE_LOCKED
107439 ** to the user because it requires a lock that will not be available
107440 ** until connection pBlocker concludes its current transaction.
107441 */
107442 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
107443   enterMutex();
107444   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
107445     addToBlockedList(db);
107446   }
107447   db->pBlockingConnection = pBlocker;
107448   leaveMutex();
107449 }
107450
107451 /*
107452 ** This function is called when
107453 ** the transaction opened by database db has just finished. Locks held 
107454 ** by database connection db have been released.
107455 **
107456 ** This function loops through each entry in the blocked connections
107457 ** list and does the following:
107458 **
107459 **   1) If the sqlite3.pBlockingConnection member of a list entry is
107460 **      set to db, then set pBlockingConnection=0.
107461 **
107462 **   2) If the sqlite3.pUnlockConnection member of a list entry is
107463 **      set to db, then invoke the configured unlock-notify callback and
107464 **      set pUnlockConnection=0.
107465 **
107466 **   3) If the two steps above mean that pBlockingConnection==0 and
107467 **      pUnlockConnection==0, remove the entry from the blocked connections
107468 **      list.
107469 */
107470 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
107471   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
107472   int nArg = 0;                            /* Number of entries in aArg[] */
107473   sqlite3 **pp;                            /* Iterator variable */
107474   void **aArg;               /* Arguments to the unlock callback */
107475   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
107476   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
107477
107478   aArg = aStatic;
107479   enterMutex();         /* Enter STATIC_MASTER mutex */
107480
107481   /* This loop runs once for each entry in the blocked-connections list. */
107482   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
107483     sqlite3 *p = *pp;
107484
107485     /* Step 1. */
107486     if( p->pBlockingConnection==db ){
107487       p->pBlockingConnection = 0;
107488     }
107489
107490     /* Step 2. */
107491     if( p->pUnlockConnection==db ){
107492       assert( p->xUnlockNotify );
107493       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
107494         xUnlockNotify(aArg, nArg);
107495         nArg = 0;
107496       }
107497
107498       sqlite3BeginBenignMalloc();
107499       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
107500       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
107501       if( (!aDyn && nArg==(int)ArraySize(aStatic))
107502        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
107503       ){
107504         /* The aArg[] array needs to grow. */
107505         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
107506         if( pNew ){
107507           memcpy(pNew, aArg, nArg*sizeof(void *));
107508           sqlite3_free(aDyn);
107509           aDyn = aArg = pNew;
107510         }else{
107511           /* This occurs when the array of context pointers that need to
107512           ** be passed to the unlock-notify callback is larger than the
107513           ** aStatic[] array allocated on the stack and the attempt to 
107514           ** allocate a larger array from the heap has failed.
107515           **
107516           ** This is a difficult situation to handle. Returning an error
107517           ** code to the caller is insufficient, as even if an error code
107518           ** is returned the transaction on connection db will still be
107519           ** closed and the unlock-notify callbacks on blocked connections
107520           ** will go unissued. This might cause the application to wait
107521           ** indefinitely for an unlock-notify callback that will never 
107522           ** arrive.
107523           **
107524           ** Instead, invoke the unlock-notify callback with the context
107525           ** array already accumulated. We can then clear the array and
107526           ** begin accumulating any further context pointers without 
107527           ** requiring any dynamic allocation. This is sub-optimal because
107528           ** it means that instead of one callback with a large array of
107529           ** context pointers the application will receive two or more
107530           ** callbacks with smaller arrays of context pointers, which will
107531           ** reduce the applications ability to prioritize multiple 
107532           ** connections. But it is the best that can be done under the
107533           ** circumstances.
107534           */
107535           xUnlockNotify(aArg, nArg);
107536           nArg = 0;
107537         }
107538       }
107539       sqlite3EndBenignMalloc();
107540
107541       aArg[nArg++] = p->pUnlockArg;
107542       xUnlockNotify = p->xUnlockNotify;
107543       p->pUnlockConnection = 0;
107544       p->xUnlockNotify = 0;
107545       p->pUnlockArg = 0;
107546     }
107547
107548     /* Step 3. */
107549     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
107550       /* Remove connection p from the blocked connections list. */
107551       *pp = p->pNextBlocked;
107552       p->pNextBlocked = 0;
107553     }else{
107554       pp = &p->pNextBlocked;
107555     }
107556   }
107557
107558   if( nArg!=0 ){
107559     xUnlockNotify(aArg, nArg);
107560   }
107561   sqlite3_free(aDyn);
107562   leaveMutex();         /* Leave STATIC_MASTER mutex */
107563 }
107564
107565 /*
107566 ** This is called when the database connection passed as an argument is 
107567 ** being closed. The connection is removed from the blocked list.
107568 */
107569 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
107570   sqlite3ConnectionUnlocked(db);
107571   enterMutex();
107572   removeFromBlockedList(db);
107573   checkListProperties(db);
107574   leaveMutex();
107575 }
107576 #endif
107577
107578 /************** End of notify.c **********************************************/
107579 /************** Begin file fts3.c ********************************************/
107580 /*
107581 ** 2006 Oct 10
107582 **
107583 ** The author disclaims copyright to this source code.  In place of
107584 ** a legal notice, here is a blessing:
107585 **
107586 **    May you do good and not evil.
107587 **    May you find forgiveness for yourself and forgive others.
107588 **    May you share freely, never taking more than you give.
107589 **
107590 ******************************************************************************
107591 **
107592 ** This is an SQLite module implementing full-text search.
107593 */
107594
107595 /*
107596 ** The code in this file is only compiled if:
107597 **
107598 **     * The FTS3 module is being built as an extension
107599 **       (in which case SQLITE_CORE is not defined), or
107600 **
107601 **     * The FTS3 module is being built into the core of
107602 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
107603 */
107604
107605 /* The full-text index is stored in a series of b+tree (-like)
107606 ** structures called segments which map terms to doclists.  The
107607 ** structures are like b+trees in layout, but are constructed from the
107608 ** bottom up in optimal fashion and are not updatable.  Since trees
107609 ** are built from the bottom up, things will be described from the
107610 ** bottom up.
107611 **
107612 **
107613 **** Varints ****
107614 ** The basic unit of encoding is a variable-length integer called a
107615 ** varint.  We encode variable-length integers in little-endian order
107616 ** using seven bits * per byte as follows:
107617 **
107618 ** KEY:
107619 **         A = 0xxxxxxx    7 bits of data and one flag bit
107620 **         B = 1xxxxxxx    7 bits of data and one flag bit
107621 **
107622 **  7 bits - A
107623 ** 14 bits - BA
107624 ** 21 bits - BBA
107625 ** and so on.
107626 **
107627 ** This is similar in concept to how sqlite encodes "varints" but
107628 ** the encoding is not the same.  SQLite varints are big-endian
107629 ** are are limited to 9 bytes in length whereas FTS3 varints are
107630 ** little-endian and can be up to 10 bytes in length (in theory).
107631 **
107632 ** Example encodings:
107633 **
107634 **     1:    0x01
107635 **   127:    0x7f
107636 **   128:    0x81 0x00
107637 **
107638 **
107639 **** Document lists ****
107640 ** A doclist (document list) holds a docid-sorted list of hits for a
107641 ** given term.  Doclists hold docids and associated token positions.
107642 ** A docid is the unique integer identifier for a single document.
107643 ** A position is the index of a word within the document.  The first 
107644 ** word of the document has a position of 0.
107645 **
107646 ** FTS3 used to optionally store character offsets using a compile-time
107647 ** option.  But that functionality is no longer supported.
107648 **
107649 ** A doclist is stored like this:
107650 **
107651 ** array {
107652 **   varint docid;
107653 **   array {                (position list for column 0)
107654 **     varint position;     (2 more than the delta from previous position)
107655 **   }
107656 **   array {
107657 **     varint POS_COLUMN;   (marks start of position list for new column)
107658 **     varint column;       (index of new column)
107659 **     array {
107660 **       varint position;   (2 more than the delta from previous position)
107661 **     }
107662 **   }
107663 **   varint POS_END;        (marks end of positions for this document.
107664 ** }
107665 **
107666 ** Here, array { X } means zero or more occurrences of X, adjacent in
107667 ** memory.  A "position" is an index of a token in the token stream
107668 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
107669 ** in the same logical place as the position element, and act as sentinals
107670 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
107671 ** The positions numbers are not stored literally but rather as two more
107672 ** than the difference from the prior position, or the just the position plus
107673 ** 2 for the first position.  Example:
107674 **
107675 **   label:       A B C D E  F  G H   I  J K
107676 **   value:     123 5 9 1 1 14 35 0 234 72 0
107677 **
107678 ** The 123 value is the first docid.  For column zero in this document
107679 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
107680 ** at D signals the start of a new column; the 1 at E indicates that the
107681 ** new column is column number 1.  There are two positions at 12 and 45
107682 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
107683 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
107684 ** terminates with the 0 at K.
107685 **
107686 ** A "position-list" is the list of positions for multiple columns for
107687 ** a single docid.  A "column-list" is the set of positions for a single
107688 ** column.  Hence, a position-list consists of one or more column-lists,
107689 ** a document record consists of a docid followed by a position-list and
107690 ** a doclist consists of one or more document records.
107691 **
107692 ** A bare doclist omits the position information, becoming an 
107693 ** array of varint-encoded docids.
107694 **
107695 **** Segment leaf nodes ****
107696 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
107697 ** nodes are written using LeafWriter, and read using LeafReader (to
107698 ** iterate through a single leaf node's data) and LeavesReader (to
107699 ** iterate through a segment's entire leaf layer).  Leaf nodes have
107700 ** the format:
107701 **
107702 ** varint iHeight;             (height from leaf level, always 0)
107703 ** varint nTerm;               (length of first term)
107704 ** char pTerm[nTerm];          (content of first term)
107705 ** varint nDoclist;            (length of term's associated doclist)
107706 ** char pDoclist[nDoclist];    (content of doclist)
107707 ** array {
107708 **                             (further terms are delta-encoded)
107709 **   varint nPrefix;           (length of prefix shared with previous term)
107710 **   varint nSuffix;           (length of unshared suffix)
107711 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
107712 **   varint nDoclist;          (length of term's associated doclist)
107713 **   char pDoclist[nDoclist];  (content of doclist)
107714 ** }
107715 **
107716 ** Here, array { X } means zero or more occurrences of X, adjacent in
107717 ** memory.
107718 **
107719 ** Leaf nodes are broken into blocks which are stored contiguously in
107720 ** the %_segments table in sorted order.  This means that when the end
107721 ** of a node is reached, the next term is in the node with the next
107722 ** greater node id.
107723 **
107724 ** New data is spilled to a new leaf node when the current node
107725 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
107726 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
107727 ** node (a leaf node with a single term and doclist).  The goal of
107728 ** these settings is to pack together groups of small doclists while
107729 ** making it efficient to directly access large doclists.  The
107730 ** assumption is that large doclists represent terms which are more
107731 ** likely to be query targets.
107732 **
107733 ** TODO(shess) It may be useful for blocking decisions to be more
107734 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
107735 ** node rather than splitting into 2k and .5k nodes.  My intuition is
107736 ** that this might extend through 2x or 4x the pagesize.
107737 **
107738 **
107739 **** Segment interior nodes ****
107740 ** Segment interior nodes store blockids for subtree nodes and terms
107741 ** to describe what data is stored by the each subtree.  Interior
107742 ** nodes are written using InteriorWriter, and read using
107743 ** InteriorReader.  InteriorWriters are created as needed when
107744 ** SegmentWriter creates new leaf nodes, or when an interior node
107745 ** itself grows too big and must be split.  The format of interior
107746 ** nodes:
107747 **
107748 ** varint iHeight;           (height from leaf level, always >0)
107749 ** varint iBlockid;          (block id of node's leftmost subtree)
107750 ** optional {
107751 **   varint nTerm;           (length of first term)
107752 **   char pTerm[nTerm];      (content of first term)
107753 **   array {
107754 **                                (further terms are delta-encoded)
107755 **     varint nPrefix;            (length of shared prefix with previous term)
107756 **     varint nSuffix;            (length of unshared suffix)
107757 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
107758 **   }
107759 ** }
107760 **
107761 ** Here, optional { X } means an optional element, while array { X }
107762 ** means zero or more occurrences of X, adjacent in memory.
107763 **
107764 ** An interior node encodes n terms separating n+1 subtrees.  The
107765 ** subtree blocks are contiguous, so only the first subtree's blockid
107766 ** is encoded.  The subtree at iBlockid will contain all terms less
107767 ** than the first term encoded (or all terms if no term is encoded).
107768 ** Otherwise, for terms greater than or equal to pTerm[i] but less
107769 ** than pTerm[i+1], the subtree for that term will be rooted at
107770 ** iBlockid+i.  Interior nodes only store enough term data to
107771 ** distinguish adjacent children (if the rightmost term of the left
107772 ** child is "something", and the leftmost term of the right child is
107773 ** "wicked", only "w" is stored).
107774 **
107775 ** New data is spilled to a new interior node at the same height when
107776 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
107777 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
107778 ** interior nodes and making the tree too skinny.  The interior nodes
107779 ** at a given height are naturally tracked by interior nodes at
107780 ** height+1, and so on.
107781 **
107782 **
107783 **** Segment directory ****
107784 ** The segment directory in table %_segdir stores meta-information for
107785 ** merging and deleting segments, and also the root node of the
107786 ** segment's tree.
107787 **
107788 ** The root node is the top node of the segment's tree after encoding
107789 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
107790 ** This could be either a leaf node or an interior node.  If the top
107791 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
107792 ** and a new root interior node is generated (which should always fit
107793 ** within ROOT_MAX because it only needs space for 2 varints, the
107794 ** height and the blockid of the previous root).
107795 **
107796 ** The meta-information in the segment directory is:
107797 **   level               - segment level (see below)
107798 **   idx                 - index within level
107799 **                       - (level,idx uniquely identify a segment)
107800 **   start_block         - first leaf node
107801 **   leaves_end_block    - last leaf node
107802 **   end_block           - last block (including interior nodes)
107803 **   root                - contents of root node
107804 **
107805 ** If the root node is a leaf node, then start_block,
107806 ** leaves_end_block, and end_block are all 0.
107807 **
107808 **
107809 **** Segment merging ****
107810 ** To amortize update costs, segments are grouped into levels and
107811 ** merged in batches.  Each increase in level represents exponentially
107812 ** more documents.
107813 **
107814 ** New documents (actually, document updates) are tokenized and
107815 ** written individually (using LeafWriter) to a level 0 segment, with
107816 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
107817 ** level 0 segments are merged into a single level 1 segment.  Level 1
107818 ** is populated like level 0, and eventually MERGE_COUNT level 1
107819 ** segments are merged to a single level 2 segment (representing
107820 ** MERGE_COUNT^2 updates), and so on.
107821 **
107822 ** A segment merge traverses all segments at a given level in
107823 ** parallel, performing a straightforward sorted merge.  Since segment
107824 ** leaf nodes are written in to the %_segments table in order, this
107825 ** merge traverses the underlying sqlite disk structures efficiently.
107826 ** After the merge, all segment blocks from the merged level are
107827 ** deleted.
107828 **
107829 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
107830 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
107831 ** very similar performance numbers to 16 on insertion, though they're
107832 ** a tiny bit slower (perhaps due to more overhead in merge-time
107833 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
107834 ** 16, 2 about 66% slower than 16.
107835 **
107836 ** At query time, high MERGE_COUNT increases the number of segments
107837 ** which need to be scanned and merged.  For instance, with 100k docs
107838 ** inserted:
107839 **
107840 **    MERGE_COUNT   segments
107841 **       16           25
107842 **        8           12
107843 **        4           10
107844 **        2            6
107845 **
107846 ** This appears to have only a moderate impact on queries for very
107847 ** frequent terms (which are somewhat dominated by segment merge
107848 ** costs), and infrequent and non-existent terms still seem to be fast
107849 ** even with many segments.
107850 **
107851 ** TODO(shess) That said, it would be nice to have a better query-side
107852 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
107853 ** optimizations to things like doclist merging will swing the sweet
107854 ** spot around.
107855 **
107856 **
107857 **
107858 **** Handling of deletions and updates ****
107859 ** Since we're using a segmented structure, with no docid-oriented
107860 ** index into the term index, we clearly cannot simply update the term
107861 ** index when a document is deleted or updated.  For deletions, we
107862 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
107863 ** we simply write the new doclist.  Segment merges overwrite older
107864 ** data for a particular docid with newer data, so deletes or updates
107865 ** will eventually overtake the earlier data and knock it out.  The
107866 ** query logic likewise merges doclists so that newer data knocks out
107867 ** older data.
107868 **
107869 ** TODO(shess) Provide a VACUUM type operation to clear out all
107870 ** deletions and duplications.  This would basically be a forced merge
107871 ** into a single segment.
107872 */
107873
107874 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
107875
107876 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
107877 # define SQLITE_CORE 1
107878 #endif
107879
107880 /************** Include fts3Int.h in the middle of fts3.c ********************/
107881 /************** Begin file fts3Int.h *****************************************/
107882 /*
107883 ** 2009 Nov 12
107884 **
107885 ** The author disclaims copyright to this source code.  In place of
107886 ** a legal notice, here is a blessing:
107887 **
107888 **    May you do good and not evil.
107889 **    May you find forgiveness for yourself and forgive others.
107890 **    May you share freely, never taking more than you give.
107891 **
107892 ******************************************************************************
107893 **
107894 */
107895
107896 #ifndef _FTSINT_H
107897 #define _FTSINT_H
107898
107899 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
107900 # define NDEBUG 1
107901 #endif
107902
107903 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
107904 /************** Begin file fts3_tokenizer.h **********************************/
107905 /*
107906 ** 2006 July 10
107907 **
107908 ** The author disclaims copyright to this source code.
107909 **
107910 *************************************************************************
107911 ** Defines the interface to tokenizers used by fulltext-search.  There
107912 ** are three basic components:
107913 **
107914 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
107915 ** interface functions.  This is essentially the class structure for
107916 ** tokenizers.
107917 **
107918 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
107919 ** including customization information defined at creation time.
107920 **
107921 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
107922 ** tokens from a particular input.
107923 */
107924 #ifndef _FTS3_TOKENIZER_H_
107925 #define _FTS3_TOKENIZER_H_
107926
107927 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
107928 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
107929 ** we will need a way to register the API consistently.
107930 */
107931
107932 /*
107933 ** Structures used by the tokenizer interface. When a new tokenizer
107934 ** implementation is registered, the caller provides a pointer to
107935 ** an sqlite3_tokenizer_module containing pointers to the callback
107936 ** functions that make up an implementation.
107937 **
107938 ** When an fts3 table is created, it passes any arguments passed to
107939 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
107940 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
107941 ** implementation. The xCreate() function in turn returns an 
107942 ** sqlite3_tokenizer structure representing the specific tokenizer to
107943 ** be used for the fts3 table (customized by the tokenizer clause arguments).
107944 **
107945 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
107946 ** method is called. It returns an sqlite3_tokenizer_cursor object
107947 ** that may be used to tokenize a specific input buffer based on
107948 ** the tokenization rules supplied by a specific sqlite3_tokenizer
107949 ** object.
107950 */
107951 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
107952 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
107953 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
107954
107955 struct sqlite3_tokenizer_module {
107956
107957   /*
107958   ** Structure version. Should always be set to 0.
107959   */
107960   int iVersion;
107961
107962   /*
107963   ** Create a new tokenizer. The values in the argv[] array are the
107964   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
107965   ** TABLE statement that created the fts3 table. For example, if
107966   ** the following SQL is executed:
107967   **
107968   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
107969   **
107970   ** then argc is set to 2, and the argv[] array contains pointers
107971   ** to the strings "arg1" and "arg2".
107972   **
107973   ** This method should return either SQLITE_OK (0), or an SQLite error 
107974   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
107975   ** to point at the newly created tokenizer structure. The generic
107976   ** sqlite3_tokenizer.pModule variable should not be initialised by
107977   ** this callback. The caller will do so.
107978   */
107979   int (*xCreate)(
107980     int argc,                           /* Size of argv array */
107981     const char *const*argv,             /* Tokenizer argument strings */
107982     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
107983   );
107984
107985   /*
107986   ** Destroy an existing tokenizer. The fts3 module calls this method
107987   ** exactly once for each successful call to xCreate().
107988   */
107989   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
107990
107991   /*
107992   ** Create a tokenizer cursor to tokenize an input buffer. The caller
107993   ** is responsible for ensuring that the input buffer remains valid
107994   ** until the cursor is closed (using the xClose() method). 
107995   */
107996   int (*xOpen)(
107997     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
107998     const char *pInput, int nBytes,      /* Input buffer */
107999     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
108000   );
108001
108002   /*
108003   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
108004   ** method exactly once for each successful call to xOpen().
108005   */
108006   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
108007
108008   /*
108009   ** Retrieve the next token from the tokenizer cursor pCursor. This
108010   ** method should either return SQLITE_OK and set the values of the
108011   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
108012   ** the end of the buffer has been reached, or an SQLite error code.
108013   **
108014   ** *ppToken should be set to point at a buffer containing the 
108015   ** normalized version of the token (i.e. after any case-folding and/or
108016   ** stemming has been performed). *pnBytes should be set to the length
108017   ** of this buffer in bytes. The input text that generated the token is
108018   ** identified by the byte offsets returned in *piStartOffset and
108019   ** *piEndOffset. *piStartOffset should be set to the index of the first
108020   ** byte of the token in the input buffer. *piEndOffset should be set
108021   ** to the index of the first byte just past the end of the token in
108022   ** the input buffer.
108023   **
108024   ** The buffer *ppToken is set to point at is managed by the tokenizer
108025   ** implementation. It is only required to be valid until the next call
108026   ** to xNext() or xClose(). 
108027   */
108028   /* TODO(shess) current implementation requires pInput to be
108029   ** nul-terminated.  This should either be fixed, or pInput/nBytes
108030   ** should be converted to zInput.
108031   */
108032   int (*xNext)(
108033     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
108034     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
108035     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
108036     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
108037     int *piPosition      /* OUT: Number of tokens returned before this one */
108038   );
108039 };
108040
108041 struct sqlite3_tokenizer {
108042   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
108043   /* Tokenizer implementations will typically add additional fields */
108044 };
108045
108046 struct sqlite3_tokenizer_cursor {
108047   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
108048   /* Tokenizer implementations will typically add additional fields */
108049 };
108050
108051 int fts3_global_term_cnt(int iTerm, int iCol);
108052 int fts3_term_cnt(int iTerm, int iCol);
108053
108054
108055 #endif /* _FTS3_TOKENIZER_H_ */
108056
108057 /************** End of fts3_tokenizer.h **************************************/
108058 /************** Continuing where we left off in fts3Int.h ********************/
108059 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
108060 /************** Begin file fts3_hash.h ***************************************/
108061 /*
108062 ** 2001 September 22
108063 **
108064 ** The author disclaims copyright to this source code.  In place of
108065 ** a legal notice, here is a blessing:
108066 **
108067 **    May you do good and not evil.
108068 **    May you find forgiveness for yourself and forgive others.
108069 **    May you share freely, never taking more than you give.
108070 **
108071 *************************************************************************
108072 ** This is the header file for the generic hash-table implemenation
108073 ** used in SQLite.  We've modified it slightly to serve as a standalone
108074 ** hash table implementation for the full-text indexing module.
108075 **
108076 */
108077 #ifndef _FTS3_HASH_H_
108078 #define _FTS3_HASH_H_
108079
108080 /* Forward declarations of structures. */
108081 typedef struct Fts3Hash Fts3Hash;
108082 typedef struct Fts3HashElem Fts3HashElem;
108083
108084 /* A complete hash table is an instance of the following structure.
108085 ** The internals of this structure are intended to be opaque -- client
108086 ** code should not attempt to access or modify the fields of this structure
108087 ** directly.  Change this structure only by using the routines below.
108088 ** However, many of the "procedures" and "functions" for modifying and
108089 ** accessing this structure are really macros, so we can't really make
108090 ** this structure opaque.
108091 */
108092 struct Fts3Hash {
108093   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
108094   char copyKey;           /* True if copy of key made on insert */
108095   int count;              /* Number of entries in this table */
108096   Fts3HashElem *first;    /* The first element of the array */
108097   int htsize;             /* Number of buckets in the hash table */
108098   struct _fts3ht {        /* the hash table */
108099     int count;               /* Number of entries with this hash */
108100     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
108101   } *ht;
108102 };
108103
108104 /* Each element in the hash table is an instance of the following 
108105 ** structure.  All elements are stored on a single doubly-linked list.
108106 **
108107 ** Again, this structure is intended to be opaque, but it can't really
108108 ** be opaque because it is used by macros.
108109 */
108110 struct Fts3HashElem {
108111   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
108112   void *data;                /* Data associated with this element */
108113   void *pKey; int nKey;      /* Key associated with this element */
108114 };
108115
108116 /*
108117 ** There are 2 different modes of operation for a hash table:
108118 **
108119 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
108120 **                           (including the null-terminator, if any).  Case
108121 **                           is respected in comparisons.
108122 **
108123 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
108124 **                           memcmp() is used to compare keys.
108125 **
108126 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
108127 */
108128 #define FTS3_HASH_STRING    1
108129 #define FTS3_HASH_BINARY    2
108130
108131 /*
108132 ** Access routines.  To delete, insert a NULL pointer.
108133 */
108134 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
108135 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
108136 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
108137 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
108138 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
108139
108140 /*
108141 ** Shorthand for the functions above
108142 */
108143 #define fts3HashInit     sqlite3Fts3HashInit
108144 #define fts3HashInsert   sqlite3Fts3HashInsert
108145 #define fts3HashFind     sqlite3Fts3HashFind
108146 #define fts3HashClear    sqlite3Fts3HashClear
108147 #define fts3HashFindElem sqlite3Fts3HashFindElem
108148
108149 /*
108150 ** Macros for looping over all elements of a hash table.  The idiom is
108151 ** like this:
108152 **
108153 **   Fts3Hash h;
108154 **   Fts3HashElem *p;
108155 **   ...
108156 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
108157 **     SomeStructure *pData = fts3HashData(p);
108158 **     // do something with pData
108159 **   }
108160 */
108161 #define fts3HashFirst(H)  ((H)->first)
108162 #define fts3HashNext(E)   ((E)->next)
108163 #define fts3HashData(E)   ((E)->data)
108164 #define fts3HashKey(E)    ((E)->pKey)
108165 #define fts3HashKeysize(E) ((E)->nKey)
108166
108167 /*
108168 ** Number of entries in a hash table
108169 */
108170 #define fts3HashCount(H)  ((H)->count)
108171
108172 #endif /* _FTS3_HASH_H_ */
108173
108174 /************** End of fts3_hash.h *******************************************/
108175 /************** Continuing where we left off in fts3Int.h ********************/
108176
108177 /*
108178 ** This constant controls how often segments are merged. Once there are
108179 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
108180 ** segment of level N+1.
108181 */
108182 #define FTS3_MERGE_COUNT 16
108183
108184 /*
108185 ** This is the maximum amount of data (in bytes) to store in the 
108186 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
108187 ** populated as documents are inserted/updated/deleted in a transaction
108188 ** and used to create a new segment when the transaction is committed.
108189 ** However if this limit is reached midway through a transaction, a new 
108190 ** segment is created and the hash table cleared immediately.
108191 */
108192 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
108193
108194 /*
108195 ** Macro to return the number of elements in an array. SQLite has a
108196 ** similar macro called ArraySize(). Use a different name to avoid
108197 ** a collision when building an amalgamation with built-in FTS3.
108198 */
108199 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
108200
108201 /*
108202 ** Maximum length of a varint encoded integer. The varint format is different
108203 ** from that used by SQLite, so the maximum length is 10, not 9.
108204 */
108205 #define FTS3_VARINT_MAX 10
108206
108207 /*
108208 ** The testcase() macro is only used by the amalgamation.  If undefined,
108209 ** make it a no-op.
108210 */
108211 #ifndef testcase
108212 # define testcase(X)
108213 #endif
108214
108215 /*
108216 ** Terminator values for position-lists and column-lists.
108217 */
108218 #define POS_COLUMN  (1)     /* Column-list terminator */
108219 #define POS_END     (0)     /* Position-list terminator */ 
108220
108221 /*
108222 ** This section provides definitions to allow the
108223 ** FTS3 extension to be compiled outside of the 
108224 ** amalgamation.
108225 */
108226 #ifndef SQLITE_AMALGAMATION
108227 /*
108228 ** Macros indicating that conditional expressions are always true or
108229 ** false.
108230 */
108231 #ifdef SQLITE_COVERAGE_TEST
108232 # define ALWAYS(x) (1)
108233 # define NEVER(X)  (0)
108234 #else
108235 # define ALWAYS(x) (x)
108236 # define NEVER(X)  (x)
108237 #endif
108238
108239 /*
108240 ** Internal types used by SQLite.
108241 */
108242 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
108243 typedef short int i16;            /* 2-byte (or larger) signed integer */
108244 typedef unsigned int u32;         /* 4-byte unsigned integer */
108245 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
108246 /*
108247 ** Macro used to suppress compiler warnings for unused parameters.
108248 */
108249 #define UNUSED_PARAMETER(x) (void)(x)
108250 #endif
108251
108252 typedef struct Fts3Table Fts3Table;
108253 typedef struct Fts3Cursor Fts3Cursor;
108254 typedef struct Fts3Expr Fts3Expr;
108255 typedef struct Fts3Phrase Fts3Phrase;
108256 typedef struct Fts3PhraseToken Fts3PhraseToken;
108257
108258 typedef struct Fts3SegFilter Fts3SegFilter;
108259 typedef struct Fts3DeferredToken Fts3DeferredToken;
108260 typedef struct Fts3SegReader Fts3SegReader;
108261 typedef struct Fts3SegReaderArray Fts3SegReaderArray;
108262
108263 /*
108264 ** A connection to a fulltext index is an instance of the following
108265 ** structure. The xCreate and xConnect methods create an instance
108266 ** of this structure and xDestroy and xDisconnect free that instance.
108267 ** All other methods receive a pointer to the structure as one of their
108268 ** arguments.
108269 */
108270 struct Fts3Table {
108271   sqlite3_vtab base;              /* Base class used by SQLite core */
108272   sqlite3 *db;                    /* The database connection */
108273   const char *zDb;                /* logical database name */
108274   const char *zName;              /* virtual table name */
108275   int nColumn;                    /* number of named columns in virtual table */
108276   char **azColumn;                /* column names.  malloced */
108277   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
108278
108279   /* Precompiled statements used by the implementation. Each of these 
108280   ** statements is run and reset within a single virtual table API call. 
108281   */
108282   sqlite3_stmt *aStmt[24];
108283
108284   int nNodeSize;                  /* Soft limit for node size */
108285   u8 bHasStat;                    /* True if %_stat table exists */
108286   u8 bHasDocsize;                 /* True if %_docsize table exists */
108287   int nPgsz;                      /* Page size for host database */
108288   char *zSegmentsTbl;             /* Name of %_segments table */
108289   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
108290
108291   /* The following hash table is used to buffer pending index updates during
108292   ** transactions. Variable nPendingData estimates the memory size of the 
108293   ** pending data, including hash table overhead, but not malloc overhead. 
108294   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
108295   ** automatically. Variable iPrevDocid is the docid of the most recently
108296   ** inserted record.
108297   */
108298   int nMaxPendingData;
108299   int nPendingData;
108300   sqlite_int64 iPrevDocid;
108301   Fts3Hash pendingTerms;
108302 };
108303
108304 /*
108305 ** When the core wants to read from the virtual table, it creates a
108306 ** virtual table cursor (an instance of the following structure) using
108307 ** the xOpen method. Cursors are destroyed using the xClose method.
108308 */
108309 struct Fts3Cursor {
108310   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
108311   i16 eSearch;                    /* Search strategy (see below) */
108312   u8 isEof;                       /* True if at End Of Results */
108313   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
108314   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
108315   Fts3Expr *pExpr;                /* Parsed MATCH query string */
108316   int nPhrase;                    /* Number of matchable phrases in query */
108317   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
108318   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
108319   char *pNextId;                  /* Pointer into the body of aDoclist */
108320   char *aDoclist;                 /* List of docids for full-text queries */
108321   int nDoclist;                   /* Size of buffer at aDoclist */
108322   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
108323   int nRowAvg;                    /* Average size of database rows, in pages */
108324
108325   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
108326   u32 *aMatchinfo;                /* Information about most recent match */
108327   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
108328   char *zMatchinfo;               /* Matchinfo specification */
108329 };
108330
108331 #define FTS3_EVAL_FILTER    0
108332 #define FTS3_EVAL_NEXT      1
108333 #define FTS3_EVAL_MATCHINFO 2
108334
108335 /*
108336 ** The Fts3Cursor.eSearch member is always set to one of the following.
108337 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
108338 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
108339 ** of the column to be searched.  For example, in
108340 **
108341 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
108342 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
108343 ** 
108344 ** Because the LHS of the MATCH operator is 2nd column "b",
108345 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
108346 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
108347 ** indicating that all columns should be searched,
108348 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
108349 */
108350 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
108351 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
108352 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
108353
108354 /*
108355 ** A "phrase" is a sequence of one or more tokens that must match in
108356 ** sequence.  A single token is the base case and the most common case.
108357 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
108358 ** nToken will be the number of tokens in the string.
108359 **
108360 ** The nDocMatch and nMatch variables contain data that may be used by the
108361 ** matchinfo() function. They are populated when the full-text index is 
108362 ** queried for hits on the phrase. If one or more tokens in the phrase
108363 ** are deferred, the nDocMatch and nMatch variables are populated based
108364 ** on the assumption that the 
108365 */
108366 struct Fts3PhraseToken {
108367   char *z;                        /* Text of the token */
108368   int n;                          /* Number of bytes in buffer z */
108369   int isPrefix;                   /* True if token ends with a "*" character */
108370   int bFulltext;                  /* True if full-text index was used */
108371   Fts3SegReaderArray *pArray;     /* Segment-reader for this token */
108372   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
108373 };
108374
108375 struct Fts3Phrase {
108376   /* Variables populated by fts3_expr.c when parsing a MATCH expression */
108377   int nToken;                /* Number of tokens in the phrase */
108378   int iColumn;               /* Index of column this phrase must match */
108379   int isNot;                 /* Phrase prefixed by unary not (-) operator */
108380   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
108381 };
108382
108383 /*
108384 ** A tree of these objects forms the RHS of a MATCH operator.
108385 **
108386 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
108387 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes, 
108388 ** containing the results of the NEAR or phrase query in FTS3 doclist
108389 ** format. As usual, the initial "Length" field found in doclists stored
108390 ** on disk is omitted from this buffer.
108391 **
108392 ** Variable pCurrent always points to the start of a docid field within
108393 ** aDoclist. Since the doclist is usually scanned in docid order, this can
108394 ** be used to accelerate seeking to the required docid within the doclist.
108395 */
108396 struct Fts3Expr {
108397   int eType;                 /* One of the FTSQUERY_XXX values defined below */
108398   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
108399   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
108400   Fts3Expr *pLeft;           /* Left operand */
108401   Fts3Expr *pRight;          /* Right operand */
108402   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
108403
108404   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
108405   char *aDoclist;            /* Buffer containing doclist */
108406   int nDoclist;              /* Size of aDoclist in bytes */
108407
108408   sqlite3_int64 iCurrent;
108409   char *pCurrent;
108410 };
108411
108412 /*
108413 ** Candidate values for Fts3Query.eType. Note that the order of the first
108414 ** four values is in order of precedence when parsing expressions. For 
108415 ** example, the following:
108416 **
108417 **   "a OR b AND c NOT d NEAR e"
108418 **
108419 ** is equivalent to:
108420 **
108421 **   "a OR (b AND (c NOT (d NEAR e)))"
108422 */
108423 #define FTSQUERY_NEAR   1
108424 #define FTSQUERY_NOT    2
108425 #define FTSQUERY_AND    3
108426 #define FTSQUERY_OR     4
108427 #define FTSQUERY_PHRASE 5
108428
108429
108430 /* fts3_write.c */
108431 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
108432 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
108433 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
108434 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
108435 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
108436   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
108437 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
108438 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
108439 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
108440   Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
108441   int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
108442 );
108443 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(Fts3Cursor *, Fts3SegReader *, int *);
108444 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
108445 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
108446 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*);
108447
108448 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
108449 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
108450
108451 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
108452 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
108453 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
108454 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
108455 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *, int *);
108456
108457 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
108458
108459 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
108460 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
108461 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
108462 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
108463 #define FTS3_SEGMENT_PREFIX        0x00000008
108464
108465 /* Type passed as 4th argument to SegmentReaderIterate() */
108466 struct Fts3SegFilter {
108467   const char *zTerm;
108468   int nTerm;
108469   int iCol;
108470   int flags;
108471 };
108472
108473 /* fts3.c */
108474 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
108475 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
108476 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
108477 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
108478 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
108479
108480 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
108481 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *, Fts3Expr *);
108482 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(Fts3Cursor *, Fts3Expr *, char **, int *);
108483 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
108484
108485 /* fts3_tokenizer.c */
108486 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
108487 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
108488 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
108489     sqlite3_tokenizer **, char **
108490 );
108491 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
108492
108493 /* fts3_snippet.c */
108494 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
108495 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
108496   const char *, const char *, int, int
108497 );
108498 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
108499
108500 /* fts3_expr.c */
108501 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, 
108502   char **, int, int, const char *, int, Fts3Expr **
108503 );
108504 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
108505 #ifdef SQLITE_TEST
108506 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
108507 #endif
108508
108509 #endif /* _FTSINT_H */
108510
108511 /************** End of fts3Int.h *********************************************/
108512 /************** Continuing where we left off in fts3.c ***********************/
108513
108514
108515 #ifndef SQLITE_CORE 
108516   SQLITE_EXTENSION_INIT1
108517 #endif
108518
108519 /* 
108520 ** Write a 64-bit variable-length integer to memory starting at p[0].
108521 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
108522 ** The number of bytes written is returned.
108523 */
108524 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
108525   unsigned char *q = (unsigned char *) p;
108526   sqlite_uint64 vu = v;
108527   do{
108528     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
108529     vu >>= 7;
108530   }while( vu!=0 );
108531   q[-1] &= 0x7f;  /* turn off high bit in final byte */
108532   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
108533   return (int) (q - (unsigned char *)p);
108534 }
108535
108536 /* 
108537 ** Read a 64-bit variable-length integer from memory starting at p[0].
108538 ** Return the number of bytes read, or 0 on error.
108539 ** The value is stored in *v.
108540 */
108541 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
108542   const unsigned char *q = (const unsigned char *) p;
108543   sqlite_uint64 x = 0, y = 1;
108544   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
108545     x += y * (*q++ & 0x7f);
108546     y <<= 7;
108547   }
108548   x += y * (*q++);
108549   *v = (sqlite_int64) x;
108550   return (int) (q - (unsigned char *)p);
108551 }
108552
108553 /*
108554 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
108555 ** 32-bit integer before it is returned.
108556 */
108557 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
108558  sqlite_int64 i;
108559  int ret = sqlite3Fts3GetVarint(p, &i);
108560  *pi = (int) i;
108561  return ret;
108562 }
108563
108564 /*
108565 ** Return the number of bytes required to encode v as a varint
108566 */
108567 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
108568   int i = 0;
108569   do{
108570     i++;
108571     v >>= 7;
108572   }while( v!=0 );
108573   return i;
108574 }
108575
108576 /*
108577 ** Convert an SQL-style quoted string into a normal string by removing
108578 ** the quote characters.  The conversion is done in-place.  If the
108579 ** input does not begin with a quote character, then this routine
108580 ** is a no-op.
108581 **
108582 ** Examples:
108583 **
108584 **     "abc"   becomes   abc
108585 **     'xyz'   becomes   xyz
108586 **     [pqr]   becomes   pqr
108587 **     `mno`   becomes   mno
108588 **
108589 */
108590 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
108591   char quote;                     /* Quote character (if any ) */
108592
108593   quote = z[0];
108594   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
108595     int iIn = 1;                  /* Index of next byte to read from input */
108596     int iOut = 0;                 /* Index of next byte to write to output */
108597
108598     /* If the first byte was a '[', then the close-quote character is a ']' */
108599     if( quote=='[' ) quote = ']';  
108600
108601     while( ALWAYS(z[iIn]) ){
108602       if( z[iIn]==quote ){
108603         if( z[iIn+1]!=quote ) break;
108604         z[iOut++] = quote;
108605         iIn += 2;
108606       }else{
108607         z[iOut++] = z[iIn++];
108608       }
108609     }
108610     z[iOut] = '\0';
108611   }
108612 }
108613
108614 /*
108615 ** Read a single varint from the doclist at *pp and advance *pp to point
108616 ** to the first byte past the end of the varint.  Add the value of the varint
108617 ** to *pVal.
108618 */
108619 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
108620   sqlite3_int64 iVal;
108621   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
108622   *pVal += iVal;
108623 }
108624
108625 /*
108626 ** As long as *pp has not reached its end (pEnd), then do the same
108627 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
108628 ** But if we have reached the end of the varint, just set *pp=0 and
108629 ** leave *pVal unchanged.
108630 */
108631 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
108632   if( *pp>=pEnd ){
108633     *pp = 0;
108634   }else{
108635     fts3GetDeltaVarint(pp, pVal);
108636   }
108637 }
108638
108639 /*
108640 ** The xDisconnect() virtual table method.
108641 */
108642 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
108643   Fts3Table *p = (Fts3Table *)pVtab;
108644   int i;
108645
108646   assert( p->nPendingData==0 );
108647   assert( p->pSegments==0 );
108648
108649   /* Free any prepared statements held */
108650   for(i=0; i<SizeofArray(p->aStmt); i++){
108651     sqlite3_finalize(p->aStmt[i]);
108652   }
108653   sqlite3_free(p->zSegmentsTbl);
108654
108655   /* Invoke the tokenizer destructor to free the tokenizer. */
108656   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
108657
108658   sqlite3_free(p);
108659   return SQLITE_OK;
108660 }
108661
108662 /*
108663 ** Construct one or more SQL statements from the format string given
108664 ** and then evaluate those statements. The success code is written
108665 ** into *pRc.
108666 **
108667 ** If *pRc is initially non-zero then this routine is a no-op.
108668 */
108669 static void fts3DbExec(
108670   int *pRc,              /* Success code */
108671   sqlite3 *db,           /* Database in which to run SQL */
108672   const char *zFormat,   /* Format string for SQL */
108673   ...                    /* Arguments to the format string */
108674 ){
108675   va_list ap;
108676   char *zSql;
108677   if( *pRc ) return;
108678   va_start(ap, zFormat);
108679   zSql = sqlite3_vmprintf(zFormat, ap);
108680   va_end(ap);
108681   if( zSql==0 ){
108682     *pRc = SQLITE_NOMEM;
108683   }else{
108684     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
108685     sqlite3_free(zSql);
108686   }
108687 }
108688
108689 /*
108690 ** The xDestroy() virtual table method.
108691 */
108692 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
108693   int rc = SQLITE_OK;              /* Return code */
108694   Fts3Table *p = (Fts3Table *)pVtab;
108695   sqlite3 *db = p->db;
108696
108697   /* Drop the shadow tables */
108698   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
108699   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
108700   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
108701   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
108702   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
108703
108704   /* If everything has worked, invoke fts3DisconnectMethod() to free the
108705   ** memory associated with the Fts3Table structure and return SQLITE_OK.
108706   ** Otherwise, return an SQLite error code.
108707   */
108708   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
108709 }
108710
108711
108712 /*
108713 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
108714 ** passed as the first argument. This is done as part of the xConnect()
108715 ** and xCreate() methods.
108716 **
108717 ** If *pRc is non-zero when this function is called, it is a no-op. 
108718 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
108719 ** before returning.
108720 */
108721 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
108722   if( *pRc==SQLITE_OK ){
108723     int i;                        /* Iterator variable */
108724     int rc;                       /* Return code */
108725     char *zSql;                   /* SQL statement passed to declare_vtab() */
108726     char *zCols;                  /* List of user defined columns */
108727
108728     /* Create a list of user columns for the virtual table */
108729     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
108730     for(i=1; zCols && i<p->nColumn; i++){
108731       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
108732     }
108733
108734     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
108735     zSql = sqlite3_mprintf(
108736         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
108737     );
108738     if( !zCols || !zSql ){
108739       rc = SQLITE_NOMEM;
108740     }else{
108741       rc = sqlite3_declare_vtab(p->db, zSql);
108742     }
108743
108744     sqlite3_free(zSql);
108745     sqlite3_free(zCols);
108746     *pRc = rc;
108747   }
108748 }
108749
108750 /*
108751 ** Create the backing store tables (%_content, %_segments and %_segdir)
108752 ** required by the FTS3 table passed as the only argument. This is done
108753 ** as part of the vtab xCreate() method.
108754 **
108755 ** If the p->bHasDocsize boolean is true (indicating that this is an
108756 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
108757 ** %_stat tables required by FTS4.
108758 */
108759 static int fts3CreateTables(Fts3Table *p){
108760   int rc = SQLITE_OK;             /* Return code */
108761   int i;                          /* Iterator variable */
108762   char *zContentCols;             /* Columns of %_content table */
108763   sqlite3 *db = p->db;            /* The database connection */
108764
108765   /* Create a list of user columns for the content table */
108766   zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
108767   for(i=0; zContentCols && i<p->nColumn; i++){
108768     char *z = p->azColumn[i];
108769     zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
108770   }
108771   if( zContentCols==0 ) rc = SQLITE_NOMEM;
108772
108773   /* Create the content table */
108774   fts3DbExec(&rc, db, 
108775      "CREATE TABLE %Q.'%q_content'(%s)",
108776      p->zDb, p->zName, zContentCols
108777   );
108778   sqlite3_free(zContentCols);
108779   /* Create other tables */
108780   fts3DbExec(&rc, db, 
108781       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
108782       p->zDb, p->zName
108783   );
108784   fts3DbExec(&rc, db, 
108785       "CREATE TABLE %Q.'%q_segdir'("
108786         "level INTEGER,"
108787         "idx INTEGER,"
108788         "start_block INTEGER,"
108789         "leaves_end_block INTEGER,"
108790         "end_block INTEGER,"
108791         "root BLOB,"
108792         "PRIMARY KEY(level, idx)"
108793       ");",
108794       p->zDb, p->zName
108795   );
108796   if( p->bHasDocsize ){
108797     fts3DbExec(&rc, db, 
108798         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
108799         p->zDb, p->zName
108800     );
108801   }
108802   if( p->bHasStat ){
108803     fts3DbExec(&rc, db, 
108804         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
108805         p->zDb, p->zName
108806     );
108807   }
108808   return rc;
108809 }
108810
108811 /*
108812 ** Store the current database page-size in bytes in p->nPgsz.
108813 **
108814 ** If *pRc is non-zero when this function is called, it is a no-op. 
108815 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
108816 ** before returning.
108817 */
108818 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
108819   if( *pRc==SQLITE_OK ){
108820     int rc;                       /* Return code */
108821     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
108822     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
108823   
108824     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
108825     if( !zSql ){
108826       rc = SQLITE_NOMEM;
108827     }else{
108828       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
108829       if( rc==SQLITE_OK ){
108830         sqlite3_step(pStmt);
108831         p->nPgsz = sqlite3_column_int(pStmt, 0);
108832         rc = sqlite3_finalize(pStmt);
108833       }
108834     }
108835     assert( p->nPgsz>0 || rc!=SQLITE_OK );
108836     sqlite3_free(zSql);
108837     *pRc = rc;
108838   }
108839 }
108840
108841 /*
108842 ** "Special" FTS4 arguments are column specifications of the following form:
108843 **
108844 **   <key> = <value>
108845 **
108846 ** There may not be whitespace surrounding the "=" character. The <value> 
108847 ** term may be quoted, but the <key> may not.
108848 */
108849 static int fts3IsSpecialColumn(
108850   const char *z, 
108851   int *pnKey,
108852   char **pzValue
108853 ){
108854   char *zValue;
108855   const char *zCsr = z;
108856
108857   while( *zCsr!='=' ){
108858     if( *zCsr=='\0' ) return 0;
108859     zCsr++;
108860   }
108861
108862   *pnKey = (int)(zCsr-z);
108863   zValue = sqlite3_mprintf("%s", &zCsr[1]);
108864   if( zValue ){
108865     sqlite3Fts3Dequote(zValue);
108866   }
108867   *pzValue = zValue;
108868   return 1;
108869 }
108870
108871 /*
108872 ** This function is the implementation of both the xConnect and xCreate
108873 ** methods of the FTS3 virtual table.
108874 **
108875 ** The argv[] array contains the following:
108876 **
108877 **   argv[0]   -> module name  ("fts3" or "fts4")
108878 **   argv[1]   -> database name
108879 **   argv[2]   -> table name
108880 **   argv[...] -> "column name" and other module argument fields.
108881 */
108882 static int fts3InitVtab(
108883   int isCreate,                   /* True for xCreate, false for xConnect */
108884   sqlite3 *db,                    /* The SQLite database connection */
108885   void *pAux,                     /* Hash table containing tokenizers */
108886   int argc,                       /* Number of elements in argv array */
108887   const char * const *argv,       /* xCreate/xConnect argument array */
108888   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
108889   char **pzErr                    /* Write any error message here */
108890 ){
108891   Fts3Hash *pHash = (Fts3Hash *)pAux;
108892   Fts3Table *p = 0;               /* Pointer to allocated vtab */
108893   int rc = SQLITE_OK;             /* Return code */
108894   int i;                          /* Iterator variable */
108895   int nByte;                      /* Size of allocation used for *p */
108896   int iCol;                       /* Column index */
108897   int nString = 0;                /* Bytes required to hold all column names */
108898   int nCol = 0;                   /* Number of columns in the FTS table */
108899   char *zCsr;                     /* Space for holding column names */
108900   int nDb;                        /* Bytes required to hold database name */
108901   int nName;                      /* Bytes required to hold table name */
108902   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
108903   int bNoDocsize = 0;             /* True to omit %_docsize table */
108904   const char **aCol;              /* Array of column names */
108905   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
108906
108907   assert( strlen(argv[0])==4 );
108908   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
108909        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
108910   );
108911
108912   nDb = (int)strlen(argv[1]) + 1;
108913   nName = (int)strlen(argv[2]) + 1;
108914
108915   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
108916   if( !aCol ) return SQLITE_NOMEM;
108917   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
108918
108919   /* Loop through all of the arguments passed by the user to the FTS3/4
108920   ** module (i.e. all the column names and special arguments). This loop
108921   ** does the following:
108922   **
108923   **   + Figures out the number of columns the FTSX table will have, and
108924   **     the number of bytes of space that must be allocated to store copies
108925   **     of the column names.
108926   **
108927   **   + If there is a tokenizer specification included in the arguments,
108928   **     initializes the tokenizer pTokenizer.
108929   */
108930   for(i=3; rc==SQLITE_OK && i<argc; i++){
108931     char const *z = argv[i];
108932     int nKey;
108933     char *zVal;
108934
108935     /* Check if this is a tokenizer specification */
108936     if( !pTokenizer 
108937      && strlen(z)>8
108938      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
108939      && 0==sqlite3Fts3IsIdChar(z[8])
108940     ){
108941       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
108942     }
108943
108944     /* Check if it is an FTS4 special argument. */
108945     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
108946       if( !zVal ){
108947         rc = SQLITE_NOMEM;
108948         goto fts3_init_out;
108949       }
108950       if( nKey==9 && 0==sqlite3_strnicmp(z, "matchinfo", 9) ){
108951         if( strlen(zVal)==4 && 0==sqlite3_strnicmp(zVal, "fts3", 4) ){
108952           bNoDocsize = 1;
108953         }else{
108954           *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
108955           rc = SQLITE_ERROR;
108956         }
108957       }else{
108958         *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
108959         rc = SQLITE_ERROR;
108960       }
108961       sqlite3_free(zVal);
108962     }
108963
108964     /* Otherwise, the argument is a column name. */
108965     else {
108966       nString += (int)(strlen(z) + 1);
108967       aCol[nCol++] = z;
108968     }
108969   }
108970   if( rc!=SQLITE_OK ) goto fts3_init_out;
108971
108972   if( nCol==0 ){
108973     assert( nString==0 );
108974     aCol[0] = "content";
108975     nString = 8;
108976     nCol = 1;
108977   }
108978
108979   if( pTokenizer==0 ){
108980     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
108981     if( rc!=SQLITE_OK ) goto fts3_init_out;
108982   }
108983   assert( pTokenizer );
108984
108985
108986   /* Allocate and populate the Fts3Table structure. */
108987   nByte = sizeof(Fts3Table) +              /* Fts3Table */
108988           nCol * sizeof(char *) +              /* azColumn */
108989           nName +                              /* zName */
108990           nDb +                                /* zDb */
108991           nString;                             /* Space for azColumn strings */
108992   p = (Fts3Table*)sqlite3_malloc(nByte);
108993   if( p==0 ){
108994     rc = SQLITE_NOMEM;
108995     goto fts3_init_out;
108996   }
108997   memset(p, 0, nByte);
108998   p->db = db;
108999   p->nColumn = nCol;
109000   p->nPendingData = 0;
109001   p->azColumn = (char **)&p[1];
109002   p->pTokenizer = pTokenizer;
109003   p->nNodeSize = 1000;
109004   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
109005   p->bHasDocsize = (isFts4 && bNoDocsize==0);
109006   p->bHasStat = isFts4;
109007   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
109008
109009   /* Fill in the zName and zDb fields of the vtab structure. */
109010   zCsr = (char *)&p->azColumn[nCol];
109011   p->zName = zCsr;
109012   memcpy(zCsr, argv[2], nName);
109013   zCsr += nName;
109014   p->zDb = zCsr;
109015   memcpy(zCsr, argv[1], nDb);
109016   zCsr += nDb;
109017
109018   /* Fill in the azColumn array */
109019   for(iCol=0; iCol<nCol; iCol++){
109020     char *z; 
109021     int n;
109022     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
109023     memcpy(zCsr, z, n);
109024     zCsr[n] = '\0';
109025     sqlite3Fts3Dequote(zCsr);
109026     p->azColumn[iCol] = zCsr;
109027     zCsr += n+1;
109028     assert( zCsr <= &((char *)p)[nByte] );
109029   }
109030
109031   /* If this is an xCreate call, create the underlying tables in the 
109032   ** database. TODO: For xConnect(), it could verify that said tables exist.
109033   */
109034   if( isCreate ){
109035     rc = fts3CreateTables(p);
109036   }
109037
109038   /* Figure out the page-size for the database. This is required in order to
109039   ** estimate the cost of loading large doclists from the database (see 
109040   ** function sqlite3Fts3SegReaderCost() for details).
109041   */
109042   fts3DatabasePageSize(&rc, p);
109043
109044   /* Declare the table schema to SQLite. */
109045   fts3DeclareVtab(&rc, p);
109046
109047 fts3_init_out:
109048
109049   sqlite3_free((void *)aCol);
109050   if( rc!=SQLITE_OK ){
109051     if( p ){
109052       fts3DisconnectMethod((sqlite3_vtab *)p);
109053     }else if( pTokenizer ){
109054       pTokenizer->pModule->xDestroy(pTokenizer);
109055     }
109056   }else{
109057     *ppVTab = &p->base;
109058   }
109059   return rc;
109060 }
109061
109062 /*
109063 ** The xConnect() and xCreate() methods for the virtual table. All the
109064 ** work is done in function fts3InitVtab().
109065 */
109066 static int fts3ConnectMethod(
109067   sqlite3 *db,                    /* Database connection */
109068   void *pAux,                     /* Pointer to tokenizer hash table */
109069   int argc,                       /* Number of elements in argv array */
109070   const char * const *argv,       /* xCreate/xConnect argument array */
109071   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
109072   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
109073 ){
109074   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
109075 }
109076 static int fts3CreateMethod(
109077   sqlite3 *db,                    /* Database connection */
109078   void *pAux,                     /* Pointer to tokenizer hash table */
109079   int argc,                       /* Number of elements in argv array */
109080   const char * const *argv,       /* xCreate/xConnect argument array */
109081   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
109082   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
109083 ){
109084   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
109085 }
109086
109087 /* 
109088 ** Implementation of the xBestIndex method for FTS3 tables. There
109089 ** are three possible strategies, in order of preference:
109090 **
109091 **   1. Direct lookup by rowid or docid. 
109092 **   2. Full-text search using a MATCH operator on a non-docid column.
109093 **   3. Linear scan of %_content table.
109094 */
109095 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
109096   Fts3Table *p = (Fts3Table *)pVTab;
109097   int i;                          /* Iterator variable */
109098   int iCons = -1;                 /* Index of constraint to use */
109099
109100   /* By default use a full table scan. This is an expensive option,
109101   ** so search through the constraints to see if a more efficient 
109102   ** strategy is possible.
109103   */
109104   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
109105   pInfo->estimatedCost = 500000;
109106   for(i=0; i<pInfo->nConstraint; i++){
109107     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
109108     if( pCons->usable==0 ) continue;
109109
109110     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
109111     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
109112      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
109113     ){
109114       pInfo->idxNum = FTS3_DOCID_SEARCH;
109115       pInfo->estimatedCost = 1.0;
109116       iCons = i;
109117     }
109118
109119     /* A MATCH constraint. Use a full-text search.
109120     **
109121     ** If there is more than one MATCH constraint available, use the first
109122     ** one encountered. If there is both a MATCH constraint and a direct
109123     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
109124     ** though the rowid/docid lookup is faster than a MATCH query, selecting
109125     ** it would lead to an "unable to use function MATCH in the requested 
109126     ** context" error.
109127     */
109128     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
109129      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
109130     ){
109131       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
109132       pInfo->estimatedCost = 2.0;
109133       iCons = i;
109134       break;
109135     }
109136   }
109137
109138   if( iCons>=0 ){
109139     pInfo->aConstraintUsage[iCons].argvIndex = 1;
109140     pInfo->aConstraintUsage[iCons].omit = 1;
109141   } 
109142   return SQLITE_OK;
109143 }
109144
109145 /*
109146 ** Implementation of xOpen method.
109147 */
109148 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
109149   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
109150
109151   UNUSED_PARAMETER(pVTab);
109152
109153   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
109154   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
109155   ** if the allocation fails, return SQLITE_NOMEM.
109156   */
109157   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
109158   if( !pCsr ){
109159     return SQLITE_NOMEM;
109160   }
109161   memset(pCsr, 0, sizeof(Fts3Cursor));
109162   return SQLITE_OK;
109163 }
109164
109165 /*
109166 ** Close the cursor.  For additional information see the documentation
109167 ** on the xClose method of the virtual table interface.
109168 */
109169 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
109170   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
109171   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
109172   sqlite3_finalize(pCsr->pStmt);
109173   sqlite3Fts3ExprFree(pCsr->pExpr);
109174   sqlite3Fts3FreeDeferredTokens(pCsr);
109175   sqlite3_free(pCsr->aDoclist);
109176   sqlite3_free(pCsr->aMatchinfo);
109177   sqlite3_free(pCsr);
109178   return SQLITE_OK;
109179 }
109180
109181 /*
109182 ** Position the pCsr->pStmt statement so that it is on the row
109183 ** of the %_content table that contains the last match.  Return
109184 ** SQLITE_OK on success.  
109185 */
109186 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
109187   if( pCsr->isRequireSeek ){
109188     pCsr->isRequireSeek = 0;
109189     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
109190     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
109191       return SQLITE_OK;
109192     }else{
109193       int rc = sqlite3_reset(pCsr->pStmt);
109194       if( rc==SQLITE_OK ){
109195         /* If no row was found and no error has occured, then the %_content
109196         ** table is missing a row that is present in the full-text index.
109197         ** The data structures are corrupt.
109198         */
109199         rc = SQLITE_CORRUPT;
109200       }
109201       pCsr->isEof = 1;
109202       if( pContext ){
109203         sqlite3_result_error_code(pContext, rc);
109204       }
109205       return rc;
109206     }
109207   }else{
109208     return SQLITE_OK;
109209   }
109210 }
109211
109212 /*
109213 ** This function is used to process a single interior node when searching
109214 ** a b-tree for a term or term prefix. The node data is passed to this 
109215 ** function via the zNode/nNode parameters. The term to search for is
109216 ** passed in zTerm/nTerm.
109217 **
109218 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
109219 ** of the child node that heads the sub-tree that may contain the term.
109220 **
109221 ** If piLast is not NULL, then *piLast is set to the right-most child node
109222 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
109223 ** a prefix.
109224 **
109225 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
109226 */
109227 static int fts3ScanInteriorNode(
109228   const char *zTerm,              /* Term to select leaves for */
109229   int nTerm,                      /* Size of term zTerm in bytes */
109230   const char *zNode,              /* Buffer containing segment interior node */
109231   int nNode,                      /* Size of buffer at zNode */
109232   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
109233   sqlite3_int64 *piLast           /* OUT: Selected child node */
109234 ){
109235   int rc = SQLITE_OK;             /* Return code */
109236   const char *zCsr = zNode;       /* Cursor to iterate through node */
109237   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
109238   char *zBuffer = 0;              /* Buffer to load terms into */
109239   int nAlloc = 0;                 /* Size of allocated buffer */
109240   int isFirstTerm = 1;            /* True when processing first term on page */
109241   sqlite3_int64 iChild;           /* Block id of child node to descend to */
109242
109243   /* Skip over the 'height' varint that occurs at the start of every 
109244   ** interior node. Then load the blockid of the left-child of the b-tree
109245   ** node into variable iChild.  
109246   **
109247   ** Even if the data structure on disk is corrupted, this (reading two
109248   ** varints from the buffer) does not risk an overread. If zNode is a
109249   ** root node, then the buffer comes from a SELECT statement. SQLite does
109250   ** not make this guarantee explicitly, but in practice there are always
109251   ** either more than 20 bytes of allocated space following the nNode bytes of
109252   ** contents, or two zero bytes. Or, if the node is read from the %_segments
109253   ** table, then there are always 20 bytes of zeroed padding following the
109254   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
109255   */
109256   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
109257   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
109258   if( zCsr>zEnd ){
109259     return SQLITE_CORRUPT;
109260   }
109261   
109262   while( zCsr<zEnd && (piFirst || piLast) ){
109263     int cmp;                      /* memcmp() result */
109264     int nSuffix;                  /* Size of term suffix */
109265     int nPrefix = 0;              /* Size of term prefix */
109266     int nBuffer;                  /* Total term size */
109267   
109268     /* Load the next term on the node into zBuffer. Use realloc() to expand
109269     ** the size of zBuffer if required.  */
109270     if( !isFirstTerm ){
109271       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
109272     }
109273     isFirstTerm = 0;
109274     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
109275     
109276     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
109277       rc = SQLITE_CORRUPT;
109278       goto finish_scan;
109279     }
109280     if( nPrefix+nSuffix>nAlloc ){
109281       char *zNew;
109282       nAlloc = (nPrefix+nSuffix) * 2;
109283       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
109284       if( !zNew ){
109285         rc = SQLITE_NOMEM;
109286         goto finish_scan;
109287       }
109288       zBuffer = zNew;
109289     }
109290     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
109291     nBuffer = nPrefix + nSuffix;
109292     zCsr += nSuffix;
109293
109294     /* Compare the term we are searching for with the term just loaded from
109295     ** the interior node. If the specified term is greater than or equal
109296     ** to the term from the interior node, then all terms on the sub-tree 
109297     ** headed by node iChild are smaller than zTerm. No need to search 
109298     ** iChild.
109299     **
109300     ** If the interior node term is larger than the specified term, then
109301     ** the tree headed by iChild may contain the specified term.
109302     */
109303     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
109304     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
109305       *piFirst = iChild;
109306       piFirst = 0;
109307     }
109308
109309     if( piLast && cmp<0 ){
109310       *piLast = iChild;
109311       piLast = 0;
109312     }
109313
109314     iChild++;
109315   };
109316
109317   if( piFirst ) *piFirst = iChild;
109318   if( piLast ) *piLast = iChild;
109319
109320  finish_scan:
109321   sqlite3_free(zBuffer);
109322   return rc;
109323 }
109324
109325
109326 /*
109327 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
109328 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
109329 ** contains a term. This function searches the sub-tree headed by the zNode
109330 ** node for the range of leaf nodes that may contain the specified term
109331 ** or terms for which the specified term is a prefix.
109332 **
109333 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
109334 ** left-most leaf node in the tree that may contain the specified term.
109335 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
109336 ** right-most leaf node that may contain a term for which the specified
109337 ** term is a prefix.
109338 **
109339 ** It is possible that the range of returned leaf nodes does not contain 
109340 ** the specified term or any terms for which it is a prefix. However, if the 
109341 ** segment does contain any such terms, they are stored within the identified
109342 ** range. Because this function only inspects interior segment nodes (and
109343 ** never loads leaf nodes into memory), it is not possible to be sure.
109344 **
109345 ** If an error occurs, an error code other than SQLITE_OK is returned.
109346 */ 
109347 static int fts3SelectLeaf(
109348   Fts3Table *p,                   /* Virtual table handle */
109349   const char *zTerm,              /* Term to select leaves for */
109350   int nTerm,                      /* Size of term zTerm in bytes */
109351   const char *zNode,              /* Buffer containing segment interior node */
109352   int nNode,                      /* Size of buffer at zNode */
109353   sqlite3_int64 *piLeaf,          /* Selected leaf node */
109354   sqlite3_int64 *piLeaf2          /* Selected leaf node */
109355 ){
109356   int rc;                         /* Return code */
109357   int iHeight;                    /* Height of this node in tree */
109358
109359   assert( piLeaf || piLeaf2 );
109360
109361   sqlite3Fts3GetVarint32(zNode, &iHeight);
109362   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
109363   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
109364
109365   if( rc==SQLITE_OK && iHeight>1 ){
109366     char *zBlob = 0;              /* Blob read from %_segments table */
109367     int nBlob;                    /* Size of zBlob in bytes */
109368
109369     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
109370       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob);
109371       if( rc==SQLITE_OK ){
109372         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
109373       }
109374       sqlite3_free(zBlob);
109375       piLeaf = 0;
109376       zBlob = 0;
109377     }
109378
109379     if( rc==SQLITE_OK ){
109380       rc = sqlite3Fts3ReadBlock(p, piLeaf ? *piLeaf : *piLeaf2, &zBlob, &nBlob);
109381     }
109382     if( rc==SQLITE_OK ){
109383       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
109384     }
109385     sqlite3_free(zBlob);
109386   }
109387
109388   return rc;
109389 }
109390
109391 /*
109392 ** This function is used to create delta-encoded serialized lists of FTS3 
109393 ** varints. Each call to this function appends a single varint to a list.
109394 */
109395 static void fts3PutDeltaVarint(
109396   char **pp,                      /* IN/OUT: Output pointer */
109397   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
109398   sqlite3_int64 iVal              /* Write this value to the list */
109399 ){
109400   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
109401   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
109402   *piPrev = iVal;
109403 }
109404
109405 /*
109406 ** When this function is called, *ppPoslist is assumed to point to the 
109407 ** start of a position-list. After it returns, *ppPoslist points to the
109408 ** first byte after the position-list.
109409 **
109410 ** A position list is list of positions (delta encoded) and columns for 
109411 ** a single document record of a doclist.  So, in other words, this
109412 ** routine advances *ppPoslist so that it points to the next docid in
109413 ** the doclist, or to the first byte past the end of the doclist.
109414 **
109415 ** If pp is not NULL, then the contents of the position list are copied
109416 ** to *pp. *pp is set to point to the first byte past the last byte copied
109417 ** before this function returns.
109418 */
109419 static void fts3PoslistCopy(char **pp, char **ppPoslist){
109420   char *pEnd = *ppPoslist;
109421   char c = 0;
109422
109423   /* The end of a position list is marked by a zero encoded as an FTS3 
109424   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
109425   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
109426   ** of some other, multi-byte, value.
109427   **
109428   ** The following while-loop moves pEnd to point to the first byte that is not 
109429   ** immediately preceded by a byte with the 0x80 bit set. Then increments
109430   ** pEnd once more so that it points to the byte immediately following the
109431   ** last byte in the position-list.
109432   */
109433   while( *pEnd | c ){
109434     c = *pEnd++ & 0x80;
109435     testcase( c!=0 && (*pEnd)==0 );
109436   }
109437   pEnd++;  /* Advance past the POS_END terminator byte */
109438
109439   if( pp ){
109440     int n = (int)(pEnd - *ppPoslist);
109441     char *p = *pp;
109442     memcpy(p, *ppPoslist, n);
109443     p += n;
109444     *pp = p;
109445   }
109446   *ppPoslist = pEnd;
109447 }
109448
109449 /*
109450 ** When this function is called, *ppPoslist is assumed to point to the 
109451 ** start of a column-list. After it returns, *ppPoslist points to the
109452 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
109453 **
109454 ** A column-list is list of delta-encoded positions for a single column
109455 ** within a single document within a doclist.
109456 **
109457 ** The column-list is terminated either by a POS_COLUMN varint (1) or
109458 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
109459 ** the POS_COLUMN or POS_END that terminates the column-list.
109460 **
109461 ** If pp is not NULL, then the contents of the column-list are copied
109462 ** to *pp. *pp is set to point to the first byte past the last byte copied
109463 ** before this function returns.  The POS_COLUMN or POS_END terminator
109464 ** is not copied into *pp.
109465 */
109466 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
109467   char *pEnd = *ppPoslist;
109468   char c = 0;
109469
109470   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
109471   ** not part of a multi-byte varint.
109472   */
109473   while( 0xFE & (*pEnd | c) ){
109474     c = *pEnd++ & 0x80;
109475     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
109476   }
109477   if( pp ){
109478     int n = (int)(pEnd - *ppPoslist);
109479     char *p = *pp;
109480     memcpy(p, *ppPoslist, n);
109481     p += n;
109482     *pp = p;
109483   }
109484   *ppPoslist = pEnd;
109485 }
109486
109487 /*
109488 ** Value used to signify the end of an position-list. This is safe because
109489 ** it is not possible to have a document with 2^31 terms.
109490 */
109491 #define POSITION_LIST_END 0x7fffffff
109492
109493 /*
109494 ** This function is used to help parse position-lists. When this function is
109495 ** called, *pp may point to the start of the next varint in the position-list
109496 ** being parsed, or it may point to 1 byte past the end of the position-list
109497 ** (in which case **pp will be a terminator bytes POS_END (0) or
109498 ** (1)).
109499 **
109500 ** If *pp points past the end of the current position-list, set *pi to 
109501 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
109502 ** increment the current value of *pi by the value read, and set *pp to
109503 ** point to the next value before returning.
109504 **
109505 ** Before calling this routine *pi must be initialized to the value of
109506 ** the previous position, or zero if we are reading the first position
109507 ** in the position-list.  Because positions are delta-encoded, the value
109508 ** of the previous position is needed in order to compute the value of
109509 ** the next position.
109510 */
109511 static void fts3ReadNextPos(
109512   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
109513   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
109514 ){
109515   if( (**pp)&0xFE ){
109516     fts3GetDeltaVarint(pp, pi);
109517     *pi -= 2;
109518   }else{
109519     *pi = POSITION_LIST_END;
109520   }
109521 }
109522
109523 /*
109524 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
109525 ** the value of iCol encoded as a varint to *pp.   This will start a new
109526 ** column list.
109527 **
109528 ** Set *pp to point to the byte just after the last byte written before 
109529 ** returning (do not modify it if iCol==0). Return the total number of bytes
109530 ** written (0 if iCol==0).
109531 */
109532 static int fts3PutColNumber(char **pp, int iCol){
109533   int n = 0;                      /* Number of bytes written */
109534   if( iCol ){
109535     char *p = *pp;                /* Output pointer */
109536     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
109537     *p = 0x01;
109538     *pp = &p[n];
109539   }
109540   return n;
109541 }
109542
109543 /*
109544 ** Compute the union of two position lists.  The output written
109545 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
109546 ** order and with any duplicates removed.  All pointers are
109547 ** updated appropriately.   The caller is responsible for insuring
109548 ** that there is enough space in *pp to hold the complete output.
109549 */
109550 static void fts3PoslistMerge(
109551   char **pp,                      /* Output buffer */
109552   char **pp1,                     /* Left input list */
109553   char **pp2                      /* Right input list */
109554 ){
109555   char *p = *pp;
109556   char *p1 = *pp1;
109557   char *p2 = *pp2;
109558
109559   while( *p1 || *p2 ){
109560     int iCol1;         /* The current column index in pp1 */
109561     int iCol2;         /* The current column index in pp2 */
109562
109563     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
109564     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
109565     else iCol1 = 0;
109566
109567     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
109568     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
109569     else iCol2 = 0;
109570
109571     if( iCol1==iCol2 ){
109572       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
109573       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
109574       sqlite3_int64 iPrev = 0;
109575       int n = fts3PutColNumber(&p, iCol1);
109576       p1 += n;
109577       p2 += n;
109578
109579       /* At this point, both p1 and p2 point to the start of column-lists
109580       ** for the same column (the column with index iCol1 and iCol2).
109581       ** A column-list is a list of non-negative delta-encoded varints, each 
109582       ** incremented by 2 before being stored. Each list is terminated by a
109583       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
109584       ** and writes the results to buffer p. p is left pointing to the byte
109585       ** after the list written. No terminator (POS_END or POS_COLUMN) is
109586       ** written to the output.
109587       */
109588       fts3GetDeltaVarint(&p1, &i1);
109589       fts3GetDeltaVarint(&p2, &i2);
109590       do {
109591         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
109592         iPrev -= 2;
109593         if( i1==i2 ){
109594           fts3ReadNextPos(&p1, &i1);
109595           fts3ReadNextPos(&p2, &i2);
109596         }else if( i1<i2 ){
109597           fts3ReadNextPos(&p1, &i1);
109598         }else{
109599           fts3ReadNextPos(&p2, &i2);
109600         }
109601       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
109602     }else if( iCol1<iCol2 ){
109603       p1 += fts3PutColNumber(&p, iCol1);
109604       fts3ColumnlistCopy(&p, &p1);
109605     }else{
109606       p2 += fts3PutColNumber(&p, iCol2);
109607       fts3ColumnlistCopy(&p, &p2);
109608     }
109609   }
109610
109611   *p++ = POS_END;
109612   *pp = p;
109613   *pp1 = p1 + 1;
109614   *pp2 = p2 + 1;
109615 }
109616
109617 /*
109618 ** nToken==1 searches for adjacent positions.
109619 **
109620 ** This function is used to merge two position lists into one. When it is
109621 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
109622 ** the part of a doclist that follows each document id. For example, if a row
109623 ** contains:
109624 **
109625 **     'a b c'|'x y z'|'a b b a'
109626 **
109627 ** Then the position list for this row for token 'b' would consist of:
109628 **
109629 **     0x02 0x01 0x02 0x03 0x03 0x00
109630 **
109631 ** When this function returns, both *pp1 and *pp2 are left pointing to the
109632 ** byte following the 0x00 terminator of their respective position lists.
109633 **
109634 ** If isSaveLeft is 0, an entry is added to the output position list for 
109635 ** each position in *pp2 for which there exists one or more positions in
109636 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
109637 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
109638 ** slots before it.
109639 */
109640 static int fts3PoslistPhraseMerge(
109641   char **pp,                      /* IN/OUT: Preallocated output buffer */
109642   int nToken,                     /* Maximum difference in token positions */
109643   int isSaveLeft,                 /* Save the left position */
109644   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
109645   char **pp1,                     /* IN/OUT: Left input list */
109646   char **pp2                      /* IN/OUT: Right input list */
109647 ){
109648   char *p = (pp ? *pp : 0);
109649   char *p1 = *pp1;
109650   char *p2 = *pp2;
109651   int iCol1 = 0;
109652   int iCol2 = 0;
109653
109654   /* Never set both isSaveLeft and isExact for the same invocation. */
109655   assert( isSaveLeft==0 || isExact==0 );
109656
109657   assert( *p1!=0 && *p2!=0 );
109658   if( *p1==POS_COLUMN ){ 
109659     p1++;
109660     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
109661   }
109662   if( *p2==POS_COLUMN ){ 
109663     p2++;
109664     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
109665   }
109666
109667   while( 1 ){
109668     if( iCol1==iCol2 ){
109669       char *pSave = p;
109670       sqlite3_int64 iPrev = 0;
109671       sqlite3_int64 iPos1 = 0;
109672       sqlite3_int64 iPos2 = 0;
109673
109674       if( pp && iCol1 ){
109675         *p++ = POS_COLUMN;
109676         p += sqlite3Fts3PutVarint(p, iCol1);
109677       }
109678
109679       assert( *p1!=POS_END && *p1!=POS_COLUMN );
109680       assert( *p2!=POS_END && *p2!=POS_COLUMN );
109681       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
109682       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
109683
109684       while( 1 ){
109685         if( iPos2==iPos1+nToken 
109686          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
109687         ){
109688           sqlite3_int64 iSave;
109689           if( !pp ){
109690             fts3PoslistCopy(0, &p2);
109691             fts3PoslistCopy(0, &p1);
109692             *pp1 = p1;
109693             *pp2 = p2;
109694             return 1;
109695           }
109696           iSave = isSaveLeft ? iPos1 : iPos2;
109697           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
109698           pSave = 0;
109699         }
109700         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
109701           if( (*p2&0xFE)==0 ) break;
109702           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
109703         }else{
109704           if( (*p1&0xFE)==0 ) break;
109705           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
109706         }
109707       }
109708
109709       if( pSave ){
109710         assert( pp && p );
109711         p = pSave;
109712       }
109713
109714       fts3ColumnlistCopy(0, &p1);
109715       fts3ColumnlistCopy(0, &p2);
109716       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
109717       if( 0==*p1 || 0==*p2 ) break;
109718
109719       p1++;
109720       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
109721       p2++;
109722       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
109723     }
109724
109725     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
109726     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
109727     ** end of the position list, or the 0x01 that precedes the next 
109728     ** column-number in the position list. 
109729     */
109730     else if( iCol1<iCol2 ){
109731       fts3ColumnlistCopy(0, &p1);
109732       if( 0==*p1 ) break;
109733       p1++;
109734       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
109735     }else{
109736       fts3ColumnlistCopy(0, &p2);
109737       if( 0==*p2 ) break;
109738       p2++;
109739       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
109740     }
109741   }
109742
109743   fts3PoslistCopy(0, &p2);
109744   fts3PoslistCopy(0, &p1);
109745   *pp1 = p1;
109746   *pp2 = p2;
109747   if( !pp || *pp==p ){
109748     return 0;
109749   }
109750   *p++ = 0x00;
109751   *pp = p;
109752   return 1;
109753 }
109754
109755 /*
109756 ** Merge two position-lists as required by the NEAR operator.
109757 */
109758 static int fts3PoslistNearMerge(
109759   char **pp,                      /* Output buffer */
109760   char *aTmp,                     /* Temporary buffer space */
109761   int nRight,                     /* Maximum difference in token positions */
109762   int nLeft,                      /* Maximum difference in token positions */
109763   char **pp1,                     /* IN/OUT: Left input list */
109764   char **pp2                      /* IN/OUT: Right input list */
109765 ){
109766   char *p1 = *pp1;
109767   char *p2 = *pp2;
109768
109769   if( !pp ){
109770     if( fts3PoslistPhraseMerge(0, nRight, 0, 0, pp1, pp2) ) return 1;
109771     *pp1 = p1;
109772     *pp2 = p2;
109773     return fts3PoslistPhraseMerge(0, nLeft, 0, 0, pp2, pp1);
109774   }else{
109775     char *pTmp1 = aTmp;
109776     char *pTmp2;
109777     char *aTmp2;
109778     int res = 1;
109779
109780     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
109781     aTmp2 = pTmp2 = pTmp1;
109782     *pp1 = p1;
109783     *pp2 = p2;
109784     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
109785     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
109786       fts3PoslistMerge(pp, &aTmp, &aTmp2);
109787     }else if( pTmp1!=aTmp ){
109788       fts3PoslistCopy(pp, &aTmp);
109789     }else if( pTmp2!=aTmp2 ){
109790       fts3PoslistCopy(pp, &aTmp2);
109791     }else{
109792       res = 0;
109793     }
109794
109795     return res;
109796   }
109797 }
109798
109799 /*
109800 ** Values that may be used as the first parameter to fts3DoclistMerge().
109801 */
109802 #define MERGE_NOT        2        /* D + D -> D */
109803 #define MERGE_AND        3        /* D + D -> D */
109804 #define MERGE_OR         4        /* D + D -> D */
109805 #define MERGE_POS_OR     5        /* P + P -> P */
109806 #define MERGE_PHRASE     6        /* P + P -> D */
109807 #define MERGE_POS_PHRASE 7        /* P + P -> P */
109808 #define MERGE_NEAR       8        /* P + P -> D */
109809 #define MERGE_POS_NEAR   9        /* P + P -> P */
109810
109811 /*
109812 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
109813 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
109814 ** which is guaranteed to be large enough to hold the results. The number
109815 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
109816 **
109817 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
109818 ** occurs while allocating a temporary buffer as part of the merge operation,
109819 ** SQLITE_NOMEM is returned.
109820 */
109821 static int fts3DoclistMerge(
109822   int mergetype,                  /* One of the MERGE_XXX constants */
109823   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
109824   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
109825   char *aBuffer,                  /* Pre-allocated output buffer */
109826   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
109827   char *a1,                       /* Buffer containing first doclist */
109828   int n1,                         /* Size of buffer a1 */
109829   char *a2,                       /* Buffer containing second doclist */
109830   int n2,                         /* Size of buffer a2 */
109831   int *pnDoc                      /* OUT: Number of docids in output */
109832 ){
109833   sqlite3_int64 i1 = 0;
109834   sqlite3_int64 i2 = 0;
109835   sqlite3_int64 iPrev = 0;
109836
109837   char *p = aBuffer;
109838   char *p1 = a1;
109839   char *p2 = a2;
109840   char *pEnd1 = &a1[n1];
109841   char *pEnd2 = &a2[n2];
109842   int nDoc = 0;
109843
109844   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR 
109845        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
109846        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
109847        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
109848   );
109849
109850   if( !aBuffer ){
109851     *pnBuffer = 0;
109852     return SQLITE_NOMEM;
109853   }
109854
109855   /* Read the first docid from each doclist */
109856   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109857   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109858
109859   switch( mergetype ){
109860     case MERGE_OR:
109861     case MERGE_POS_OR:
109862       while( p1 || p2 ){
109863         if( p2 && p1 && i1==i2 ){
109864           fts3PutDeltaVarint(&p, &iPrev, i1);
109865           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
109866           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109867           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109868         }else if( !p2 || (p1 && i1<i2) ){
109869           fts3PutDeltaVarint(&p, &iPrev, i1);
109870           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
109871           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109872         }else{
109873           fts3PutDeltaVarint(&p, &iPrev, i2);
109874           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
109875           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109876         }
109877       }
109878       break;
109879
109880     case MERGE_AND:
109881       while( p1 && p2 ){
109882         if( i1==i2 ){
109883           fts3PutDeltaVarint(&p, &iPrev, i1);
109884           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109885           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109886           nDoc++;
109887         }else if( i1<i2 ){
109888           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109889         }else{
109890           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109891         }
109892       }
109893       break;
109894
109895     case MERGE_NOT:
109896       while( p1 ){
109897         if( p2 && i1==i2 ){
109898           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109899           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109900         }else if( !p2 || i1<i2 ){
109901           fts3PutDeltaVarint(&p, &iPrev, i1);
109902           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109903         }else{
109904           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109905         }
109906       }
109907       break;
109908
109909     case MERGE_POS_PHRASE:
109910     case MERGE_PHRASE: {
109911       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
109912       while( p1 && p2 ){
109913         if( i1==i2 ){
109914           char *pSave = p;
109915           sqlite3_int64 iPrevSave = iPrev;
109916           fts3PutDeltaVarint(&p, &iPrev, i1);
109917           if( 0==fts3PoslistPhraseMerge(ppPos, nParam1, 0, 1, &p1, &p2) ){
109918             p = pSave;
109919             iPrev = iPrevSave;
109920           }else{
109921             nDoc++;
109922           }
109923           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109924           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109925         }else if( i1<i2 ){
109926           fts3PoslistCopy(0, &p1);
109927           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109928         }else{
109929           fts3PoslistCopy(0, &p2);
109930           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109931         }
109932       }
109933       break;
109934     }
109935
109936     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
109937       char *aTmp = 0;
109938       char **ppPos = 0;
109939
109940       if( mergetype==MERGE_POS_NEAR ){
109941         ppPos = &p;
109942         aTmp = sqlite3_malloc(2*(n1+n2+1));
109943         if( !aTmp ){
109944           return SQLITE_NOMEM;
109945         }
109946       }
109947
109948       while( p1 && p2 ){
109949         if( i1==i2 ){
109950           char *pSave = p;
109951           sqlite3_int64 iPrevSave = iPrev;
109952           fts3PutDeltaVarint(&p, &iPrev, i1);
109953
109954           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
109955             iPrev = iPrevSave;
109956             p = pSave;
109957           }
109958
109959           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109960           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109961         }else if( i1<i2 ){
109962           fts3PoslistCopy(0, &p1);
109963           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
109964         }else{
109965           fts3PoslistCopy(0, &p2);
109966           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
109967         }
109968       }
109969       sqlite3_free(aTmp);
109970       break;
109971     }
109972   }
109973
109974   if( pnDoc ) *pnDoc = nDoc;
109975   *pnBuffer = (int)(p-aBuffer);
109976   return SQLITE_OK;
109977 }
109978
109979 /* 
109980 ** A pointer to an instance of this structure is used as the context 
109981 ** argument to sqlite3Fts3SegReaderIterate()
109982 */
109983 typedef struct TermSelect TermSelect;
109984 struct TermSelect {
109985   int isReqPos;
109986   char *aaOutput[16];             /* Malloc'd output buffer */
109987   int anOutput[16];               /* Size of output in bytes */
109988 };
109989
109990 /*
109991 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
109992 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
109993 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
109994 **
109995 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
109996 ** the responsibility of the caller to free any doclists left in the
109997 ** TermSelect.aaOutput[] array.
109998 */
109999 static int fts3TermSelectMerge(TermSelect *pTS){
110000   int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
110001   char *aOut = 0;
110002   int nOut = 0;
110003   int i;
110004
110005   /* Loop through the doclists in the aaOutput[] array. Merge them all
110006   ** into a single doclist.
110007   */
110008   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
110009     if( pTS->aaOutput[i] ){
110010       if( !aOut ){
110011         aOut = pTS->aaOutput[i];
110012         nOut = pTS->anOutput[i];
110013         pTS->aaOutput[i] = 0;
110014       }else{
110015         int nNew = nOut + pTS->anOutput[i];
110016         char *aNew = sqlite3_malloc(nNew);
110017         if( !aNew ){
110018           sqlite3_free(aOut);
110019           return SQLITE_NOMEM;
110020         }
110021         fts3DoclistMerge(mergetype, 0, 0,
110022             aNew, &nNew, pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, 0
110023         );
110024         sqlite3_free(pTS->aaOutput[i]);
110025         sqlite3_free(aOut);
110026         pTS->aaOutput[i] = 0;
110027         aOut = aNew;
110028         nOut = nNew;
110029       }
110030     }
110031   }
110032
110033   pTS->aaOutput[0] = aOut;
110034   pTS->anOutput[0] = nOut;
110035   return SQLITE_OK;
110036 }
110037
110038 /*
110039 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
110040 ** querying the full-text index for a doclist associated with a term or
110041 ** term-prefix.
110042 */
110043 static int fts3TermSelectCb(
110044   Fts3Table *p,                   /* Virtual table object */
110045   void *pContext,                 /* Pointer to TermSelect structure */
110046   char *zTerm,
110047   int nTerm,
110048   char *aDoclist,
110049   int nDoclist
110050 ){
110051   TermSelect *pTS = (TermSelect *)pContext;
110052
110053   UNUSED_PARAMETER(p);
110054   UNUSED_PARAMETER(zTerm);
110055   UNUSED_PARAMETER(nTerm);
110056
110057   if( pTS->aaOutput[0]==0 ){
110058     /* If this is the first term selected, copy the doclist to the output
110059     ** buffer using memcpy(). TODO: Add a way to transfer control of the
110060     ** aDoclist buffer from the caller so as to avoid the memcpy().
110061     */
110062     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
110063     pTS->anOutput[0] = nDoclist;
110064     if( pTS->aaOutput[0] ){
110065       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
110066     }else{
110067       return SQLITE_NOMEM;
110068     }
110069   }else{
110070     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
110071     char *aMerge = aDoclist;
110072     int nMerge = nDoclist;
110073     int iOut;
110074
110075     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
110076       char *aNew;
110077       int nNew;
110078       if( pTS->aaOutput[iOut]==0 ){
110079         assert( iOut>0 );
110080         pTS->aaOutput[iOut] = aMerge;
110081         pTS->anOutput[iOut] = nMerge;
110082         break;
110083       }
110084
110085       nNew = nMerge + pTS->anOutput[iOut];
110086       aNew = sqlite3_malloc(nNew);
110087       if( !aNew ){
110088         if( aMerge!=aDoclist ){
110089           sqlite3_free(aMerge);
110090         }
110091         return SQLITE_NOMEM;
110092       }
110093       fts3DoclistMerge(mergetype, 0, 0, aNew, &nNew, 
110094           pTS->aaOutput[iOut], pTS->anOutput[iOut], aMerge, nMerge, 0
110095       );
110096
110097       if( iOut>0 ) sqlite3_free(aMerge);
110098       sqlite3_free(pTS->aaOutput[iOut]);
110099       pTS->aaOutput[iOut] = 0;
110100
110101       aMerge = aNew;
110102       nMerge = nNew;
110103       if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
110104         pTS->aaOutput[iOut] = aMerge;
110105         pTS->anOutput[iOut] = nMerge;
110106       }
110107     }
110108   }
110109   return SQLITE_OK;
110110 }
110111
110112 static int fts3DeferredTermSelect(
110113   Fts3DeferredToken *pToken,      /* Phrase token */
110114   int isTermPos,                  /* True to include positions */
110115   int *pnOut,                     /* OUT: Size of list */
110116   char **ppOut                    /* OUT: Body of list */
110117 ){
110118   char *aSource;
110119   int nSource;
110120
110121   aSource = sqlite3Fts3DeferredDoclist(pToken, &nSource);
110122   if( !aSource ){
110123     *pnOut = 0;
110124     *ppOut = 0;
110125   }else if( isTermPos ){
110126     *ppOut = sqlite3_malloc(nSource);
110127     if( !*ppOut ) return SQLITE_NOMEM;
110128     memcpy(*ppOut, aSource, nSource);
110129     *pnOut = nSource;
110130   }else{
110131     sqlite3_int64 docid;
110132     *pnOut = sqlite3Fts3GetVarint(aSource, &docid);
110133     *ppOut = sqlite3_malloc(*pnOut);
110134     if( !*ppOut ) return SQLITE_NOMEM;
110135     sqlite3Fts3PutVarint(*ppOut, docid);
110136   }
110137
110138   return SQLITE_OK;
110139 }
110140
110141 /*
110142 ** An Fts3SegReaderArray is used to store an array of Fts3SegReader objects.
110143 ** Elements are added to the array using fts3SegReaderArrayAdd(). 
110144 */
110145 struct Fts3SegReaderArray {
110146   int nSegment;                   /* Number of valid entries in apSegment[] */
110147   int nAlloc;                     /* Allocated size of apSegment[] */
110148   int nCost;                      /* The cost of executing SegReaderIterate() */
110149   Fts3SegReader *apSegment[1];    /* Array of seg-reader objects */
110150 };
110151
110152
110153 /*
110154 ** Free an Fts3SegReaderArray object. Also free all seg-readers in the
110155 ** array (using sqlite3Fts3SegReaderFree()).
110156 */
110157 static void fts3SegReaderArrayFree(Fts3SegReaderArray *pArray){
110158   if( pArray ){
110159     int i;
110160     for(i=0; i<pArray->nSegment; i++){
110161       sqlite3Fts3SegReaderFree(pArray->apSegment[i]);
110162     }
110163     sqlite3_free(pArray);
110164   }
110165 }
110166
110167 static int fts3SegReaderArrayAdd(
110168   Fts3SegReaderArray **ppArray, 
110169   Fts3SegReader *pNew
110170 ){
110171   Fts3SegReaderArray *pArray = *ppArray;
110172
110173   if( !pArray || pArray->nAlloc==pArray->nSegment ){
110174     int nNew = (pArray ? pArray->nAlloc+16 : 16);
110175     pArray = (Fts3SegReaderArray *)sqlite3_realloc(pArray, 
110176         sizeof(Fts3SegReaderArray) + (nNew-1) * sizeof(Fts3SegReader*)
110177     );
110178     if( !pArray ){
110179       sqlite3Fts3SegReaderFree(pNew);
110180       return SQLITE_NOMEM;
110181     }
110182     if( nNew==16 ){
110183       pArray->nSegment = 0;
110184       pArray->nCost = 0;
110185     }
110186     pArray->nAlloc = nNew;
110187     *ppArray = pArray;
110188   }
110189
110190   pArray->apSegment[pArray->nSegment++] = pNew;
110191   return SQLITE_OK;
110192 }
110193
110194 static int fts3TermSegReaderArray(
110195   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
110196   const char *zTerm,              /* Term to query for */
110197   int nTerm,                      /* Size of zTerm in bytes */
110198   int isPrefix,                   /* True for a prefix search */
110199   Fts3SegReaderArray **ppArray    /* OUT: Allocated seg-reader array */
110200 ){
110201   Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
110202   int rc;                         /* Return code */
110203   Fts3SegReaderArray *pArray = 0; /* Array object to build */
110204   Fts3SegReader *pReader = 0;     /* Seg-reader to add to pArray */ 
110205   sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
110206   int iAge = 0;                   /* Used to assign ages to segments */
110207
110208   /* Allocate a seg-reader to scan the pending terms, if any. */
110209   rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &pReader);
110210   if( rc==SQLITE_OK && pReader ) {
110211     rc = fts3SegReaderArrayAdd(&pArray, pReader);
110212   }
110213
110214   /* Loop through the entire %_segdir table. For each segment, create a
110215   ** Fts3SegReader to iterate through the subset of the segment leaves
110216   ** that may contain a term that matches zTerm/nTerm. For non-prefix
110217   ** searches, this is always a single leaf. For prefix searches, this
110218   ** may be a contiguous block of leaves.
110219   */
110220   if( rc==SQLITE_OK ){
110221     rc = sqlite3Fts3AllSegdirs(p, &pStmt);
110222   }
110223   while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
110224     Fts3SegReader *pNew = 0;
110225     int nRoot = sqlite3_column_bytes(pStmt, 4);
110226     char const *zRoot = sqlite3_column_blob(pStmt, 4);
110227     if( sqlite3_column_int64(pStmt, 1)==0 ){
110228       /* The entire segment is stored on the root node (which must be a
110229       ** leaf). Do not bother inspecting any data in this case, just
110230       ** create a Fts3SegReader to scan the single leaf. 
110231       */
110232       rc = sqlite3Fts3SegReaderNew(iAge, 0, 0, 0, zRoot, nRoot, &pNew);
110233     }else{
110234       sqlite3_int64 i1;           /* First leaf that may contain zTerm */
110235       sqlite3_int64 i2;           /* Final leaf that may contain zTerm */
110236       rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1, (isPrefix?&i2:0));
110237       if( isPrefix==0 ) i2 = i1;
110238       if( rc==SQLITE_OK ){
110239         rc = sqlite3Fts3SegReaderNew(iAge, i1, i2, 0, 0, 0, &pNew);
110240       }
110241     }
110242     assert( (pNew==0)==(rc!=SQLITE_OK) );
110243
110244     /* If a new Fts3SegReader was allocated, add it to the array. */
110245     if( rc==SQLITE_OK ){
110246       rc = fts3SegReaderArrayAdd(&pArray, pNew);
110247     }
110248     if( rc==SQLITE_OK ){
110249       rc = sqlite3Fts3SegReaderCost(pCsr, pNew, &pArray->nCost);
110250     }
110251     iAge++;
110252   }
110253
110254   if( rc==SQLITE_DONE ){
110255     rc = sqlite3_reset(pStmt);
110256   }else{
110257     sqlite3_reset(pStmt);
110258   }
110259   if( rc!=SQLITE_OK ){
110260     fts3SegReaderArrayFree(pArray);
110261     pArray = 0;
110262   }
110263   *ppArray = pArray;
110264   return rc;
110265 }
110266
110267 /*
110268 ** This function retreives the doclist for the specified term (or term
110269 ** prefix) from the database. 
110270 **
110271 ** The returned doclist may be in one of two formats, depending on the 
110272 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
110273 ** a sorted list of delta-compressed docids (a bare doclist). If isReqPos
110274 ** is non-zero, then the returned list is in the same format as is stored 
110275 ** in the database without the found length specifier at the start of on-disk
110276 ** doclists.
110277 */
110278 static int fts3TermSelect(
110279   Fts3Table *p,                   /* Virtual table handle */
110280   Fts3PhraseToken *pTok,          /* Token to query for */
110281   int iColumn,                    /* Column to query (or -ve for all columns) */
110282   int isReqPos,                   /* True to include position lists in output */
110283   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
110284   char **ppOut                    /* OUT: Malloced result buffer */
110285 ){
110286   int rc;                         /* Return code */
110287   Fts3SegReaderArray *pArray;     /* Seg-reader array for this term */
110288   TermSelect tsc;               /* Context object for fts3TermSelectCb() */
110289   Fts3SegFilter filter;         /* Segment term filter configuration */
110290
110291   pArray = pTok->pArray;
110292   memset(&tsc, 0, sizeof(TermSelect));
110293   tsc.isReqPos = isReqPos;
110294
110295   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY 
110296         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
110297         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
110298         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
110299   filter.iCol = iColumn;
110300   filter.zTerm = pTok->z;
110301   filter.nTerm = pTok->n;
110302
110303   rc = sqlite3Fts3SegReaderIterate(p, pArray->apSegment, pArray->nSegment, 
110304       &filter, fts3TermSelectCb, (void *)&tsc
110305   );
110306   if( rc==SQLITE_OK ){
110307     rc = fts3TermSelectMerge(&tsc);
110308   }
110309
110310   if( rc==SQLITE_OK ){
110311     *ppOut = tsc.aaOutput[0];
110312     *pnOut = tsc.anOutput[0];
110313   }else{
110314     int i;
110315     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
110316       sqlite3_free(tsc.aaOutput[i]);
110317     }
110318   }
110319
110320   fts3SegReaderArrayFree(pArray);
110321   pTok->pArray = 0;
110322   return rc;
110323 }
110324
110325 /*
110326 ** This function counts the total number of docids in the doclist stored
110327 ** in buffer aList[], size nList bytes.
110328 **
110329 ** If the isPoslist argument is true, then it is assumed that the doclist
110330 ** contains a position-list following each docid. Otherwise, it is assumed
110331 ** that the doclist is simply a list of docids stored as delta encoded 
110332 ** varints.
110333 */
110334 static int fts3DoclistCountDocids(int isPoslist, char *aList, int nList){
110335   int nDoc = 0;                   /* Return value */
110336   if( aList ){
110337     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
110338     char *p = aList;              /* Cursor */
110339     if( !isPoslist ){
110340       /* The number of docids in the list is the same as the number of 
110341       ** varints. In FTS3 a varint consists of a single byte with the 0x80 
110342       ** bit cleared and zero or more bytes with the 0x80 bit set. So to
110343       ** count the varints in the buffer, just count the number of bytes
110344       ** with the 0x80 bit clear.  */
110345       while( p<aEnd ) nDoc += (((*p++)&0x80)==0);
110346     }else{
110347       while( p<aEnd ){
110348         nDoc++;
110349         while( (*p++)&0x80 );     /* Skip docid varint */
110350         fts3PoslistCopy(0, &p);   /* Skip over position list */
110351       }
110352     }
110353   }
110354
110355   return nDoc;
110356 }
110357
110358 /*
110359 ** Call sqlite3Fts3DeferToken() for each token in the expression pExpr.
110360 */
110361 static int fts3DeferExpression(Fts3Cursor *pCsr, Fts3Expr *pExpr){
110362   int rc = SQLITE_OK;
110363   if( pExpr ){
110364     rc = fts3DeferExpression(pCsr, pExpr->pLeft);
110365     if( rc==SQLITE_OK ){
110366       rc = fts3DeferExpression(pCsr, pExpr->pRight);
110367     }
110368     if( pExpr->eType==FTSQUERY_PHRASE ){
110369       int iCol = pExpr->pPhrase->iColumn;
110370       int i;
110371       for(i=0; rc==SQLITE_OK && i<pExpr->pPhrase->nToken; i++){
110372         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
110373         if( pToken->pDeferred==0 ){
110374           rc = sqlite3Fts3DeferToken(pCsr, pToken, iCol);
110375         }
110376       }
110377     }
110378   }
110379   return rc;
110380 }
110381
110382 /*
110383 ** This function removes the position information from a doclist. When
110384 ** called, buffer aList (size *pnList bytes) contains a doclist that includes
110385 ** position information. This function removes the position information so
110386 ** that aList contains only docids, and adjusts *pnList to reflect the new
110387 ** (possibly reduced) size of the doclist.
110388 */
110389 static void fts3DoclistStripPositions(
110390   char *aList,                    /* IN/OUT: Buffer containing doclist */
110391   int *pnList                     /* IN/OUT: Size of doclist in bytes */
110392 ){
110393   if( aList ){
110394     char *aEnd = &aList[*pnList]; /* Pointer to one byte after EOF */
110395     char *p = aList;              /* Input cursor */
110396     char *pOut = aList;           /* Output cursor */
110397   
110398     while( p<aEnd ){
110399       sqlite3_int64 delta;
110400       p += sqlite3Fts3GetVarint(p, &delta);
110401       fts3PoslistCopy(0, &p);
110402       pOut += sqlite3Fts3PutVarint(pOut, delta);
110403     }
110404
110405     *pnList = (int)(pOut - aList);
110406   }
110407 }
110408
110409 /* 
110410 ** Return a DocList corresponding to the phrase *pPhrase.
110411 **
110412 ** If this function returns SQLITE_OK, but *pnOut is set to a negative value,
110413 ** then no tokens in the phrase were looked up in the full-text index. This
110414 ** is only possible when this function is called from within xFilter(). The
110415 ** caller should assume that all documents match the phrase. The actual
110416 ** filtering will take place in xNext().
110417 */
110418 static int fts3PhraseSelect(
110419   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
110420   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
110421   int isReqPos,                   /* True if output should contain positions */
110422   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
110423   int *pnOut                      /* OUT: Size of buffer at *paOut */
110424 ){
110425   char *pOut = 0;
110426   int nOut = 0;
110427   int rc = SQLITE_OK;
110428   int ii;
110429   int iCol = pPhrase->iColumn;
110430   int isTermPos = (pPhrase->nToken>1 || isReqPos);
110431   Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
110432   int isFirst = 1;
110433
110434   int iPrevTok = 0;
110435   int nDoc = 0;
110436
110437   /* If this is an xFilter() evaluation, create a segment-reader for each
110438   ** phrase token. Or, if this is an xNext() or snippet/offsets/matchinfo
110439   ** evaluation, only create segment-readers if there are no Fts3DeferredToken
110440   ** objects attached to the phrase-tokens.
110441   */
110442   for(ii=0; ii<pPhrase->nToken; ii++){
110443     Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
110444     if( pTok->pArray==0 ){
110445       if( (pCsr->eEvalmode==FTS3_EVAL_FILTER)
110446        || (pCsr->eEvalmode==FTS3_EVAL_NEXT && pCsr->pDeferred==0) 
110447        || (pCsr->eEvalmode==FTS3_EVAL_MATCHINFO && pTok->bFulltext) 
110448       ){
110449         rc = fts3TermSegReaderArray(
110450             pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pArray
110451         );
110452         if( rc!=SQLITE_OK ) return rc;
110453       }
110454     }
110455   }
110456
110457   for(ii=0; ii<pPhrase->nToken; ii++){
110458     Fts3PhraseToken *pTok;        /* Token to find doclist for */
110459     int iTok = 0;                 /* The token being queried this iteration */
110460     char *pList = 0;              /* Pointer to token doclist */
110461     int nList = 0;                /* Size of buffer at pList */
110462
110463     /* Select a token to process. If this is an xFilter() call, then tokens 
110464     ** are processed in order from least to most costly. Otherwise, tokens 
110465     ** are processed in the order in which they occur in the phrase.
110466     */
110467     if( pCsr->eEvalmode==FTS3_EVAL_MATCHINFO ){
110468       assert( isReqPos );
110469       iTok = ii;
110470       pTok = &pPhrase->aToken[iTok];
110471       if( pTok->bFulltext==0 ) continue;
110472     }else if( pCsr->eEvalmode==FTS3_EVAL_NEXT || isReqPos ){
110473       iTok = ii;
110474       pTok = &pPhrase->aToken[iTok];
110475     }else{
110476       int nMinCost = 0x7FFFFFFF;
110477       int jj;
110478
110479       /* Find the remaining token with the lowest cost. */
110480       for(jj=0; jj<pPhrase->nToken; jj++){
110481         Fts3SegReaderArray *pArray = pPhrase->aToken[jj].pArray;
110482         if( pArray && pArray->nCost<nMinCost ){
110483           iTok = jj;
110484           nMinCost = pArray->nCost;
110485         }
110486       }
110487       pTok = &pPhrase->aToken[iTok];
110488
110489       /* This branch is taken if it is determined that loading the doclist
110490       ** for the next token would require more IO than loading all documents
110491       ** currently identified by doclist pOut/nOut. No further doclists will
110492       ** be loaded from the full-text index for this phrase.
110493       */
110494       if( nMinCost>nDoc && ii>0 ){
110495         rc = fts3DeferExpression(pCsr, pCsr->pExpr);
110496         break;
110497       }
110498     }
110499
110500     if( pCsr->eEvalmode==FTS3_EVAL_NEXT && pTok->pDeferred ){
110501       rc = fts3DeferredTermSelect(pTok->pDeferred, isTermPos, &nList, &pList);
110502     }else{
110503       if( pTok->pArray ){
110504         rc = fts3TermSelect(p, pTok, iCol, isTermPos, &nList, &pList);
110505       }
110506       pTok->bFulltext = 1;
110507     }
110508     assert( rc!=SQLITE_OK || pCsr->eEvalmode || pTok->pArray==0 );
110509     if( rc!=SQLITE_OK ) break;
110510
110511     if( isFirst ){
110512       pOut = pList;
110513       nOut = nList;
110514       if( pCsr->eEvalmode==FTS3_EVAL_FILTER && pPhrase->nToken>1 ){
110515         nDoc = fts3DoclistCountDocids(1, pOut, nOut);
110516       }
110517       isFirst = 0;
110518       iPrevTok = iTok;
110519     }else{
110520       /* Merge the new term list and the current output. */
110521       char *aLeft, *aRight;
110522       int nLeft, nRight;
110523       int nDist;
110524       int mt;
110525
110526       /* If this is the final token of the phrase, and positions were not
110527       ** requested by the caller, use MERGE_PHRASE instead of POS_PHRASE.
110528       ** This drops the position information from the output list.
110529       */
110530       mt = MERGE_POS_PHRASE;
110531       if( ii==pPhrase->nToken-1 && !isReqPos ) mt = MERGE_PHRASE;
110532
110533       assert( iPrevTok!=iTok );
110534       if( iPrevTok<iTok ){
110535         aLeft = pOut;
110536         nLeft = nOut;
110537         aRight = pList;
110538         nRight = nList;
110539         nDist = iTok-iPrevTok;
110540         iPrevTok = iTok;
110541       }else{
110542         aRight = pOut;
110543         nRight = nOut;
110544         aLeft = pList;
110545         nLeft = nList;
110546         nDist = iPrevTok-iTok;
110547       }
110548       pOut = aRight;
110549       fts3DoclistMerge(
110550           mt, nDist, 0, pOut, &nOut, aLeft, nLeft, aRight, nRight, &nDoc
110551       );
110552       sqlite3_free(aLeft);
110553     }
110554     assert( nOut==0 || pOut!=0 );
110555   }
110556
110557   if( rc==SQLITE_OK ){
110558     if( ii!=pPhrase->nToken ){
110559       assert( pCsr->eEvalmode==FTS3_EVAL_FILTER && isReqPos==0 );
110560       fts3DoclistStripPositions(pOut, &nOut);
110561     }
110562     *paOut = pOut;
110563     *pnOut = nOut;
110564   }else{
110565     sqlite3_free(pOut);
110566   }
110567   return rc;
110568 }
110569
110570 /*
110571 ** This function merges two doclists according to the requirements of a
110572 ** NEAR operator.
110573 **
110574 ** Both input doclists must include position information. The output doclist 
110575 ** includes position information if the first argument to this function
110576 ** is MERGE_POS_NEAR, or does not if it is MERGE_NEAR.
110577 */
110578 static int fts3NearMerge(
110579   int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
110580   int nNear,                      /* Parameter to NEAR operator */
110581   int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
110582   char *aLeft,                    /* Doclist for LHS (incl. positions) */
110583   int nLeft,                      /* Size of LHS doclist in bytes */
110584   int nTokenRight,                /* As nTokenLeft */
110585   char *aRight,                   /* As aLeft */
110586   int nRight,                     /* As nRight */
110587   char **paOut,                   /* OUT: Results of merge (malloced) */
110588   int *pnOut                      /* OUT: Sized of output buffer */
110589 ){
110590   char *aOut;                     /* Buffer to write output doclist to */
110591   int rc;                         /* Return code */
110592
110593   assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
110594
110595   aOut = sqlite3_malloc(nLeft+nRight+1);
110596   if( aOut==0 ){
110597     rc = SQLITE_NOMEM;
110598   }else{
110599     rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft, 
110600       aOut, pnOut, aLeft, nLeft, aRight, nRight, 0
110601     );
110602     if( rc!=SQLITE_OK ){
110603       sqlite3_free(aOut);
110604       aOut = 0;
110605     }
110606   }
110607
110608   *paOut = aOut;
110609   return rc;
110610 }
110611
110612 /*
110613 ** This function is used as part of the processing for the snippet() and
110614 ** offsets() functions.
110615 **
110616 ** Both pLeft and pRight are expression nodes of type FTSQUERY_PHRASE. Both
110617 ** have their respective doclists (including position information) loaded
110618 ** in Fts3Expr.aDoclist/nDoclist. This function removes all entries from
110619 ** each doclist that are not within nNear tokens of a corresponding entry
110620 ** in the other doclist.
110621 */
110622 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
110623   int rc;                         /* Return code */
110624
110625   assert( pLeft->eType==FTSQUERY_PHRASE );
110626   assert( pRight->eType==FTSQUERY_PHRASE );
110627   assert( pLeft->isLoaded && pRight->isLoaded );
110628
110629   if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
110630     sqlite3_free(pLeft->aDoclist);
110631     sqlite3_free(pRight->aDoclist);
110632     pRight->aDoclist = 0;
110633     pLeft->aDoclist = 0;
110634     rc = SQLITE_OK;
110635   }else{
110636     char *aOut;                   /* Buffer in which to assemble new doclist */
110637     int nOut;                     /* Size of buffer aOut in bytes */
110638
110639     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
110640         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
110641         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
110642         &aOut, &nOut
110643     );
110644     if( rc!=SQLITE_OK ) return rc;
110645     sqlite3_free(pRight->aDoclist);
110646     pRight->aDoclist = aOut;
110647     pRight->nDoclist = nOut;
110648
110649     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
110650         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
110651         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
110652         &aOut, &nOut
110653     );
110654     sqlite3_free(pLeft->aDoclist);
110655     pLeft->aDoclist = aOut;
110656     pLeft->nDoclist = nOut;
110657   }
110658   return rc;
110659 }
110660
110661
110662 /*
110663 ** Allocate an Fts3SegReaderArray for each token in the expression pExpr. 
110664 ** The allocated objects are stored in the Fts3PhraseToken.pArray member
110665 ** variables of each token structure.
110666 */
110667 static int fts3ExprAllocateSegReaders(
110668   Fts3Cursor *pCsr,               /* FTS3 table */
110669   Fts3Expr *pExpr,                /* Expression to create seg-readers for */
110670   int *pnExpr                     /* OUT: Number of AND'd expressions */
110671 ){
110672   int rc = SQLITE_OK;             /* Return code */
110673
110674   assert( pCsr->eEvalmode==FTS3_EVAL_FILTER );
110675   if( pnExpr && pExpr->eType!=FTSQUERY_AND ){
110676     (*pnExpr)++;
110677     pnExpr = 0;
110678   }
110679
110680   if( pExpr->eType==FTSQUERY_PHRASE ){
110681     Fts3Phrase *pPhrase = pExpr->pPhrase;
110682     int ii;
110683
110684     for(ii=0; rc==SQLITE_OK && ii<pPhrase->nToken; ii++){
110685       Fts3PhraseToken *pTok = &pPhrase->aToken[ii];
110686       if( pTok->pArray==0 ){
110687         rc = fts3TermSegReaderArray(
110688             pCsr, pTok->z, pTok->n, pTok->isPrefix, &pTok->pArray
110689         );
110690       }
110691     }
110692   }else{ 
110693     rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pLeft, pnExpr);
110694     if( rc==SQLITE_OK ){
110695       rc = fts3ExprAllocateSegReaders(pCsr, pExpr->pRight, pnExpr);
110696     }
110697   }
110698   return rc;
110699 }
110700
110701 /*
110702 ** Free the Fts3SegReaderArray objects associated with each token in the
110703 ** expression pExpr. In other words, this function frees the resources
110704 ** allocated by fts3ExprAllocateSegReaders().
110705 */
110706 static void fts3ExprFreeSegReaders(Fts3Expr *pExpr){
110707   if( pExpr ){
110708     Fts3Phrase *pPhrase = pExpr->pPhrase;
110709     if( pPhrase ){
110710       int kk;
110711       for(kk=0; kk<pPhrase->nToken; kk++){
110712         fts3SegReaderArrayFree(pPhrase->aToken[kk].pArray);
110713         pPhrase->aToken[kk].pArray = 0;
110714       }
110715     }
110716     fts3ExprFreeSegReaders(pExpr->pLeft);
110717     fts3ExprFreeSegReaders(pExpr->pRight);
110718   }
110719 }
110720
110721 /*
110722 ** Return the sum of the costs of all tokens in the expression pExpr. This
110723 ** function must be called after Fts3SegReaderArrays have been allocated
110724 ** for all tokens using fts3ExprAllocateSegReaders().
110725 */
110726 static int fts3ExprCost(Fts3Expr *pExpr){
110727   int nCost;                      /* Return value */
110728   if( pExpr->eType==FTSQUERY_PHRASE ){
110729     Fts3Phrase *pPhrase = pExpr->pPhrase;
110730     int ii;
110731     nCost = 0;
110732     for(ii=0; ii<pPhrase->nToken; ii++){
110733       Fts3SegReaderArray *pArray = pPhrase->aToken[ii].pArray;
110734       if( pArray ){
110735         nCost += pPhrase->aToken[ii].pArray->nCost;
110736       }
110737     }
110738   }else{
110739     nCost = fts3ExprCost(pExpr->pLeft) + fts3ExprCost(pExpr->pRight);
110740   }
110741   return nCost;
110742 }
110743
110744 /*
110745 ** The following is a helper function (and type) for fts3EvalExpr(). It
110746 ** must be called after Fts3SegReaders have been allocated for every token
110747 ** in the expression. See the context it is called from in fts3EvalExpr()
110748 ** for further explanation.
110749 */
110750 typedef struct ExprAndCost ExprAndCost;
110751 struct ExprAndCost {
110752   Fts3Expr *pExpr;
110753   int nCost;
110754 };
110755 static void fts3ExprAssignCosts(
110756   Fts3Expr *pExpr,                /* Expression to create seg-readers for */
110757   ExprAndCost **ppExprCost        /* OUT: Write to *ppExprCost */
110758 ){
110759   if( pExpr->eType==FTSQUERY_AND ){
110760     fts3ExprAssignCosts(pExpr->pLeft, ppExprCost);
110761     fts3ExprAssignCosts(pExpr->pRight, ppExprCost);
110762   }else{
110763     (*ppExprCost)->pExpr = pExpr;
110764     (*ppExprCost)->nCost = fts3ExprCost(pExpr);
110765     (*ppExprCost)++;
110766   }
110767 }
110768
110769 /*
110770 ** Evaluate the full-text expression pExpr against FTS3 table pTab. Store
110771 ** the resulting doclist in *paOut and *pnOut. This routine mallocs for
110772 ** the space needed to store the output. The caller is responsible for
110773 ** freeing the space when it has finished.
110774 **
110775 ** This function is called in two distinct contexts:
110776 **
110777 **   * From within the virtual table xFilter() method. In this case, the
110778 **     output doclist contains entries for all rows in the table, based on
110779 **     data read from the full-text index.
110780 **
110781 **     In this case, if the query expression contains one or more tokens that 
110782 **     are very common, then the returned doclist may contain a superset of 
110783 **     the documents that actually match the expression.
110784 **
110785 **   * From within the virtual table xNext() method. This call is only made
110786 **     if the call from within xFilter() found that there were very common 
110787 **     tokens in the query expression and did return a superset of the 
110788 **     matching documents. In this case the returned doclist contains only
110789 **     entries that correspond to the current row of the table. Instead of
110790 **     reading the data for each token from the full-text index, the data is
110791 **     already available in-memory in the Fts3PhraseToken.pDeferred structures.
110792 **     See fts3EvalDeferred() for how it gets there.
110793 **
110794 ** In the first case above, Fts3Cursor.doDeferred==0. In the second (if it is
110795 ** required) Fts3Cursor.doDeferred==1.
110796 **
110797 ** If the SQLite invokes the snippet(), offsets() or matchinfo() function
110798 ** as part of a SELECT on an FTS3 table, this function is called on each
110799 ** individual phrase expression in the query. If there were very common tokens
110800 ** found in the xFilter() call, then this function is called once for phrase
110801 ** for each row visited, and the returned doclist contains entries for the
110802 ** current row only. Otherwise, if there were no very common tokens, then this
110803 ** function is called once only for each phrase in the query and the returned
110804 ** doclist contains entries for all rows of the table.
110805 **
110806 ** Fts3Cursor.doDeferred==1 when this function is called on phrases as a
110807 ** result of a snippet(), offsets() or matchinfo() invocation.
110808 */
110809 static int fts3EvalExpr(
110810   Fts3Cursor *p,                  /* Virtual table cursor handle */
110811   Fts3Expr *pExpr,                /* Parsed fts3 expression */
110812   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
110813   int *pnOut,                     /* OUT: Size of buffer at *paOut */
110814   int isReqPos                    /* Require positions in output buffer */
110815 ){
110816   int rc = SQLITE_OK;             /* Return code */
110817
110818   /* Zero the output parameters. */
110819   *paOut = 0;
110820   *pnOut = 0;
110821
110822   if( pExpr ){
110823     assert( pExpr->eType==FTSQUERY_NEAR   || pExpr->eType==FTSQUERY_OR     
110824          || pExpr->eType==FTSQUERY_AND    || pExpr->eType==FTSQUERY_NOT
110825          || pExpr->eType==FTSQUERY_PHRASE
110826     );
110827     assert( pExpr->eType==FTSQUERY_PHRASE || isReqPos==0 );
110828
110829     if( pExpr->eType==FTSQUERY_PHRASE ){
110830       rc = fts3PhraseSelect(p, pExpr->pPhrase,
110831           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
110832           paOut, pnOut
110833       );
110834       fts3ExprFreeSegReaders(pExpr);
110835     }else if( p->eEvalmode==FTS3_EVAL_FILTER && pExpr->eType==FTSQUERY_AND ){
110836       ExprAndCost *aExpr = 0;     /* Array of AND'd expressions and costs */
110837       int nExpr = 0;              /* Size of aExpr[] */
110838       char *aRet = 0;             /* Doclist to return to caller */
110839       int nRet = 0;               /* Length of aRet[] in bytes */
110840       int nDoc = 0x7FFFFFFF;
110841
110842       assert( !isReqPos );
110843
110844       rc = fts3ExprAllocateSegReaders(p, pExpr, &nExpr);
110845       if( rc==SQLITE_OK ){
110846         assert( nExpr>1 );
110847         aExpr = sqlite3_malloc(sizeof(ExprAndCost) * nExpr);
110848         if( !aExpr ) rc = SQLITE_NOMEM;
110849       }
110850       if( rc==SQLITE_OK ){
110851         int ii;                   /* Used to iterate through expressions */
110852
110853         fts3ExprAssignCosts(pExpr, &aExpr);
110854         aExpr -= nExpr;
110855         for(ii=0; ii<nExpr; ii++){
110856           char *aNew;
110857           int nNew;
110858           int jj;
110859           ExprAndCost *pBest = 0;
110860   
110861           for(jj=0; jj<nExpr; jj++){
110862             ExprAndCost *pCand = &aExpr[jj];
110863             if( pCand->pExpr && (pBest==0 || pCand->nCost<pBest->nCost) ){
110864               pBest = pCand;
110865             }
110866           }
110867   
110868           if( pBest->nCost>nDoc ){
110869             rc = fts3DeferExpression(p, p->pExpr);
110870             break;
110871           }else{
110872             rc = fts3EvalExpr(p, pBest->pExpr, &aNew, &nNew, 0);
110873             if( rc!=SQLITE_OK ) break;
110874             pBest->pExpr = 0;
110875             if( ii==0 ){
110876               aRet = aNew;
110877               nRet = nNew;
110878               nDoc = fts3DoclistCountDocids(0, aRet, nRet);
110879             }else{
110880               fts3DoclistMerge(
110881                   MERGE_AND, 0, 0, aRet, &nRet, aRet, nRet, aNew, nNew, &nDoc
110882               );
110883               sqlite3_free(aNew);
110884             }
110885           }
110886         }
110887       }
110888
110889       if( rc==SQLITE_OK ){
110890         *paOut = aRet;
110891         *pnOut = nRet;
110892       }else{
110893         assert( *paOut==0 );
110894         sqlite3_free(aRet);
110895       }
110896       sqlite3_free(aExpr);
110897       fts3ExprFreeSegReaders(pExpr);
110898
110899     }else{
110900       char *aLeft;
110901       char *aRight;
110902       int nLeft;
110903       int nRight;
110904
110905       assert( pExpr->eType==FTSQUERY_NEAR 
110906            || pExpr->eType==FTSQUERY_OR
110907            || pExpr->eType==FTSQUERY_NOT
110908            || (pExpr->eType==FTSQUERY_AND && p->eEvalmode==FTS3_EVAL_NEXT)
110909       );
110910
110911       if( 0==(rc = fts3EvalExpr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
110912        && 0==(rc = fts3EvalExpr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
110913       ){
110914         switch( pExpr->eType ){
110915           case FTSQUERY_NEAR: {
110916             Fts3Expr *pLeft;
110917             Fts3Expr *pRight;
110918             int mergetype = MERGE_NEAR;
110919             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
110920               mergetype = MERGE_POS_NEAR;
110921             }
110922             pLeft = pExpr->pLeft;
110923             while( pLeft->eType==FTSQUERY_NEAR ){ 
110924               pLeft=pLeft->pRight;
110925             }
110926             pRight = pExpr->pRight;
110927             assert( pRight->eType==FTSQUERY_PHRASE );
110928             assert( pLeft->eType==FTSQUERY_PHRASE );
110929
110930             rc = fts3NearMerge(mergetype, pExpr->nNear, 
110931                 pLeft->pPhrase->nToken, aLeft, nLeft,
110932                 pRight->pPhrase->nToken, aRight, nRight,
110933                 paOut, pnOut
110934             );
110935             sqlite3_free(aLeft);
110936             break;
110937           }
110938
110939           case FTSQUERY_OR: {
110940             /* Allocate a buffer for the output. The maximum size is the
110941             ** sum of the sizes of the two input buffers. The +1 term is
110942             ** so that a buffer of zero bytes is never allocated - this can
110943             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
110944             */
110945             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
110946             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
110947                 aLeft, nLeft, aRight, nRight, 0
110948             );
110949             *paOut = aBuffer;
110950             sqlite3_free(aLeft);
110951             break;
110952           }
110953
110954           default: {
110955             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
110956             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
110957                 aLeft, nLeft, aRight, nRight, 0
110958             );
110959             *paOut = aLeft;
110960             break;
110961           }
110962         }
110963       }
110964       sqlite3_free(aRight);
110965     }
110966   }
110967
110968   assert( rc==SQLITE_OK || *paOut==0 );
110969   return rc;
110970 }
110971
110972 /*
110973 ** This function is called from within xNext() for each row visited by
110974 ** an FTS3 query. If evaluating the FTS3 query expression within xFilter()
110975 ** was able to determine the exact set of matching rows, this function sets
110976 ** *pbRes to true and returns SQLITE_IO immediately.
110977 **
110978 ** Otherwise, if evaluating the query expression within xFilter() returned a
110979 ** superset of the matching documents instead of an exact set (this happens
110980 ** when the query includes very common tokens and it is deemed too expensive to
110981 ** load their doclists from disk), this function tests if the current row
110982 ** really does match the FTS3 query.
110983 **
110984 ** If an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK
110985 ** is returned and *pbRes is set to true if the current row matches the
110986 ** FTS3 query (and should be included in the results returned to SQLite), or
110987 ** false otherwise.
110988 */
110989 static int fts3EvalDeferred(
110990   Fts3Cursor *pCsr,               /* FTS3 cursor pointing at row to test */
110991   int *pbRes                      /* OUT: Set to true if row is a match */
110992 ){
110993   int rc = SQLITE_OK;
110994   if( pCsr->pDeferred==0 ){
110995     *pbRes = 1;
110996   }else{
110997     rc = fts3CursorSeek(0, pCsr);
110998     if( rc==SQLITE_OK ){
110999       sqlite3Fts3FreeDeferredDoclists(pCsr);
111000       rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
111001     }
111002     if( rc==SQLITE_OK ){
111003       char *a = 0;
111004       int n = 0;
111005       rc = fts3EvalExpr(pCsr, pCsr->pExpr, &a, &n, 0);
111006       assert( n>=0 );
111007       *pbRes = (n>0);
111008       sqlite3_free(a);
111009     }
111010   }
111011   return rc;
111012 }
111013
111014 /*
111015 ** Advance the cursor to the next row in the %_content table that
111016 ** matches the search criteria.  For a MATCH search, this will be
111017 ** the next row that matches. For a full-table scan, this will be
111018 ** simply the next row in the %_content table.  For a docid lookup,
111019 ** this routine simply sets the EOF flag.
111020 **
111021 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
111022 ** even if we reach end-of-file.  The fts3EofMethod() will be called
111023 ** subsequently to determine whether or not an EOF was hit.
111024 */
111025 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
111026   int res;
111027   int rc = SQLITE_OK;             /* Return code */
111028   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
111029
111030   pCsr->eEvalmode = FTS3_EVAL_NEXT;
111031   do {
111032     if( pCsr->aDoclist==0 ){
111033       if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
111034         pCsr->isEof = 1;
111035         rc = sqlite3_reset(pCsr->pStmt);
111036         break;
111037       }
111038       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
111039     }else{
111040       if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
111041         pCsr->isEof = 1;
111042         break;
111043       }
111044       sqlite3_reset(pCsr->pStmt);
111045       fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
111046       pCsr->isRequireSeek = 1;
111047       pCsr->isMatchinfoNeeded = 1;
111048     }
111049   }while( SQLITE_OK==(rc = fts3EvalDeferred(pCsr, &res)) && res==0 );
111050
111051   return rc;
111052 }
111053
111054 /*
111055 ** This is the xFilter interface for the virtual table.  See
111056 ** the virtual table xFilter method documentation for additional
111057 ** information.
111058 **
111059 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
111060 ** the %_content table.
111061 **
111062 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
111063 ** in the %_content table.
111064 **
111065 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
111066 ** column on the left-hand side of the MATCH operator is column
111067 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
111068 ** side of the MATCH operator.
111069 */
111070 static int fts3FilterMethod(
111071   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
111072   int idxNum,                     /* Strategy index */
111073   const char *idxStr,             /* Unused */
111074   int nVal,                       /* Number of elements in apVal */
111075   sqlite3_value **apVal           /* Arguments for the indexing scheme */
111076 ){
111077   const char *azSql[] = {
111078     "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
111079     "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
111080   };
111081   int rc;                         /* Return code */
111082   char *zSql;                     /* SQL statement used to access %_content */
111083   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
111084   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
111085
111086   UNUSED_PARAMETER(idxStr);
111087   UNUSED_PARAMETER(nVal);
111088
111089   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
111090   assert( nVal==0 || nVal==1 );
111091   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
111092   assert( p->pSegments==0 );
111093
111094   /* In case the cursor has been used before, clear it now. */
111095   sqlite3_finalize(pCsr->pStmt);
111096   sqlite3_free(pCsr->aDoclist);
111097   sqlite3Fts3ExprFree(pCsr->pExpr);
111098   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
111099
111100   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
111101     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
111102     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
111103
111104     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
111105       return SQLITE_NOMEM;
111106     }
111107
111108     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, 
111109         iCol, zQuery, -1, &pCsr->pExpr
111110     );
111111     if( rc!=SQLITE_OK ){
111112       if( rc==SQLITE_ERROR ){
111113         p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
111114                                           zQuery);
111115       }
111116       return rc;
111117     }
111118
111119     rc = sqlite3Fts3ReadLock(p);
111120     if( rc!=SQLITE_OK ) return rc;
111121
111122     rc = fts3EvalExpr(pCsr, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
111123     sqlite3Fts3SegmentsClose(p);
111124     if( rc!=SQLITE_OK ) return rc;
111125     pCsr->pNextId = pCsr->aDoclist;
111126     pCsr->iPrevId = 0;
111127   }
111128
111129   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
111130   ** statement loops through all rows of the %_content table. For a
111131   ** full-text query or docid lookup, the statement retrieves a single
111132   ** row by docid.
111133   */
111134   zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
111135   if( !zSql ){
111136     rc = SQLITE_NOMEM;
111137   }else{
111138     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
111139     sqlite3_free(zSql);
111140   }
111141   if( rc==SQLITE_OK && idxNum==FTS3_DOCID_SEARCH ){
111142     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
111143   }
111144   pCsr->eSearch = (i16)idxNum;
111145
111146   if( rc!=SQLITE_OK ) return rc;
111147   return fts3NextMethod(pCursor);
111148 }
111149
111150 /* 
111151 ** This is the xEof method of the virtual table. SQLite calls this 
111152 ** routine to find out if it has reached the end of a result set.
111153 */
111154 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
111155   return ((Fts3Cursor *)pCursor)->isEof;
111156 }
111157
111158 /* 
111159 ** This is the xRowid method. The SQLite core calls this routine to
111160 ** retrieve the rowid for the current row of the result set. fts3
111161 ** exposes %_content.docid as the rowid for the virtual table. The
111162 ** rowid should be written to *pRowid.
111163 */
111164 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
111165   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
111166   if( pCsr->aDoclist ){
111167     *pRowid = pCsr->iPrevId;
111168   }else{
111169     /* This branch runs if the query is implemented using a full-table scan
111170     ** (not using the full-text index). In this case grab the rowid from the
111171     ** SELECT statement.
111172     */
111173     assert( pCsr->isRequireSeek==0 );
111174     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
111175   }
111176   return SQLITE_OK;
111177 }
111178
111179 /* 
111180 ** This is the xColumn method, called by SQLite to request a value from
111181 ** the row that the supplied cursor currently points to.
111182 */
111183 static int fts3ColumnMethod(
111184   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
111185   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
111186   int iCol                        /* Index of column to read value from */
111187 ){
111188   int rc;                         /* Return Code */
111189   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
111190   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
111191
111192   /* The column value supplied by SQLite must be in range. */
111193   assert( iCol>=0 && iCol<=p->nColumn+1 );
111194
111195   if( iCol==p->nColumn+1 ){
111196     /* This call is a request for the "docid" column. Since "docid" is an 
111197     ** alias for "rowid", use the xRowid() method to obtain the value.
111198     */
111199     sqlite3_int64 iRowid;
111200     rc = fts3RowidMethod(pCursor, &iRowid);
111201     sqlite3_result_int64(pContext, iRowid);
111202   }else if( iCol==p->nColumn ){
111203     /* The extra column whose name is the same as the table.
111204     ** Return a blob which is a pointer to the cursor.
111205     */
111206     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
111207     rc = SQLITE_OK;
111208   }else{
111209     rc = fts3CursorSeek(0, pCsr);
111210     if( rc==SQLITE_OK ){
111211       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
111212     }
111213   }
111214   return rc;
111215 }
111216
111217 /* 
111218 ** This function is the implementation of the xUpdate callback used by 
111219 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
111220 ** inserted, updated or deleted.
111221 */
111222 static int fts3UpdateMethod(
111223   sqlite3_vtab *pVtab,            /* Virtual table handle */
111224   int nArg,                       /* Size of argument array */
111225   sqlite3_value **apVal,          /* Array of arguments */
111226   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
111227 ){
111228   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
111229 }
111230
111231 /*
111232 ** Implementation of xSync() method. Flush the contents of the pending-terms
111233 ** hash-table to the database.
111234 */
111235 static int fts3SyncMethod(sqlite3_vtab *pVtab){
111236   int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
111237   sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
111238   return rc;
111239 }
111240
111241 /*
111242 ** Implementation of xBegin() method. This is a no-op.
111243 */
111244 static int fts3BeginMethod(sqlite3_vtab *pVtab){
111245   UNUSED_PARAMETER(pVtab);
111246   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
111247   return SQLITE_OK;
111248 }
111249
111250 /*
111251 ** Implementation of xCommit() method. This is a no-op. The contents of
111252 ** the pending-terms hash-table have already been flushed into the database
111253 ** by fts3SyncMethod().
111254 */
111255 static int fts3CommitMethod(sqlite3_vtab *pVtab){
111256   UNUSED_PARAMETER(pVtab);
111257   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
111258   return SQLITE_OK;
111259 }
111260
111261 /*
111262 ** Implementation of xRollback(). Discard the contents of the pending-terms
111263 ** hash-table. Any changes made to the database are reverted by SQLite.
111264 */
111265 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
111266   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
111267   return SQLITE_OK;
111268 }
111269
111270 /*
111271 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
111272 ** The loaded doclist contains positions as well as the document ids.
111273 ** This is used by the matchinfo(), snippet() and offsets() auxillary
111274 ** functions.
111275 */
111276 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Cursor *pCsr, Fts3Expr *pExpr){
111277   int rc;
111278   assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
111279   assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
111280   rc = fts3EvalExpr(pCsr, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
111281   return rc;
111282 }
111283
111284 SQLITE_PRIVATE int sqlite3Fts3ExprLoadFtDoclist(
111285   Fts3Cursor *pCsr, 
111286   Fts3Expr *pExpr,
111287   char **paDoclist,
111288   int *pnDoclist
111289 ){
111290   int rc;
111291   assert( pCsr->eEvalmode==FTS3_EVAL_NEXT );
111292   assert( pExpr->eType==FTSQUERY_PHRASE && pExpr->pPhrase );
111293   pCsr->eEvalmode = FTS3_EVAL_MATCHINFO;
111294   rc = fts3EvalExpr(pCsr, pExpr, paDoclist, pnDoclist, 1);
111295   pCsr->eEvalmode = FTS3_EVAL_NEXT;
111296   return rc;
111297 }
111298
111299 /*
111300 ** After ExprLoadDoclist() (see above) has been called, this function is
111301 ** used to iterate/search through the position lists that make up the doclist
111302 ** stored in pExpr->aDoclist.
111303 */
111304 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
111305   Fts3Expr *pExpr,                /* Access this expressions doclist */
111306   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
111307   int iCol                        /* Column of requested pos-list */
111308 ){
111309   assert( pExpr->isLoaded );
111310   if( pExpr->aDoclist ){
111311     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
111312     char *pCsr = pExpr->pCurrent;
111313
111314     assert( pCsr );
111315     while( pCsr<pEnd ){
111316       if( pExpr->iCurrent<iDocid ){
111317         fts3PoslistCopy(0, &pCsr);
111318         if( pCsr<pEnd ){
111319           fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
111320         }
111321         pExpr->pCurrent = pCsr;
111322       }else{
111323         if( pExpr->iCurrent==iDocid ){
111324           int iThis = 0;
111325           if( iCol<0 ){
111326             /* If iCol is negative, return a pointer to the start of the
111327             ** position-list (instead of a pointer to the start of a list
111328             ** of offsets associated with a specific column).
111329             */
111330             return pCsr;
111331           }
111332           while( iThis<iCol ){
111333             fts3ColumnlistCopy(0, &pCsr);
111334             if( *pCsr==0x00 ) return 0;
111335             pCsr++;
111336             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
111337           }
111338           if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
111339         }
111340         return 0;
111341       }
111342     }
111343   }
111344
111345   return 0;
111346 }
111347
111348 /*
111349 ** Helper function used by the implementation of the overloaded snippet(),
111350 ** offsets() and optimize() SQL functions.
111351 **
111352 ** If the value passed as the third argument is a blob of size
111353 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
111354 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
111355 ** message is written to context pContext and SQLITE_ERROR returned. The
111356 ** string passed via zFunc is used as part of the error message.
111357 */
111358 static int fts3FunctionArg(
111359   sqlite3_context *pContext,      /* SQL function call context */
111360   const char *zFunc,              /* Function name */
111361   sqlite3_value *pVal,            /* argv[0] passed to function */
111362   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
111363 ){
111364   Fts3Cursor *pRet;
111365   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
111366    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
111367   ){
111368     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
111369     sqlite3_result_error(pContext, zErr, -1);
111370     sqlite3_free(zErr);
111371     return SQLITE_ERROR;
111372   }
111373   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
111374   *ppCsr = pRet;
111375   return SQLITE_OK;
111376 }
111377
111378 /*
111379 ** Implementation of the snippet() function for FTS3
111380 */
111381 static void fts3SnippetFunc(
111382   sqlite3_context *pContext,      /* SQLite function call context */
111383   int nVal,                       /* Size of apVal[] array */
111384   sqlite3_value **apVal           /* Array of arguments */
111385 ){
111386   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
111387   const char *zStart = "<b>";
111388   const char *zEnd = "</b>";
111389   const char *zEllipsis = "<b>...</b>";
111390   int iCol = -1;
111391   int nToken = 15;                /* Default number of tokens in snippet */
111392
111393   /* There must be at least one argument passed to this function (otherwise
111394   ** the non-overloaded version would have been called instead of this one).
111395   */
111396   assert( nVal>=1 );
111397
111398   if( nVal>6 ){
111399     sqlite3_result_error(pContext, 
111400         "wrong number of arguments to function snippet()", -1);
111401     return;
111402   }
111403   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
111404
111405   switch( nVal ){
111406     case 6: nToken = sqlite3_value_int(apVal[5]);
111407     case 5: iCol = sqlite3_value_int(apVal[4]);
111408     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
111409     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
111410     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
111411   }
111412   if( !zEllipsis || !zEnd || !zStart ){
111413     sqlite3_result_error_nomem(pContext);
111414   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
111415     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
111416   }
111417 }
111418
111419 /*
111420 ** Implementation of the offsets() function for FTS3
111421 */
111422 static void fts3OffsetsFunc(
111423   sqlite3_context *pContext,      /* SQLite function call context */
111424   int nVal,                       /* Size of argument array */
111425   sqlite3_value **apVal           /* Array of arguments */
111426 ){
111427   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
111428
111429   UNUSED_PARAMETER(nVal);
111430
111431   assert( nVal==1 );
111432   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
111433   assert( pCsr );
111434   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
111435     sqlite3Fts3Offsets(pContext, pCsr);
111436   }
111437 }
111438
111439 /* 
111440 ** Implementation of the special optimize() function for FTS3. This 
111441 ** function merges all segments in the database to a single segment.
111442 ** Example usage is:
111443 **
111444 **   SELECT optimize(t) FROM t LIMIT 1;
111445 **
111446 ** where 't' is the name of an FTS3 table.
111447 */
111448 static void fts3OptimizeFunc(
111449   sqlite3_context *pContext,      /* SQLite function call context */
111450   int nVal,                       /* Size of argument array */
111451   sqlite3_value **apVal           /* Array of arguments */
111452 ){
111453   int rc;                         /* Return code */
111454   Fts3Table *p;                   /* Virtual table handle */
111455   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
111456
111457   UNUSED_PARAMETER(nVal);
111458
111459   assert( nVal==1 );
111460   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
111461   p = (Fts3Table *)pCursor->base.pVtab;
111462   assert( p );
111463
111464   rc = sqlite3Fts3Optimize(p);
111465
111466   switch( rc ){
111467     case SQLITE_OK:
111468       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
111469       break;
111470     case SQLITE_DONE:
111471       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
111472       break;
111473     default:
111474       sqlite3_result_error_code(pContext, rc);
111475       break;
111476   }
111477 }
111478
111479 /*
111480 ** Implementation of the matchinfo() function for FTS3
111481 */
111482 static void fts3MatchinfoFunc(
111483   sqlite3_context *pContext,      /* SQLite function call context */
111484   int nVal,                       /* Size of argument array */
111485   sqlite3_value **apVal           /* Array of arguments */
111486 ){
111487   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
111488   assert( nVal==1 || nVal==2 );
111489   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
111490     const char *zArg = 0;
111491     if( nVal>1 ){
111492       zArg = (const char *)sqlite3_value_text(apVal[1]);
111493     }
111494     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
111495   }
111496 }
111497
111498 /*
111499 ** This routine implements the xFindFunction method for the FTS3
111500 ** virtual table.
111501 */
111502 static int fts3FindFunctionMethod(
111503   sqlite3_vtab *pVtab,            /* Virtual table handle */
111504   int nArg,                       /* Number of SQL function arguments */
111505   const char *zName,              /* Name of SQL function */
111506   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
111507   void **ppArg                    /* Unused */
111508 ){
111509   struct Overloaded {
111510     const char *zName;
111511     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
111512   } aOverload[] = {
111513     { "snippet", fts3SnippetFunc },
111514     { "offsets", fts3OffsetsFunc },
111515     { "optimize", fts3OptimizeFunc },
111516     { "matchinfo", fts3MatchinfoFunc },
111517   };
111518   int i;                          /* Iterator variable */
111519
111520   UNUSED_PARAMETER(pVtab);
111521   UNUSED_PARAMETER(nArg);
111522   UNUSED_PARAMETER(ppArg);
111523
111524   for(i=0; i<SizeofArray(aOverload); i++){
111525     if( strcmp(zName, aOverload[i].zName)==0 ){
111526       *pxFunc = aOverload[i].xFunc;
111527       return 1;
111528     }
111529   }
111530
111531   /* No function of the specified name was found. Return 0. */
111532   return 0;
111533 }
111534
111535 /*
111536 ** Implementation of FTS3 xRename method. Rename an fts3 table.
111537 */
111538 static int fts3RenameMethod(
111539   sqlite3_vtab *pVtab,            /* Virtual table handle */
111540   const char *zName               /* New name of table */
111541 ){
111542   Fts3Table *p = (Fts3Table *)pVtab;
111543   sqlite3 *db = p->db;            /* Database connection */
111544   int rc;                         /* Return Code */
111545
111546   rc = sqlite3Fts3PendingTermsFlush(p);
111547   if( rc!=SQLITE_OK ){
111548     return rc;
111549   }
111550
111551   fts3DbExec(&rc, db,
111552     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
111553     p->zDb, p->zName, zName
111554   );
111555   if( p->bHasDocsize ){
111556     fts3DbExec(&rc, db,
111557       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
111558       p->zDb, p->zName, zName
111559     );
111560   }
111561   if( p->bHasStat ){
111562     fts3DbExec(&rc, db,
111563       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
111564       p->zDb, p->zName, zName
111565     );
111566   }
111567   fts3DbExec(&rc, db,
111568     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
111569     p->zDb, p->zName, zName
111570   );
111571   fts3DbExec(&rc, db,
111572     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
111573     p->zDb, p->zName, zName
111574   );
111575   return rc;
111576 }
111577
111578 static const sqlite3_module fts3Module = {
111579   /* iVersion      */ 0,
111580   /* xCreate       */ fts3CreateMethod,
111581   /* xConnect      */ fts3ConnectMethod,
111582   /* xBestIndex    */ fts3BestIndexMethod,
111583   /* xDisconnect   */ fts3DisconnectMethod,
111584   /* xDestroy      */ fts3DestroyMethod,
111585   /* xOpen         */ fts3OpenMethod,
111586   /* xClose        */ fts3CloseMethod,
111587   /* xFilter       */ fts3FilterMethod,
111588   /* xNext         */ fts3NextMethod,
111589   /* xEof          */ fts3EofMethod,
111590   /* xColumn       */ fts3ColumnMethod,
111591   /* xRowid        */ fts3RowidMethod,
111592   /* xUpdate       */ fts3UpdateMethod,
111593   /* xBegin        */ fts3BeginMethod,
111594   /* xSync         */ fts3SyncMethod,
111595   /* xCommit       */ fts3CommitMethod,
111596   /* xRollback     */ fts3RollbackMethod,
111597   /* xFindFunction */ fts3FindFunctionMethod,
111598   /* xRename */       fts3RenameMethod,
111599 };
111600
111601 /*
111602 ** This function is registered as the module destructor (called when an
111603 ** FTS3 enabled database connection is closed). It frees the memory
111604 ** allocated for the tokenizer hash table.
111605 */
111606 static void hashDestroy(void *p){
111607   Fts3Hash *pHash = (Fts3Hash *)p;
111608   sqlite3Fts3HashClear(pHash);
111609   sqlite3_free(pHash);
111610 }
111611
111612 /*
111613 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
111614 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
111615 ** respectively. The following three forward declarations are for functions
111616 ** declared in these files used to retrieve the respective implementations.
111617 **
111618 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
111619 ** to by the argument to point to the "simple" tokenizer implementation.
111620 ** And so on.
111621 */
111622 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
111623 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
111624 #ifdef SQLITE_ENABLE_ICU
111625 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
111626 #endif
111627
111628 /*
111629 ** Initialise the fts3 extension. If this extension is built as part
111630 ** of the sqlite library, then this function is called directly by
111631 ** SQLite. If fts3 is built as a dynamically loadable extension, this
111632 ** function is called by the sqlite3_extension_init() entry point.
111633 */
111634 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
111635   int rc = SQLITE_OK;
111636   Fts3Hash *pHash = 0;
111637   const sqlite3_tokenizer_module *pSimple = 0;
111638   const sqlite3_tokenizer_module *pPorter = 0;
111639
111640 #ifdef SQLITE_ENABLE_ICU
111641   const sqlite3_tokenizer_module *pIcu = 0;
111642   sqlite3Fts3IcuTokenizerModule(&pIcu);
111643 #endif
111644
111645   sqlite3Fts3SimpleTokenizerModule(&pSimple);
111646   sqlite3Fts3PorterTokenizerModule(&pPorter);
111647
111648   /* Allocate and initialise the hash-table used to store tokenizers. */
111649   pHash = sqlite3_malloc(sizeof(Fts3Hash));
111650   if( !pHash ){
111651     rc = SQLITE_NOMEM;
111652   }else{
111653     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
111654   }
111655
111656   /* Load the built-in tokenizers into the hash table */
111657   if( rc==SQLITE_OK ){
111658     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
111659      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
111660 #ifdef SQLITE_ENABLE_ICU
111661      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
111662 #endif
111663     ){
111664       rc = SQLITE_NOMEM;
111665     }
111666   }
111667
111668 #ifdef SQLITE_TEST
111669   if( rc==SQLITE_OK ){
111670     rc = sqlite3Fts3ExprInitTestInterface(db);
111671   }
111672 #endif
111673
111674   /* Create the virtual table wrapper around the hash-table and overload 
111675   ** the two scalar functions. If this is successful, register the
111676   ** module with sqlite.
111677   */
111678   if( SQLITE_OK==rc 
111679    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
111680    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
111681    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
111682    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
111683    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
111684    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
111685   ){
111686     rc = sqlite3_create_module_v2(
111687         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
111688     );
111689     if( rc==SQLITE_OK ){
111690       rc = sqlite3_create_module_v2(
111691           db, "fts4", &fts3Module, (void *)pHash, 0
111692       );
111693     }
111694     return rc;
111695   }
111696
111697   /* An error has occurred. Delete the hash table and return the error code. */
111698   assert( rc!=SQLITE_OK );
111699   if( pHash ){
111700     sqlite3Fts3HashClear(pHash);
111701     sqlite3_free(pHash);
111702   }
111703   return rc;
111704 }
111705
111706 #if !SQLITE_CORE
111707 SQLITE_API int sqlite3_extension_init(
111708   sqlite3 *db, 
111709   char **pzErrMsg,
111710   const sqlite3_api_routines *pApi
111711 ){
111712   SQLITE_EXTENSION_INIT2(pApi)
111713   return sqlite3Fts3Init(db);
111714 }
111715 #endif
111716
111717 #endif
111718
111719 /************** End of fts3.c ************************************************/
111720 /************** Begin file fts3_expr.c ***************************************/
111721 /*
111722 ** 2008 Nov 28
111723 **
111724 ** The author disclaims copyright to this source code.  In place of
111725 ** a legal notice, here is a blessing:
111726 **
111727 **    May you do good and not evil.
111728 **    May you find forgiveness for yourself and forgive others.
111729 **    May you share freely, never taking more than you give.
111730 **
111731 ******************************************************************************
111732 **
111733 ** This module contains code that implements a parser for fts3 query strings
111734 ** (the right-hand argument to the MATCH operator). Because the supported 
111735 ** syntax is relatively simple, the whole tokenizer/parser system is
111736 ** hand-coded. 
111737 */
111738 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
111739
111740 /*
111741 ** By default, this module parses the legacy syntax that has been 
111742 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
111743 ** is defined, then it uses the new syntax. The differences between
111744 ** the new and the old syntaxes are:
111745 **
111746 **  a) The new syntax supports parenthesis. The old does not.
111747 **
111748 **  b) The new syntax supports the AND and NOT operators. The old does not.
111749 **
111750 **  c) The old syntax supports the "-" token qualifier. This is not 
111751 **     supported by the new syntax (it is replaced by the NOT operator).
111752 **
111753 **  d) When using the old syntax, the OR operator has a greater precedence
111754 **     than an implicit AND. When using the new, both implicity and explicit
111755 **     AND operators have a higher precedence than OR.
111756 **
111757 ** If compiled with SQLITE_TEST defined, then this module exports the
111758 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
111759 ** to zero causes the module to use the old syntax. If it is set to 
111760 ** non-zero the new syntax is activated. This is so both syntaxes can
111761 ** be tested using a single build of testfixture.
111762 **
111763 ** The following describes the syntax supported by the fts3 MATCH
111764 ** operator in a similar format to that used by the lemon parser
111765 ** generator. This module does not use actually lemon, it uses a
111766 ** custom parser.
111767 **
111768 **   query ::= andexpr (OR andexpr)*.
111769 **
111770 **   andexpr ::= notexpr (AND? notexpr)*.
111771 **
111772 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
111773 **   notexpr ::= LP query RP.
111774 **
111775 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
111776 **
111777 **   distance_opt ::= .
111778 **   distance_opt ::= / INTEGER.
111779 **
111780 **   phrase ::= TOKEN.
111781 **   phrase ::= COLUMN:TOKEN.
111782 **   phrase ::= "TOKEN TOKEN TOKEN...".
111783 */
111784
111785 #ifdef SQLITE_TEST
111786 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
111787 #else
111788 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
111789 #  define sqlite3_fts3_enable_parentheses 1
111790 # else
111791 #  define sqlite3_fts3_enable_parentheses 0
111792 # endif
111793 #endif
111794
111795 /*
111796 ** Default span for NEAR operators.
111797 */
111798 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
111799
111800
111801 typedef struct ParseContext ParseContext;
111802 struct ParseContext {
111803   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
111804   const char **azCol;                 /* Array of column names for fts3 table */
111805   int nCol;                           /* Number of entries in azCol[] */
111806   int iDefaultCol;                    /* Default column to query */
111807   sqlite3_context *pCtx;              /* Write error message here */
111808   int nNest;                          /* Number of nested brackets */
111809 };
111810
111811 /*
111812 ** This function is equivalent to the standard isspace() function. 
111813 **
111814 ** The standard isspace() can be awkward to use safely, because although it
111815 ** is defined to accept an argument of type int, its behaviour when passed
111816 ** an integer that falls outside of the range of the unsigned char type
111817 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
111818 ** is defined to accept an argument of type char, and always returns 0 for
111819 ** any values that fall outside of the range of the unsigned char type (i.e.
111820 ** negative values).
111821 */
111822 static int fts3isspace(char c){
111823   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
111824 }
111825
111826 /*
111827 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
111828 ** zero the memory before returning a pointer to it. If unsuccessful, 
111829 ** return NULL.
111830 */
111831 static void *fts3MallocZero(int nByte){
111832   void *pRet = sqlite3_malloc(nByte);
111833   if( pRet ) memset(pRet, 0, nByte);
111834   return pRet;
111835 }
111836
111837
111838 /*
111839 ** Extract the next token from buffer z (length n) using the tokenizer
111840 ** and other information (column names etc.) in pParse. Create an Fts3Expr
111841 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
111842 ** single token and set *ppExpr to point to it. If the end of the buffer is
111843 ** reached before a token is found, set *ppExpr to zero. It is the
111844 ** responsibility of the caller to eventually deallocate the allocated 
111845 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
111846 **
111847 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
111848 ** fails.
111849 */
111850 static int getNextToken(
111851   ParseContext *pParse,                   /* fts3 query parse context */
111852   int iCol,                               /* Value for Fts3Phrase.iColumn */
111853   const char *z, int n,                   /* Input string */
111854   Fts3Expr **ppExpr,                      /* OUT: expression */
111855   int *pnConsumed                         /* OUT: Number of bytes consumed */
111856 ){
111857   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
111858   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
111859   int rc;
111860   sqlite3_tokenizer_cursor *pCursor;
111861   Fts3Expr *pRet = 0;
111862   int nConsumed = 0;
111863
111864   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
111865   if( rc==SQLITE_OK ){
111866     const char *zToken;
111867     int nToken, iStart, iEnd, iPosition;
111868     int nByte;                               /* total space to allocate */
111869
111870     pCursor->pTokenizer = pTokenizer;
111871     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
111872
111873     if( rc==SQLITE_OK ){
111874       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
111875       pRet = (Fts3Expr *)fts3MallocZero(nByte);
111876       if( !pRet ){
111877         rc = SQLITE_NOMEM;
111878       }else{
111879         pRet->eType = FTSQUERY_PHRASE;
111880         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
111881         pRet->pPhrase->nToken = 1;
111882         pRet->pPhrase->iColumn = iCol;
111883         pRet->pPhrase->aToken[0].n = nToken;
111884         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
111885         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
111886
111887         if( iEnd<n && z[iEnd]=='*' ){
111888           pRet->pPhrase->aToken[0].isPrefix = 1;
111889           iEnd++;
111890         }
111891         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
111892           pRet->pPhrase->isNot = 1;
111893         }
111894       }
111895       nConsumed = iEnd;
111896     }
111897
111898     pModule->xClose(pCursor);
111899   }
111900   
111901   *pnConsumed = nConsumed;
111902   *ppExpr = pRet;
111903   return rc;
111904 }
111905
111906
111907 /*
111908 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
111909 ** then free the old allocation.
111910 */
111911 static void *fts3ReallocOrFree(void *pOrig, int nNew){
111912   void *pRet = sqlite3_realloc(pOrig, nNew);
111913   if( !pRet ){
111914     sqlite3_free(pOrig);
111915   }
111916   return pRet;
111917 }
111918
111919 /*
111920 ** Buffer zInput, length nInput, contains the contents of a quoted string
111921 ** that appeared as part of an fts3 query expression. Neither quote character
111922 ** is included in the buffer. This function attempts to tokenize the entire
111923 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
111924 ** containing the results.
111925 **
111926 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
111927 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
111928 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
111929 ** to 0.
111930 */
111931 static int getNextString(
111932   ParseContext *pParse,                   /* fts3 query parse context */
111933   const char *zInput, int nInput,         /* Input string */
111934   Fts3Expr **ppExpr                       /* OUT: expression */
111935 ){
111936   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
111937   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
111938   int rc;
111939   Fts3Expr *p = 0;
111940   sqlite3_tokenizer_cursor *pCursor = 0;
111941   char *zTemp = 0;
111942   int nTemp = 0;
111943
111944   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
111945   if( rc==SQLITE_OK ){
111946     int ii;
111947     pCursor->pTokenizer = pTokenizer;
111948     for(ii=0; rc==SQLITE_OK; ii++){
111949       const char *zToken;
111950       int nToken, iBegin, iEnd, iPos;
111951       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
111952       if( rc==SQLITE_OK ){
111953         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
111954         p = fts3ReallocOrFree(p, nByte+ii*sizeof(Fts3PhraseToken));
111955         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
111956         if( !p || !zTemp ){
111957           goto no_mem;
111958         }
111959         if( ii==0 ){
111960           memset(p, 0, nByte);
111961           p->pPhrase = (Fts3Phrase *)&p[1];
111962         }
111963         p->pPhrase = (Fts3Phrase *)&p[1];
111964         memset(&p->pPhrase->aToken[ii], 0, sizeof(Fts3PhraseToken));
111965         p->pPhrase->nToken = ii+1;
111966         p->pPhrase->aToken[ii].n = nToken;
111967         memcpy(&zTemp[nTemp], zToken, nToken);
111968         nTemp += nToken;
111969         if( iEnd<nInput && zInput[iEnd]=='*' ){
111970           p->pPhrase->aToken[ii].isPrefix = 1;
111971         }else{
111972           p->pPhrase->aToken[ii].isPrefix = 0;
111973         }
111974       }
111975     }
111976
111977     pModule->xClose(pCursor);
111978     pCursor = 0;
111979   }
111980
111981   if( rc==SQLITE_DONE ){
111982     int jj;
111983     char *zNew = NULL;
111984     int nNew = 0;
111985     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
111986     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(Fts3PhraseToken);
111987     p = fts3ReallocOrFree(p, nByte + nTemp);
111988     if( !p ){
111989       goto no_mem;
111990     }
111991     if( zTemp ){
111992       zNew = &(((char *)p)[nByte]);
111993       memcpy(zNew, zTemp, nTemp);
111994     }else{
111995       memset(p, 0, nByte+nTemp);
111996     }
111997     p->pPhrase = (Fts3Phrase *)&p[1];
111998     for(jj=0; jj<p->pPhrase->nToken; jj++){
111999       p->pPhrase->aToken[jj].z = &zNew[nNew];
112000       nNew += p->pPhrase->aToken[jj].n;
112001     }
112002     sqlite3_free(zTemp);
112003     p->eType = FTSQUERY_PHRASE;
112004     p->pPhrase->iColumn = pParse->iDefaultCol;
112005     rc = SQLITE_OK;
112006   }
112007
112008   *ppExpr = p;
112009   return rc;
112010 no_mem:
112011
112012   if( pCursor ){
112013     pModule->xClose(pCursor);
112014   }
112015   sqlite3_free(zTemp);
112016   sqlite3_free(p);
112017   *ppExpr = 0;
112018   return SQLITE_NOMEM;
112019 }
112020
112021 /*
112022 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
112023 ** call fts3ExprParse(). So this forward declaration is required.
112024 */
112025 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
112026
112027 /*
112028 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
112029 ** structure, or set to 0 if the end of the input buffer is reached.
112030 **
112031 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
112032 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
112033 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
112034 */
112035 static int getNextNode(
112036   ParseContext *pParse,                   /* fts3 query parse context */
112037   const char *z, int n,                   /* Input string */
112038   Fts3Expr **ppExpr,                      /* OUT: expression */
112039   int *pnConsumed                         /* OUT: Number of bytes consumed */
112040 ){
112041   static const struct Fts3Keyword {
112042     char *z;                              /* Keyword text */
112043     unsigned char n;                      /* Length of the keyword */
112044     unsigned char parenOnly;              /* Only valid in paren mode */
112045     unsigned char eType;                  /* Keyword code */
112046   } aKeyword[] = {
112047     { "OR" ,  2, 0, FTSQUERY_OR   },
112048     { "AND",  3, 1, FTSQUERY_AND  },
112049     { "NOT",  3, 1, FTSQUERY_NOT  },
112050     { "NEAR", 4, 0, FTSQUERY_NEAR }
112051   };
112052   int ii;
112053   int iCol;
112054   int iColLen;
112055   int rc;
112056   Fts3Expr *pRet = 0;
112057
112058   const char *zInput = z;
112059   int nInput = n;
112060
112061   /* Skip over any whitespace before checking for a keyword, an open or
112062   ** close bracket, or a quoted string. 
112063   */
112064   while( nInput>0 && fts3isspace(*zInput) ){
112065     nInput--;
112066     zInput++;
112067   }
112068   if( nInput==0 ){
112069     return SQLITE_DONE;
112070   }
112071
112072   /* See if we are dealing with a keyword. */
112073   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
112074     const struct Fts3Keyword *pKey = &aKeyword[ii];
112075
112076     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
112077       continue;
112078     }
112079
112080     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
112081       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
112082       int nKey = pKey->n;
112083       char cNext;
112084
112085       /* If this is a "NEAR" keyword, check for an explicit nearness. */
112086       if( pKey->eType==FTSQUERY_NEAR ){
112087         assert( nKey==4 );
112088         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
112089           nNear = 0;
112090           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
112091             nNear = nNear * 10 + (zInput[nKey] - '0');
112092           }
112093         }
112094       }
112095
112096       /* At this point this is probably a keyword. But for that to be true,
112097       ** the next byte must contain either whitespace, an open or close
112098       ** parenthesis, a quote character, or EOF. 
112099       */
112100       cNext = zInput[nKey];
112101       if( fts3isspace(cNext) 
112102        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
112103       ){
112104         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
112105         if( !pRet ){
112106           return SQLITE_NOMEM;
112107         }
112108         pRet->eType = pKey->eType;
112109         pRet->nNear = nNear;
112110         *ppExpr = pRet;
112111         *pnConsumed = (int)((zInput - z) + nKey);
112112         return SQLITE_OK;
112113       }
112114
112115       /* Turns out that wasn't a keyword after all. This happens if the
112116       ** user has supplied a token such as "ORacle". Continue.
112117       */
112118     }
112119   }
112120
112121   /* Check for an open bracket. */
112122   if( sqlite3_fts3_enable_parentheses ){
112123     if( *zInput=='(' ){
112124       int nConsumed;
112125       pParse->nNest++;
112126       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
112127       if( rc==SQLITE_OK && !*ppExpr ){
112128         rc = SQLITE_DONE;
112129       }
112130       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
112131       return rc;
112132     }
112133   
112134     /* Check for a close bracket. */
112135     if( *zInput==')' ){
112136       pParse->nNest--;
112137       *pnConsumed = (int)((zInput - z) + 1);
112138       return SQLITE_DONE;
112139     }
112140   }
112141
112142   /* See if we are dealing with a quoted phrase. If this is the case, then
112143   ** search for the closing quote and pass the whole string to getNextString()
112144   ** for processing. This is easy to do, as fts3 has no syntax for escaping
112145   ** a quote character embedded in a string.
112146   */
112147   if( *zInput=='"' ){
112148     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
112149     *pnConsumed = (int)((zInput - z) + ii + 1);
112150     if( ii==nInput ){
112151       return SQLITE_ERROR;
112152     }
112153     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
112154   }
112155
112156
112157   /* If control flows to this point, this must be a regular token, or 
112158   ** the end of the input. Read a regular token using the sqlite3_tokenizer
112159   ** interface. Before doing so, figure out if there is an explicit
112160   ** column specifier for the token. 
112161   **
112162   ** TODO: Strangely, it is not possible to associate a column specifier
112163   ** with a quoted phrase, only with a single token. Not sure if this was
112164   ** an implementation artifact or an intentional decision when fts3 was
112165   ** first implemented. Whichever it was, this module duplicates the 
112166   ** limitation.
112167   */
112168   iCol = pParse->iDefaultCol;
112169   iColLen = 0;
112170   for(ii=0; ii<pParse->nCol; ii++){
112171     const char *zStr = pParse->azCol[ii];
112172     int nStr = (int)strlen(zStr);
112173     if( nInput>nStr && zInput[nStr]==':' 
112174      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
112175     ){
112176       iCol = ii;
112177       iColLen = (int)((zInput - z) + nStr + 1);
112178       break;
112179     }
112180   }
112181   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
112182   *pnConsumed += iColLen;
112183   return rc;
112184 }
112185
112186 /*
112187 ** The argument is an Fts3Expr structure for a binary operator (any type
112188 ** except an FTSQUERY_PHRASE). Return an integer value representing the
112189 ** precedence of the operator. Lower values have a higher precedence (i.e.
112190 ** group more tightly). For example, in the C language, the == operator
112191 ** groups more tightly than ||, and would therefore have a higher precedence.
112192 **
112193 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
112194 ** is defined), the order of the operators in precedence from highest to
112195 ** lowest is:
112196 **
112197 **   NEAR
112198 **   NOT
112199 **   AND (including implicit ANDs)
112200 **   OR
112201 **
112202 ** Note that when using the old query syntax, the OR operator has a higher
112203 ** precedence than the AND operator.
112204 */
112205 static int opPrecedence(Fts3Expr *p){
112206   assert( p->eType!=FTSQUERY_PHRASE );
112207   if( sqlite3_fts3_enable_parentheses ){
112208     return p->eType;
112209   }else if( p->eType==FTSQUERY_NEAR ){
112210     return 1;
112211   }else if( p->eType==FTSQUERY_OR ){
112212     return 2;
112213   }
112214   assert( p->eType==FTSQUERY_AND );
112215   return 3;
112216 }
112217
112218 /*
112219 ** Argument ppHead contains a pointer to the current head of a query 
112220 ** expression tree being parsed. pPrev is the expression node most recently
112221 ** inserted into the tree. This function adds pNew, which is always a binary
112222 ** operator node, into the expression tree based on the relative precedence
112223 ** of pNew and the existing nodes of the tree. This may result in the head
112224 ** of the tree changing, in which case *ppHead is set to the new root node.
112225 */
112226 static void insertBinaryOperator(
112227   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
112228   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
112229   Fts3Expr *pNew           /* New binary node to insert into expression tree */
112230 ){
112231   Fts3Expr *pSplit = pPrev;
112232   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
112233     pSplit = pSplit->pParent;
112234   }
112235
112236   if( pSplit->pParent ){
112237     assert( pSplit->pParent->pRight==pSplit );
112238     pSplit->pParent->pRight = pNew;
112239     pNew->pParent = pSplit->pParent;
112240   }else{
112241     *ppHead = pNew;
112242   }
112243   pNew->pLeft = pSplit;
112244   pSplit->pParent = pNew;
112245 }
112246
112247 /*
112248 ** Parse the fts3 query expression found in buffer z, length n. This function
112249 ** returns either when the end of the buffer is reached or an unmatched 
112250 ** closing bracket - ')' - is encountered.
112251 **
112252 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
112253 ** parsed form of the expression and *pnConsumed is set to the number of
112254 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
112255 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
112256 */
112257 static int fts3ExprParse(
112258   ParseContext *pParse,                   /* fts3 query parse context */
112259   const char *z, int n,                   /* Text of MATCH query */
112260   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
112261   int *pnConsumed                         /* OUT: Number of bytes consumed */
112262 ){
112263   Fts3Expr *pRet = 0;
112264   Fts3Expr *pPrev = 0;
112265   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
112266   int nIn = n;
112267   const char *zIn = z;
112268   int rc = SQLITE_OK;
112269   int isRequirePhrase = 1;
112270
112271   while( rc==SQLITE_OK ){
112272     Fts3Expr *p = 0;
112273     int nByte = 0;
112274     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
112275     if( rc==SQLITE_OK ){
112276       int isPhrase;
112277
112278       if( !sqlite3_fts3_enable_parentheses 
112279        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
112280       ){
112281         /* Create an implicit NOT operator. */
112282         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
112283         if( !pNot ){
112284           sqlite3Fts3ExprFree(p);
112285           rc = SQLITE_NOMEM;
112286           goto exprparse_out;
112287         }
112288         pNot->eType = FTSQUERY_NOT;
112289         pNot->pRight = p;
112290         if( pNotBranch ){
112291           pNot->pLeft = pNotBranch;
112292         }
112293         pNotBranch = pNot;
112294         p = pPrev;
112295       }else{
112296         int eType = p->eType;
112297         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
112298         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
112299
112300         /* The isRequirePhrase variable is set to true if a phrase or
112301         ** an expression contained in parenthesis is required. If a
112302         ** binary operator (AND, OR, NOT or NEAR) is encounted when
112303         ** isRequirePhrase is set, this is a syntax error.
112304         */
112305         if( !isPhrase && isRequirePhrase ){
112306           sqlite3Fts3ExprFree(p);
112307           rc = SQLITE_ERROR;
112308           goto exprparse_out;
112309         }
112310   
112311         if( isPhrase && !isRequirePhrase ){
112312           /* Insert an implicit AND operator. */
112313           Fts3Expr *pAnd;
112314           assert( pRet && pPrev );
112315           pAnd = fts3MallocZero(sizeof(Fts3Expr));
112316           if( !pAnd ){
112317             sqlite3Fts3ExprFree(p);
112318             rc = SQLITE_NOMEM;
112319             goto exprparse_out;
112320           }
112321           pAnd->eType = FTSQUERY_AND;
112322           insertBinaryOperator(&pRet, pPrev, pAnd);
112323           pPrev = pAnd;
112324         }
112325
112326         /* This test catches attempts to make either operand of a NEAR
112327         ** operator something other than a phrase. For example, either of
112328         ** the following:
112329         **
112330         **    (bracketed expression) NEAR phrase
112331         **    phrase NEAR (bracketed expression)
112332         **
112333         ** Return an error in either case.
112334         */
112335         if( pPrev && (
112336             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
112337          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
112338         )){
112339           sqlite3Fts3ExprFree(p);
112340           rc = SQLITE_ERROR;
112341           goto exprparse_out;
112342         }
112343   
112344         if( isPhrase ){
112345           if( pRet ){
112346             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
112347             pPrev->pRight = p;
112348             p->pParent = pPrev;
112349           }else{
112350             pRet = p;
112351           }
112352         }else{
112353           insertBinaryOperator(&pRet, pPrev, p);
112354         }
112355         isRequirePhrase = !isPhrase;
112356       }
112357       assert( nByte>0 );
112358     }
112359     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
112360     nIn -= nByte;
112361     zIn += nByte;
112362     pPrev = p;
112363   }
112364
112365   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
112366     rc = SQLITE_ERROR;
112367   }
112368
112369   if( rc==SQLITE_DONE ){
112370     rc = SQLITE_OK;
112371     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
112372       if( !pRet ){
112373         rc = SQLITE_ERROR;
112374       }else{
112375         Fts3Expr *pIter = pNotBranch;
112376         while( pIter->pLeft ){
112377           pIter = pIter->pLeft;
112378         }
112379         pIter->pLeft = pRet;
112380         pRet = pNotBranch;
112381       }
112382     }
112383   }
112384   *pnConsumed = n - nIn;
112385
112386 exprparse_out:
112387   if( rc!=SQLITE_OK ){
112388     sqlite3Fts3ExprFree(pRet);
112389     sqlite3Fts3ExprFree(pNotBranch);
112390     pRet = 0;
112391   }
112392   *ppExpr = pRet;
112393   return rc;
112394 }
112395
112396 /*
112397 ** Parameters z and n contain a pointer to and length of a buffer containing
112398 ** an fts3 query expression, respectively. This function attempts to parse the
112399 ** query expression and create a tree of Fts3Expr structures representing the
112400 ** parsed expression. If successful, *ppExpr is set to point to the head
112401 ** of the parsed expression tree and SQLITE_OK is returned. If an error
112402 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
112403 ** error) is returned and *ppExpr is set to 0.
112404 **
112405 ** If parameter n is a negative number, then z is assumed to point to a
112406 ** nul-terminated string and the length is determined using strlen().
112407 **
112408 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
112409 ** use to normalize query tokens while parsing the expression. The azCol[]
112410 ** array, which is assumed to contain nCol entries, should contain the names
112411 ** of each column in the target fts3 table, in order from left to right. 
112412 ** Column names must be nul-terminated strings.
112413 **
112414 ** The iDefaultCol parameter should be passed the index of the table column
112415 ** that appears on the left-hand-side of the MATCH operator (the default
112416 ** column to match against for tokens for which a column name is not explicitly
112417 ** specified as part of the query string), or -1 if tokens may by default
112418 ** match any table column.
112419 */
112420 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
112421   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
112422   char **azCol,                       /* Array of column names for fts3 table */
112423   int nCol,                           /* Number of entries in azCol[] */
112424   int iDefaultCol,                    /* Default column to query */
112425   const char *z, int n,               /* Text of MATCH query */
112426   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
112427 ){
112428   int nParsed;
112429   int rc;
112430   ParseContext sParse;
112431   sParse.pTokenizer = pTokenizer;
112432   sParse.azCol = (const char **)azCol;
112433   sParse.nCol = nCol;
112434   sParse.iDefaultCol = iDefaultCol;
112435   sParse.nNest = 0;
112436   if( z==0 ){
112437     *ppExpr = 0;
112438     return SQLITE_OK;
112439   }
112440   if( n<0 ){
112441     n = (int)strlen(z);
112442   }
112443   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
112444
112445   /* Check for mismatched parenthesis */
112446   if( rc==SQLITE_OK && sParse.nNest ){
112447     rc = SQLITE_ERROR;
112448     sqlite3Fts3ExprFree(*ppExpr);
112449     *ppExpr = 0;
112450   }
112451
112452   return rc;
112453 }
112454
112455 /*
112456 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
112457 */
112458 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
112459   if( p ){
112460     sqlite3Fts3ExprFree(p->pLeft);
112461     sqlite3Fts3ExprFree(p->pRight);
112462     sqlite3_free(p->aDoclist);
112463     sqlite3_free(p);
112464   }
112465 }
112466
112467 /****************************************************************************
112468 *****************************************************************************
112469 ** Everything after this point is just test code.
112470 */
112471
112472 #ifdef SQLITE_TEST
112473
112474
112475 /*
112476 ** Function to query the hash-table of tokenizers (see README.tokenizers).
112477 */
112478 static int queryTestTokenizer(
112479   sqlite3 *db, 
112480   const char *zName,  
112481   const sqlite3_tokenizer_module **pp
112482 ){
112483   int rc;
112484   sqlite3_stmt *pStmt;
112485   const char zSql[] = "SELECT fts3_tokenizer(?)";
112486
112487   *pp = 0;
112488   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
112489   if( rc!=SQLITE_OK ){
112490     return rc;
112491   }
112492
112493   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
112494   if( SQLITE_ROW==sqlite3_step(pStmt) ){
112495     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
112496       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
112497     }
112498   }
112499
112500   return sqlite3_finalize(pStmt);
112501 }
112502
112503 /*
112504 ** Return a pointer to a buffer containing a text representation of the
112505 ** expression passed as the first argument. The buffer is obtained from
112506 ** sqlite3_malloc(). It is the responsibility of the caller to use 
112507 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
112508 ** NULL is returned.
112509 **
112510 ** If the second argument is not NULL, then its contents are prepended to 
112511 ** the returned expression text and then freed using sqlite3_free().
112512 */
112513 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
112514   switch( pExpr->eType ){
112515     case FTSQUERY_PHRASE: {
112516       Fts3Phrase *pPhrase = pExpr->pPhrase;
112517       int i;
112518       zBuf = sqlite3_mprintf(
112519           "%zPHRASE %d %d", zBuf, pPhrase->iColumn, pPhrase->isNot);
112520       for(i=0; zBuf && i<pPhrase->nToken; i++){
112521         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
112522             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
112523             (pPhrase->aToken[i].isPrefix?"+":"")
112524         );
112525       }
112526       return zBuf;
112527     }
112528
112529     case FTSQUERY_NEAR:
112530       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
112531       break;
112532     case FTSQUERY_NOT:
112533       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
112534       break;
112535     case FTSQUERY_AND:
112536       zBuf = sqlite3_mprintf("%zAND ", zBuf);
112537       break;
112538     case FTSQUERY_OR:
112539       zBuf = sqlite3_mprintf("%zOR ", zBuf);
112540       break;
112541   }
112542
112543   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
112544   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
112545   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
112546
112547   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
112548   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
112549
112550   return zBuf;
112551 }
112552
112553 /*
112554 ** This is the implementation of a scalar SQL function used to test the 
112555 ** expression parser. It should be called as follows:
112556 **
112557 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
112558 **
112559 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
112560 ** to parse the query expression (see README.tokenizers). The second argument
112561 ** is the query expression to parse. Each subsequent argument is the name
112562 ** of a column of the fts3 table that the query expression may refer to.
112563 ** For example:
112564 **
112565 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
112566 */
112567 static void fts3ExprTest(
112568   sqlite3_context *context,
112569   int argc,
112570   sqlite3_value **argv
112571 ){
112572   sqlite3_tokenizer_module const *pModule = 0;
112573   sqlite3_tokenizer *pTokenizer = 0;
112574   int rc;
112575   char **azCol = 0;
112576   const char *zExpr;
112577   int nExpr;
112578   int nCol;
112579   int ii;
112580   Fts3Expr *pExpr;
112581   char *zBuf = 0;
112582   sqlite3 *db = sqlite3_context_db_handle(context);
112583
112584   if( argc<3 ){
112585     sqlite3_result_error(context, 
112586         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
112587     );
112588     return;
112589   }
112590
112591   rc = queryTestTokenizer(db,
112592                           (const char *)sqlite3_value_text(argv[0]), &pModule);
112593   if( rc==SQLITE_NOMEM ){
112594     sqlite3_result_error_nomem(context);
112595     goto exprtest_out;
112596   }else if( !pModule ){
112597     sqlite3_result_error(context, "No such tokenizer module", -1);
112598     goto exprtest_out;
112599   }
112600
112601   rc = pModule->xCreate(0, 0, &pTokenizer);
112602   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
112603   if( rc==SQLITE_NOMEM ){
112604     sqlite3_result_error_nomem(context);
112605     goto exprtest_out;
112606   }
112607   pTokenizer->pModule = pModule;
112608
112609   zExpr = (const char *)sqlite3_value_text(argv[1]);
112610   nExpr = sqlite3_value_bytes(argv[1]);
112611   nCol = argc-2;
112612   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
112613   if( !azCol ){
112614     sqlite3_result_error_nomem(context);
112615     goto exprtest_out;
112616   }
112617   for(ii=0; ii<nCol; ii++){
112618     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
112619   }
112620
112621   rc = sqlite3Fts3ExprParse(
112622       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
112623   );
112624   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
112625     sqlite3_result_error(context, "Error parsing expression", -1);
112626   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
112627     sqlite3_result_error_nomem(context);
112628   }else{
112629     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
112630     sqlite3_free(zBuf);
112631   }
112632
112633   sqlite3Fts3ExprFree(pExpr);
112634
112635 exprtest_out:
112636   if( pModule && pTokenizer ){
112637     rc = pModule->xDestroy(pTokenizer);
112638   }
112639   sqlite3_free(azCol);
112640 }
112641
112642 /*
112643 ** Register the query expression parser test function fts3_exprtest() 
112644 ** with database connection db. 
112645 */
112646 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
112647   return sqlite3_create_function(
112648       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
112649   );
112650 }
112651
112652 #endif
112653 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
112654
112655 /************** End of fts3_expr.c *******************************************/
112656 /************** Begin file fts3_hash.c ***************************************/
112657 /*
112658 ** 2001 September 22
112659 **
112660 ** The author disclaims copyright to this source code.  In place of
112661 ** a legal notice, here is a blessing:
112662 **
112663 **    May you do good and not evil.
112664 **    May you find forgiveness for yourself and forgive others.
112665 **    May you share freely, never taking more than you give.
112666 **
112667 *************************************************************************
112668 ** This is the implementation of generic hash-tables used in SQLite.
112669 ** We've modified it slightly to serve as a standalone hash table
112670 ** implementation for the full-text indexing module.
112671 */
112672
112673 /*
112674 ** The code in this file is only compiled if:
112675 **
112676 **     * The FTS3 module is being built as an extension
112677 **       (in which case SQLITE_CORE is not defined), or
112678 **
112679 **     * The FTS3 module is being built into the core of
112680 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
112681 */
112682 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
112683
112684
112685
112686 /*
112687 ** Malloc and Free functions
112688 */
112689 static void *fts3HashMalloc(int n){
112690   void *p = sqlite3_malloc(n);
112691   if( p ){
112692     memset(p, 0, n);
112693   }
112694   return p;
112695 }
112696 static void fts3HashFree(void *p){
112697   sqlite3_free(p);
112698 }
112699
112700 /* Turn bulk memory into a hash table object by initializing the
112701 ** fields of the Hash structure.
112702 **
112703 ** "pNew" is a pointer to the hash table that is to be initialized.
112704 ** keyClass is one of the constants 
112705 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
112706 ** determines what kind of key the hash table will use.  "copyKey" is
112707 ** true if the hash table should make its own private copy of keys and
112708 ** false if it should just use the supplied pointer.
112709 */
112710 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
112711   assert( pNew!=0 );
112712   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
112713   pNew->keyClass = keyClass;
112714   pNew->copyKey = copyKey;
112715   pNew->first = 0;
112716   pNew->count = 0;
112717   pNew->htsize = 0;
112718   pNew->ht = 0;
112719 }
112720
112721 /* Remove all entries from a hash table.  Reclaim all memory.
112722 ** Call this routine to delete a hash table or to reset a hash table
112723 ** to the empty state.
112724 */
112725 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
112726   Fts3HashElem *elem;         /* For looping over all elements of the table */
112727
112728   assert( pH!=0 );
112729   elem = pH->first;
112730   pH->first = 0;
112731   fts3HashFree(pH->ht);
112732   pH->ht = 0;
112733   pH->htsize = 0;
112734   while( elem ){
112735     Fts3HashElem *next_elem = elem->next;
112736     if( pH->copyKey && elem->pKey ){
112737       fts3HashFree(elem->pKey);
112738     }
112739     fts3HashFree(elem);
112740     elem = next_elem;
112741   }
112742   pH->count = 0;
112743 }
112744
112745 /*
112746 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
112747 */
112748 static int fts3StrHash(const void *pKey, int nKey){
112749   const char *z = (const char *)pKey;
112750   int h = 0;
112751   if( nKey<=0 ) nKey = (int) strlen(z);
112752   while( nKey > 0  ){
112753     h = (h<<3) ^ h ^ *z++;
112754     nKey--;
112755   }
112756   return h & 0x7fffffff;
112757 }
112758 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
112759   if( n1!=n2 ) return 1;
112760   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
112761 }
112762
112763 /*
112764 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
112765 */
112766 static int fts3BinHash(const void *pKey, int nKey){
112767   int h = 0;
112768   const char *z = (const char *)pKey;
112769   while( nKey-- > 0 ){
112770     h = (h<<3) ^ h ^ *(z++);
112771   }
112772   return h & 0x7fffffff;
112773 }
112774 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
112775   if( n1!=n2 ) return 1;
112776   return memcmp(pKey1,pKey2,n1);
112777 }
112778
112779 /*
112780 ** Return a pointer to the appropriate hash function given the key class.
112781 **
112782 ** The C syntax in this function definition may be unfamilar to some 
112783 ** programmers, so we provide the following additional explanation:
112784 **
112785 ** The name of the function is "ftsHashFunction".  The function takes a
112786 ** single parameter "keyClass".  The return value of ftsHashFunction()
112787 ** is a pointer to another function.  Specifically, the return value
112788 ** of ftsHashFunction() is a pointer to a function that takes two parameters
112789 ** with types "const void*" and "int" and returns an "int".
112790 */
112791 static int (*ftsHashFunction(int keyClass))(const void*,int){
112792   if( keyClass==FTS3_HASH_STRING ){
112793     return &fts3StrHash;
112794   }else{
112795     assert( keyClass==FTS3_HASH_BINARY );
112796     return &fts3BinHash;
112797   }
112798 }
112799
112800 /*
112801 ** Return a pointer to the appropriate hash function given the key class.
112802 **
112803 ** For help in interpreted the obscure C code in the function definition,
112804 ** see the header comment on the previous function.
112805 */
112806 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
112807   if( keyClass==FTS3_HASH_STRING ){
112808     return &fts3StrCompare;
112809   }else{
112810     assert( keyClass==FTS3_HASH_BINARY );
112811     return &fts3BinCompare;
112812   }
112813 }
112814
112815 /* Link an element into the hash table
112816 */
112817 static void fts3HashInsertElement(
112818   Fts3Hash *pH,            /* The complete hash table */
112819   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
112820   Fts3HashElem *pNew       /* The element to be inserted */
112821 ){
112822   Fts3HashElem *pHead;     /* First element already in pEntry */
112823   pHead = pEntry->chain;
112824   if( pHead ){
112825     pNew->next = pHead;
112826     pNew->prev = pHead->prev;
112827     if( pHead->prev ){ pHead->prev->next = pNew; }
112828     else             { pH->first = pNew; }
112829     pHead->prev = pNew;
112830   }else{
112831     pNew->next = pH->first;
112832     if( pH->first ){ pH->first->prev = pNew; }
112833     pNew->prev = 0;
112834     pH->first = pNew;
112835   }
112836   pEntry->count++;
112837   pEntry->chain = pNew;
112838 }
112839
112840
112841 /* Resize the hash table so that it cantains "new_size" buckets.
112842 ** "new_size" must be a power of 2.  The hash table might fail 
112843 ** to resize if sqliteMalloc() fails.
112844 **
112845 ** Return non-zero if a memory allocation error occurs.
112846 */
112847 static int fts3Rehash(Fts3Hash *pH, int new_size){
112848   struct _fts3ht *new_ht;          /* The new hash table */
112849   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
112850   int (*xHash)(const void*,int);   /* The hash function */
112851
112852   assert( (new_size & (new_size-1))==0 );
112853   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
112854   if( new_ht==0 ) return 1;
112855   fts3HashFree(pH->ht);
112856   pH->ht = new_ht;
112857   pH->htsize = new_size;
112858   xHash = ftsHashFunction(pH->keyClass);
112859   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
112860     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
112861     next_elem = elem->next;
112862     fts3HashInsertElement(pH, &new_ht[h], elem);
112863   }
112864   return 0;
112865 }
112866
112867 /* This function (for internal use only) locates an element in an
112868 ** hash table that matches the given key.  The hash for this key has
112869 ** already been computed and is passed as the 4th parameter.
112870 */
112871 static Fts3HashElem *fts3FindElementByHash(
112872   const Fts3Hash *pH, /* The pH to be searched */
112873   const void *pKey,   /* The key we are searching for */
112874   int nKey,
112875   int h               /* The hash for this key. */
112876 ){
112877   Fts3HashElem *elem;            /* Used to loop thru the element list */
112878   int count;                     /* Number of elements left to test */
112879   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
112880
112881   if( pH->ht ){
112882     struct _fts3ht *pEntry = &pH->ht[h];
112883     elem = pEntry->chain;
112884     count = pEntry->count;
112885     xCompare = ftsCompareFunction(pH->keyClass);
112886     while( count-- && elem ){
112887       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
112888         return elem;
112889       }
112890       elem = elem->next;
112891     }
112892   }
112893   return 0;
112894 }
112895
112896 /* Remove a single entry from the hash table given a pointer to that
112897 ** element and a hash on the element's key.
112898 */
112899 static void fts3RemoveElementByHash(
112900   Fts3Hash *pH,         /* The pH containing "elem" */
112901   Fts3HashElem* elem,   /* The element to be removed from the pH */
112902   int h                 /* Hash value for the element */
112903 ){
112904   struct _fts3ht *pEntry;
112905   if( elem->prev ){
112906     elem->prev->next = elem->next; 
112907   }else{
112908     pH->first = elem->next;
112909   }
112910   if( elem->next ){
112911     elem->next->prev = elem->prev;
112912   }
112913   pEntry = &pH->ht[h];
112914   if( pEntry->chain==elem ){
112915     pEntry->chain = elem->next;
112916   }
112917   pEntry->count--;
112918   if( pEntry->count<=0 ){
112919     pEntry->chain = 0;
112920   }
112921   if( pH->copyKey && elem->pKey ){
112922     fts3HashFree(elem->pKey);
112923   }
112924   fts3HashFree( elem );
112925   pH->count--;
112926   if( pH->count<=0 ){
112927     assert( pH->first==0 );
112928     assert( pH->count==0 );
112929     fts3HashClear(pH);
112930   }
112931 }
112932
112933 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
112934   const Fts3Hash *pH, 
112935   const void *pKey, 
112936   int nKey
112937 ){
112938   int h;                          /* A hash on key */
112939   int (*xHash)(const void*,int);  /* The hash function */
112940
112941   if( pH==0 || pH->ht==0 ) return 0;
112942   xHash = ftsHashFunction(pH->keyClass);
112943   assert( xHash!=0 );
112944   h = (*xHash)(pKey,nKey);
112945   assert( (pH->htsize & (pH->htsize-1))==0 );
112946   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
112947 }
112948
112949 /* 
112950 ** Attempt to locate an element of the hash table pH with a key
112951 ** that matches pKey,nKey.  Return the data for this element if it is
112952 ** found, or NULL if there is no match.
112953 */
112954 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
112955   Fts3HashElem *pElem;            /* The element that matches key (if any) */
112956
112957   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
112958   return pElem ? pElem->data : 0;
112959 }
112960
112961 /* Insert an element into the hash table pH.  The key is pKey,nKey
112962 ** and the data is "data".
112963 **
112964 ** If no element exists with a matching key, then a new
112965 ** element is created.  A copy of the key is made if the copyKey
112966 ** flag is set.  NULL is returned.
112967 **
112968 ** If another element already exists with the same key, then the
112969 ** new data replaces the old data and the old data is returned.
112970 ** The key is not copied in this instance.  If a malloc fails, then
112971 ** the new data is returned and the hash table is unchanged.
112972 **
112973 ** If the "data" parameter to this function is NULL, then the
112974 ** element corresponding to "key" is removed from the hash table.
112975 */
112976 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
112977   Fts3Hash *pH,        /* The hash table to insert into */
112978   const void *pKey,    /* The key */
112979   int nKey,            /* Number of bytes in the key */
112980   void *data           /* The data */
112981 ){
112982   int hraw;                 /* Raw hash value of the key */
112983   int h;                    /* the hash of the key modulo hash table size */
112984   Fts3HashElem *elem;       /* Used to loop thru the element list */
112985   Fts3HashElem *new_elem;   /* New element added to the pH */
112986   int (*xHash)(const void*,int);  /* The hash function */
112987
112988   assert( pH!=0 );
112989   xHash = ftsHashFunction(pH->keyClass);
112990   assert( xHash!=0 );
112991   hraw = (*xHash)(pKey, nKey);
112992   assert( (pH->htsize & (pH->htsize-1))==0 );
112993   h = hraw & (pH->htsize-1);
112994   elem = fts3FindElementByHash(pH,pKey,nKey,h);
112995   if( elem ){
112996     void *old_data = elem->data;
112997     if( data==0 ){
112998       fts3RemoveElementByHash(pH,elem,h);
112999     }else{
113000       elem->data = data;
113001     }
113002     return old_data;
113003   }
113004   if( data==0 ) return 0;
113005   if( (pH->htsize==0 && fts3Rehash(pH,8))
113006    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
113007   ){
113008     pH->count = 0;
113009     return data;
113010   }
113011   assert( pH->htsize>0 );
113012   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
113013   if( new_elem==0 ) return data;
113014   if( pH->copyKey && pKey!=0 ){
113015     new_elem->pKey = fts3HashMalloc( nKey );
113016     if( new_elem->pKey==0 ){
113017       fts3HashFree(new_elem);
113018       return data;
113019     }
113020     memcpy((void*)new_elem->pKey, pKey, nKey);
113021   }else{
113022     new_elem->pKey = (void*)pKey;
113023   }
113024   new_elem->nKey = nKey;
113025   pH->count++;
113026   assert( pH->htsize>0 );
113027   assert( (pH->htsize & (pH->htsize-1))==0 );
113028   h = hraw & (pH->htsize-1);
113029   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
113030   new_elem->data = data;
113031   return 0;
113032 }
113033
113034 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
113035
113036 /************** End of fts3_hash.c *******************************************/
113037 /************** Begin file fts3_porter.c *************************************/
113038 /*
113039 ** 2006 September 30
113040 **
113041 ** The author disclaims copyright to this source code.  In place of
113042 ** a legal notice, here is a blessing:
113043 **
113044 **    May you do good and not evil.
113045 **    May you find forgiveness for yourself and forgive others.
113046 **    May you share freely, never taking more than you give.
113047 **
113048 *************************************************************************
113049 ** Implementation of the full-text-search tokenizer that implements
113050 ** a Porter stemmer.
113051 */
113052
113053 /*
113054 ** The code in this file is only compiled if:
113055 **
113056 **     * The FTS3 module is being built as an extension
113057 **       (in which case SQLITE_CORE is not defined), or
113058 **
113059 **     * The FTS3 module is being built into the core of
113060 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
113061 */
113062 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
113063
113064
113065
113066
113067 /*
113068 ** Class derived from sqlite3_tokenizer
113069 */
113070 typedef struct porter_tokenizer {
113071   sqlite3_tokenizer base;      /* Base class */
113072 } porter_tokenizer;
113073
113074 /*
113075 ** Class derived from sqlit3_tokenizer_cursor
113076 */
113077 typedef struct porter_tokenizer_cursor {
113078   sqlite3_tokenizer_cursor base;
113079   const char *zInput;          /* input we are tokenizing */
113080   int nInput;                  /* size of the input */
113081   int iOffset;                 /* current position in zInput */
113082   int iToken;                  /* index of next token to be returned */
113083   char *zToken;                /* storage for current token */
113084   int nAllocated;              /* space allocated to zToken buffer */
113085 } porter_tokenizer_cursor;
113086
113087
113088 /*
113089 ** Create a new tokenizer instance.
113090 */
113091 static int porterCreate(
113092   int argc, const char * const *argv,
113093   sqlite3_tokenizer **ppTokenizer
113094 ){
113095   porter_tokenizer *t;
113096
113097   UNUSED_PARAMETER(argc);
113098   UNUSED_PARAMETER(argv);
113099
113100   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
113101   if( t==NULL ) return SQLITE_NOMEM;
113102   memset(t, 0, sizeof(*t));
113103   *ppTokenizer = &t->base;
113104   return SQLITE_OK;
113105 }
113106
113107 /*
113108 ** Destroy a tokenizer
113109 */
113110 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
113111   sqlite3_free(pTokenizer);
113112   return SQLITE_OK;
113113 }
113114
113115 /*
113116 ** Prepare to begin tokenizing a particular string.  The input
113117 ** string to be tokenized is zInput[0..nInput-1].  A cursor
113118 ** used to incrementally tokenize this string is returned in 
113119 ** *ppCursor.
113120 */
113121 static int porterOpen(
113122   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
113123   const char *zInput, int nInput,        /* String to be tokenized */
113124   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
113125 ){
113126   porter_tokenizer_cursor *c;
113127
113128   UNUSED_PARAMETER(pTokenizer);
113129
113130   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
113131   if( c==NULL ) return SQLITE_NOMEM;
113132
113133   c->zInput = zInput;
113134   if( zInput==0 ){
113135     c->nInput = 0;
113136   }else if( nInput<0 ){
113137     c->nInput = (int)strlen(zInput);
113138   }else{
113139     c->nInput = nInput;
113140   }
113141   c->iOffset = 0;                 /* start tokenizing at the beginning */
113142   c->iToken = 0;
113143   c->zToken = NULL;               /* no space allocated, yet. */
113144   c->nAllocated = 0;
113145
113146   *ppCursor = &c->base;
113147   return SQLITE_OK;
113148 }
113149
113150 /*
113151 ** Close a tokenization cursor previously opened by a call to
113152 ** porterOpen() above.
113153 */
113154 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
113155   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
113156   sqlite3_free(c->zToken);
113157   sqlite3_free(c);
113158   return SQLITE_OK;
113159 }
113160 /*
113161 ** Vowel or consonant
113162 */
113163 static const char cType[] = {
113164    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
113165    1, 1, 1, 2, 1
113166 };
113167
113168 /*
113169 ** isConsonant() and isVowel() determine if their first character in
113170 ** the string they point to is a consonant or a vowel, according
113171 ** to Porter ruls.  
113172 **
113173 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
113174 ** 'Y' is a consonant unless it follows another consonant,
113175 ** in which case it is a vowel.
113176 **
113177 ** In these routine, the letters are in reverse order.  So the 'y' rule
113178 ** is that 'y' is a consonant unless it is followed by another
113179 ** consonent.
113180 */
113181 static int isVowel(const char*);
113182 static int isConsonant(const char *z){
113183   int j;
113184   char x = *z;
113185   if( x==0 ) return 0;
113186   assert( x>='a' && x<='z' );
113187   j = cType[x-'a'];
113188   if( j<2 ) return j;
113189   return z[1]==0 || isVowel(z + 1);
113190 }
113191 static int isVowel(const char *z){
113192   int j;
113193   char x = *z;
113194   if( x==0 ) return 0;
113195   assert( x>='a' && x<='z' );
113196   j = cType[x-'a'];
113197   if( j<2 ) return 1-j;
113198   return isConsonant(z + 1);
113199 }
113200
113201 /*
113202 ** Let any sequence of one or more vowels be represented by V and let
113203 ** C be sequence of one or more consonants.  Then every word can be
113204 ** represented as:
113205 **
113206 **           [C] (VC){m} [V]
113207 **
113208 ** In prose:  A word is an optional consonant followed by zero or
113209 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
113210 ** number of vowel consonant pairs.  This routine computes the value
113211 ** of m for the first i bytes of a word.
113212 **
113213 ** Return true if the m-value for z is 1 or more.  In other words,
113214 ** return true if z contains at least one vowel that is followed
113215 ** by a consonant.
113216 **
113217 ** In this routine z[] is in reverse order.  So we are really looking
113218 ** for an instance of of a consonant followed by a vowel.
113219 */
113220 static int m_gt_0(const char *z){
113221   while( isVowel(z) ){ z++; }
113222   if( *z==0 ) return 0;
113223   while( isConsonant(z) ){ z++; }
113224   return *z!=0;
113225 }
113226
113227 /* Like mgt0 above except we are looking for a value of m which is
113228 ** exactly 1
113229 */
113230 static int m_eq_1(const char *z){
113231   while( isVowel(z) ){ z++; }
113232   if( *z==0 ) return 0;
113233   while( isConsonant(z) ){ z++; }
113234   if( *z==0 ) return 0;
113235   while( isVowel(z) ){ z++; }
113236   if( *z==0 ) return 1;
113237   while( isConsonant(z) ){ z++; }
113238   return *z==0;
113239 }
113240
113241 /* Like mgt0 above except we are looking for a value of m>1 instead
113242 ** or m>0
113243 */
113244 static int m_gt_1(const char *z){
113245   while( isVowel(z) ){ z++; }
113246   if( *z==0 ) return 0;
113247   while( isConsonant(z) ){ z++; }
113248   if( *z==0 ) return 0;
113249   while( isVowel(z) ){ z++; }
113250   if( *z==0 ) return 0;
113251   while( isConsonant(z) ){ z++; }
113252   return *z!=0;
113253 }
113254
113255 /*
113256 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
113257 */
113258 static int hasVowel(const char *z){
113259   while( isConsonant(z) ){ z++; }
113260   return *z!=0;
113261 }
113262
113263 /*
113264 ** Return TRUE if the word ends in a double consonant.
113265 **
113266 ** The text is reversed here. So we are really looking at
113267 ** the first two characters of z[].
113268 */
113269 static int doubleConsonant(const char *z){
113270   return isConsonant(z) && z[0]==z[1];
113271 }
113272
113273 /*
113274 ** Return TRUE if the word ends with three letters which
113275 ** are consonant-vowel-consonent and where the final consonant
113276 ** is not 'w', 'x', or 'y'.
113277 **
113278 ** The word is reversed here.  So we are really checking the
113279 ** first three letters and the first one cannot be in [wxy].
113280 */
113281 static int star_oh(const char *z){
113282   return
113283     isConsonant(z) &&
113284     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
113285     isVowel(z+1) &&
113286     isConsonant(z+2);
113287 }
113288
113289 /*
113290 ** If the word ends with zFrom and xCond() is true for the stem
113291 ** of the word that preceeds the zFrom ending, then change the 
113292 ** ending to zTo.
113293 **
113294 ** The input word *pz and zFrom are both in reverse order.  zTo
113295 ** is in normal order. 
113296 **
113297 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
113298 ** match.  Not that TRUE is returned even if xCond() fails and
113299 ** no substitution occurs.
113300 */
113301 static int stem(
113302   char **pz,             /* The word being stemmed (Reversed) */
113303   const char *zFrom,     /* If the ending matches this... (Reversed) */
113304   const char *zTo,       /* ... change the ending to this (not reversed) */
113305   int (*xCond)(const char*)   /* Condition that must be true */
113306 ){
113307   char *z = *pz;
113308   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
113309   if( *zFrom!=0 ) return 0;
113310   if( xCond && !xCond(z) ) return 1;
113311   while( *zTo ){
113312     *(--z) = *(zTo++);
113313   }
113314   *pz = z;
113315   return 1;
113316 }
113317
113318 /*
113319 ** This is the fallback stemmer used when the porter stemmer is
113320 ** inappropriate.  The input word is copied into the output with
113321 ** US-ASCII case folding.  If the input word is too long (more
113322 ** than 20 bytes if it contains no digits or more than 6 bytes if
113323 ** it contains digits) then word is truncated to 20 or 6 bytes
113324 ** by taking 10 or 3 bytes from the beginning and end.
113325 */
113326 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
113327   int i, mx, j;
113328   int hasDigit = 0;
113329   for(i=0; i<nIn; i++){
113330     char c = zIn[i];
113331     if( c>='A' && c<='Z' ){
113332       zOut[i] = c - 'A' + 'a';
113333     }else{
113334       if( c>='0' && c<='9' ) hasDigit = 1;
113335       zOut[i] = c;
113336     }
113337   }
113338   mx = hasDigit ? 3 : 10;
113339   if( nIn>mx*2 ){
113340     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
113341       zOut[j] = zOut[i];
113342     }
113343     i = j;
113344   }
113345   zOut[i] = 0;
113346   *pnOut = i;
113347 }
113348
113349
113350 /*
113351 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
113352 ** zOut is at least big enough to hold nIn bytes.  Write the actual
113353 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
113354 **
113355 ** Any upper-case characters in the US-ASCII character set ([A-Z])
113356 ** are converted to lower case.  Upper-case UTF characters are
113357 ** unchanged.
113358 **
113359 ** Words that are longer than about 20 bytes are stemmed by retaining
113360 ** a few bytes from the beginning and the end of the word.  If the
113361 ** word contains digits, 3 bytes are taken from the beginning and
113362 ** 3 bytes from the end.  For long words without digits, 10 bytes
113363 ** are taken from each end.  US-ASCII case folding still applies.
113364 ** 
113365 ** If the input word contains not digits but does characters not 
113366 ** in [a-zA-Z] then no stemming is attempted and this routine just 
113367 ** copies the input into the input into the output with US-ASCII
113368 ** case folding.
113369 **
113370 ** Stemming never increases the length of the word.  So there is
113371 ** no chance of overflowing the zOut buffer.
113372 */
113373 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
113374   int i, j;
113375   char zReverse[28];
113376   char *z, *z2;
113377   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
113378     /* The word is too big or too small for the porter stemmer.
113379     ** Fallback to the copy stemmer */
113380     copy_stemmer(zIn, nIn, zOut, pnOut);
113381     return;
113382   }
113383   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
113384     char c = zIn[i];
113385     if( c>='A' && c<='Z' ){
113386       zReverse[j] = c + 'a' - 'A';
113387     }else if( c>='a' && c<='z' ){
113388       zReverse[j] = c;
113389     }else{
113390       /* The use of a character not in [a-zA-Z] means that we fallback
113391       ** to the copy stemmer */
113392       copy_stemmer(zIn, nIn, zOut, pnOut);
113393       return;
113394     }
113395   }
113396   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
113397   z = &zReverse[j+1];
113398
113399
113400   /* Step 1a */
113401   if( z[0]=='s' ){
113402     if(
113403      !stem(&z, "sess", "ss", 0) &&
113404      !stem(&z, "sei", "i", 0)  &&
113405      !stem(&z, "ss", "ss", 0)
113406     ){
113407       z++;
113408     }
113409   }
113410
113411   /* Step 1b */  
113412   z2 = z;
113413   if( stem(&z, "dee", "ee", m_gt_0) ){
113414     /* Do nothing.  The work was all in the test */
113415   }else if( 
113416      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
113417       && z!=z2
113418   ){
113419      if( stem(&z, "ta", "ate", 0) ||
113420          stem(&z, "lb", "ble", 0) ||
113421          stem(&z, "zi", "ize", 0) ){
113422        /* Do nothing.  The work was all in the test */
113423      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
113424        z++;
113425      }else if( m_eq_1(z) && star_oh(z) ){
113426        *(--z) = 'e';
113427      }
113428   }
113429
113430   /* Step 1c */
113431   if( z[0]=='y' && hasVowel(z+1) ){
113432     z[0] = 'i';
113433   }
113434
113435   /* Step 2 */
113436   switch( z[1] ){
113437    case 'a':
113438      stem(&z, "lanoita", "ate", m_gt_0) ||
113439      stem(&z, "lanoit", "tion", m_gt_0);
113440      break;
113441    case 'c':
113442      stem(&z, "icne", "ence", m_gt_0) ||
113443      stem(&z, "icna", "ance", m_gt_0);
113444      break;
113445    case 'e':
113446      stem(&z, "rezi", "ize", m_gt_0);
113447      break;
113448    case 'g':
113449      stem(&z, "igol", "log", m_gt_0);
113450      break;
113451    case 'l':
113452      stem(&z, "ilb", "ble", m_gt_0) ||
113453      stem(&z, "illa", "al", m_gt_0) ||
113454      stem(&z, "iltne", "ent", m_gt_0) ||
113455      stem(&z, "ile", "e", m_gt_0) ||
113456      stem(&z, "ilsuo", "ous", m_gt_0);
113457      break;
113458    case 'o':
113459      stem(&z, "noitazi", "ize", m_gt_0) ||
113460      stem(&z, "noita", "ate", m_gt_0) ||
113461      stem(&z, "rota", "ate", m_gt_0);
113462      break;
113463    case 's':
113464      stem(&z, "msila", "al", m_gt_0) ||
113465      stem(&z, "ssenevi", "ive", m_gt_0) ||
113466      stem(&z, "ssenluf", "ful", m_gt_0) ||
113467      stem(&z, "ssensuo", "ous", m_gt_0);
113468      break;
113469    case 't':
113470      stem(&z, "itila", "al", m_gt_0) ||
113471      stem(&z, "itivi", "ive", m_gt_0) ||
113472      stem(&z, "itilib", "ble", m_gt_0);
113473      break;
113474   }
113475
113476   /* Step 3 */
113477   switch( z[0] ){
113478    case 'e':
113479      stem(&z, "etaci", "ic", m_gt_0) ||
113480      stem(&z, "evita", "", m_gt_0)   ||
113481      stem(&z, "ezila", "al", m_gt_0);
113482      break;
113483    case 'i':
113484      stem(&z, "itici", "ic", m_gt_0);
113485      break;
113486    case 'l':
113487      stem(&z, "laci", "ic", m_gt_0) ||
113488      stem(&z, "luf", "", m_gt_0);
113489      break;
113490    case 's':
113491      stem(&z, "ssen", "", m_gt_0);
113492      break;
113493   }
113494
113495   /* Step 4 */
113496   switch( z[1] ){
113497    case 'a':
113498      if( z[0]=='l' && m_gt_1(z+2) ){
113499        z += 2;
113500      }
113501      break;
113502    case 'c':
113503      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
113504        z += 4;
113505      }
113506      break;
113507    case 'e':
113508      if( z[0]=='r' && m_gt_1(z+2) ){
113509        z += 2;
113510      }
113511      break;
113512    case 'i':
113513      if( z[0]=='c' && m_gt_1(z+2) ){
113514        z += 2;
113515      }
113516      break;
113517    case 'l':
113518      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
113519        z += 4;
113520      }
113521      break;
113522    case 'n':
113523      if( z[0]=='t' ){
113524        if( z[2]=='a' ){
113525          if( m_gt_1(z+3) ){
113526            z += 3;
113527          }
113528        }else if( z[2]=='e' ){
113529          stem(&z, "tneme", "", m_gt_1) ||
113530          stem(&z, "tnem", "", m_gt_1) ||
113531          stem(&z, "tne", "", m_gt_1);
113532        }
113533      }
113534      break;
113535    case 'o':
113536      if( z[0]=='u' ){
113537        if( m_gt_1(z+2) ){
113538          z += 2;
113539        }
113540      }else if( z[3]=='s' || z[3]=='t' ){
113541        stem(&z, "noi", "", m_gt_1);
113542      }
113543      break;
113544    case 's':
113545      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
113546        z += 3;
113547      }
113548      break;
113549    case 't':
113550      stem(&z, "eta", "", m_gt_1) ||
113551      stem(&z, "iti", "", m_gt_1);
113552      break;
113553    case 'u':
113554      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
113555        z += 3;
113556      }
113557      break;
113558    case 'v':
113559    case 'z':
113560      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
113561        z += 3;
113562      }
113563      break;
113564   }
113565
113566   /* Step 5a */
113567   if( z[0]=='e' ){
113568     if( m_gt_1(z+1) ){
113569       z++;
113570     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
113571       z++;
113572     }
113573   }
113574
113575   /* Step 5b */
113576   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
113577     z++;
113578   }
113579
113580   /* z[] is now the stemmed word in reverse order.  Flip it back
113581   ** around into forward order and return.
113582   */
113583   *pnOut = i = (int)strlen(z);
113584   zOut[i] = 0;
113585   while( *z ){
113586     zOut[--i] = *(z++);
113587   }
113588 }
113589
113590 /*
113591 ** Characters that can be part of a token.  We assume any character
113592 ** whose value is greater than 0x80 (any UTF character) can be
113593 ** part of a token.  In other words, delimiters all must have
113594 ** values of 0x7f or lower.
113595 */
113596 static const char porterIdChar[] = {
113597 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
113598     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
113599     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
113600     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
113601     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
113602     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
113603 };
113604 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
113605
113606 /*
113607 ** Extract the next token from a tokenization cursor.  The cursor must
113608 ** have been opened by a prior call to porterOpen().
113609 */
113610 static int porterNext(
113611   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
113612   const char **pzToken,               /* OUT: *pzToken is the token text */
113613   int *pnBytes,                       /* OUT: Number of bytes in token */
113614   int *piStartOffset,                 /* OUT: Starting offset of token */
113615   int *piEndOffset,                   /* OUT: Ending offset of token */
113616   int *piPosition                     /* OUT: Position integer of token */
113617 ){
113618   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
113619   const char *z = c->zInput;
113620
113621   while( c->iOffset<c->nInput ){
113622     int iStartOffset, ch;
113623
113624     /* Scan past delimiter characters */
113625     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
113626       c->iOffset++;
113627     }
113628
113629     /* Count non-delimiter characters. */
113630     iStartOffset = c->iOffset;
113631     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
113632       c->iOffset++;
113633     }
113634
113635     if( c->iOffset>iStartOffset ){
113636       int n = c->iOffset-iStartOffset;
113637       if( n>c->nAllocated ){
113638         char *pNew;
113639         c->nAllocated = n+20;
113640         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
113641         if( !pNew ) return SQLITE_NOMEM;
113642         c->zToken = pNew;
113643       }
113644       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
113645       *pzToken = c->zToken;
113646       *piStartOffset = iStartOffset;
113647       *piEndOffset = c->iOffset;
113648       *piPosition = c->iToken++;
113649       return SQLITE_OK;
113650     }
113651   }
113652   return SQLITE_DONE;
113653 }
113654
113655 /*
113656 ** The set of routines that implement the porter-stemmer tokenizer
113657 */
113658 static const sqlite3_tokenizer_module porterTokenizerModule = {
113659   0,
113660   porterCreate,
113661   porterDestroy,
113662   porterOpen,
113663   porterClose,
113664   porterNext,
113665 };
113666
113667 /*
113668 ** Allocate a new porter tokenizer.  Return a pointer to the new
113669 ** tokenizer in *ppModule
113670 */
113671 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
113672   sqlite3_tokenizer_module const**ppModule
113673 ){
113674   *ppModule = &porterTokenizerModule;
113675 }
113676
113677 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
113678
113679 /************** End of fts3_porter.c *****************************************/
113680 /************** Begin file fts3_tokenizer.c **********************************/
113681 /*
113682 ** 2007 June 22
113683 **
113684 ** The author disclaims copyright to this source code.  In place of
113685 ** a legal notice, here is a blessing:
113686 **
113687 **    May you do good and not evil.
113688 **    May you find forgiveness for yourself and forgive others.
113689 **    May you share freely, never taking more than you give.
113690 **
113691 ******************************************************************************
113692 **
113693 ** This is part of an SQLite module implementing full-text search.
113694 ** This particular file implements the generic tokenizer interface.
113695 */
113696
113697 /*
113698 ** The code in this file is only compiled if:
113699 **
113700 **     * The FTS3 module is being built as an extension
113701 **       (in which case SQLITE_CORE is not defined), or
113702 **
113703 **     * The FTS3 module is being built into the core of
113704 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
113705 */
113706 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
113707
113708 #ifndef SQLITE_CORE
113709   SQLITE_EXTENSION_INIT1
113710 #endif
113711
113712
113713 /*
113714 ** Implementation of the SQL scalar function for accessing the underlying 
113715 ** hash table. This function may be called as follows:
113716 **
113717 **   SELECT <function-name>(<key-name>);
113718 **   SELECT <function-name>(<key-name>, <pointer>);
113719 **
113720 ** where <function-name> is the name passed as the second argument
113721 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
113722 **
113723 ** If the <pointer> argument is specified, it must be a blob value
113724 ** containing a pointer to be stored as the hash data corresponding
113725 ** to the string <key-name>. If <pointer> is not specified, then
113726 ** the string <key-name> must already exist in the has table. Otherwise,
113727 ** an error is returned.
113728 **
113729 ** Whether or not the <pointer> argument is specified, the value returned
113730 ** is a blob containing the pointer stored as the hash data corresponding
113731 ** to string <key-name> (after the hash-table is updated, if applicable).
113732 */
113733 static void scalarFunc(
113734   sqlite3_context *context,
113735   int argc,
113736   sqlite3_value **argv
113737 ){
113738   Fts3Hash *pHash;
113739   void *pPtr = 0;
113740   const unsigned char *zName;
113741   int nName;
113742
113743   assert( argc==1 || argc==2 );
113744
113745   pHash = (Fts3Hash *)sqlite3_user_data(context);
113746
113747   zName = sqlite3_value_text(argv[0]);
113748   nName = sqlite3_value_bytes(argv[0])+1;
113749
113750   if( argc==2 ){
113751     void *pOld;
113752     int n = sqlite3_value_bytes(argv[1]);
113753     if( n!=sizeof(pPtr) ){
113754       sqlite3_result_error(context, "argument type mismatch", -1);
113755       return;
113756     }
113757     pPtr = *(void **)sqlite3_value_blob(argv[1]);
113758     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
113759     if( pOld==pPtr ){
113760       sqlite3_result_error(context, "out of memory", -1);
113761       return;
113762     }
113763   }else{
113764     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
113765     if( !pPtr ){
113766       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
113767       sqlite3_result_error(context, zErr, -1);
113768       sqlite3_free(zErr);
113769       return;
113770     }
113771   }
113772
113773   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
113774 }
113775
113776 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
113777   static const char isFtsIdChar[] = {
113778       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
113779       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
113780       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
113781       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
113782       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
113783       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
113784       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
113785       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
113786   };
113787   return (c&0x80 || isFtsIdChar[(int)(c)]);
113788 }
113789
113790 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
113791   const char *z1;
113792   const char *z2 = 0;
113793
113794   /* Find the start of the next token. */
113795   z1 = zStr;
113796   while( z2==0 ){
113797     char c = *z1;
113798     switch( c ){
113799       case '\0': return 0;        /* No more tokens here */
113800       case '\'':
113801       case '"':
113802       case '`': {
113803         z2 = z1;
113804         while( *++z2 && (*z2!=c || *++z2==c) );
113805         break;
113806       }
113807       case '[':
113808         z2 = &z1[1];
113809         while( *z2 && z2[0]!=']' ) z2++;
113810         if( *z2 ) z2++;
113811         break;
113812
113813       default:
113814         if( sqlite3Fts3IsIdChar(*z1) ){
113815           z2 = &z1[1];
113816           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
113817         }else{
113818           z1++;
113819         }
113820     }
113821   }
113822
113823   *pn = (int)(z2-z1);
113824   return z1;
113825 }
113826
113827 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
113828   Fts3Hash *pHash,                /* Tokenizer hash table */
113829   const char *zArg,               /* Tokenizer name */
113830   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
113831   char **pzErr                    /* OUT: Set to malloced error message */
113832 ){
113833   int rc;
113834   char *z = (char *)zArg;
113835   int n;
113836   char *zCopy;
113837   char *zEnd;                     /* Pointer to nul-term of zCopy */
113838   sqlite3_tokenizer_module *m;
113839
113840   zCopy = sqlite3_mprintf("%s", zArg);
113841   if( !zCopy ) return SQLITE_NOMEM;
113842   zEnd = &zCopy[strlen(zCopy)];
113843
113844   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
113845   z[n] = '\0';
113846   sqlite3Fts3Dequote(z);
113847
113848   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
113849   if( !m ){
113850     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
113851     rc = SQLITE_ERROR;
113852   }else{
113853     char const **aArg = 0;
113854     int iArg = 0;
113855     z = &z[n+1];
113856     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
113857       int nNew = sizeof(char *)*(iArg+1);
113858       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
113859       if( !aNew ){
113860         sqlite3_free(zCopy);
113861         sqlite3_free((void *)aArg);
113862         return SQLITE_NOMEM;
113863       }
113864       aArg = aNew;
113865       aArg[iArg++] = z;
113866       z[n] = '\0';
113867       sqlite3Fts3Dequote(z);
113868       z = &z[n+1];
113869     }
113870     rc = m->xCreate(iArg, aArg, ppTok);
113871     assert( rc!=SQLITE_OK || *ppTok );
113872     if( rc!=SQLITE_OK ){
113873       *pzErr = sqlite3_mprintf("unknown tokenizer");
113874     }else{
113875       (*ppTok)->pModule = m; 
113876     }
113877     sqlite3_free((void *)aArg);
113878   }
113879
113880   sqlite3_free(zCopy);
113881   return rc;
113882 }
113883
113884
113885 #ifdef SQLITE_TEST
113886
113887
113888 /*
113889 ** Implementation of a special SQL scalar function for testing tokenizers 
113890 ** designed to be used in concert with the Tcl testing framework. This
113891 ** function must be called with two arguments:
113892 **
113893 **   SELECT <function-name>(<key-name>, <input-string>);
113894 **   SELECT <function-name>(<key-name>, <pointer>);
113895 **
113896 ** where <function-name> is the name passed as the second argument
113897 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
113898 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
113899 **
113900 ** The return value is a string that may be interpreted as a Tcl
113901 ** list. For each token in the <input-string>, three elements are
113902 ** added to the returned list. The first is the token position, the 
113903 ** second is the token text (folded, stemmed, etc.) and the third is the
113904 ** substring of <input-string> associated with the token. For example, 
113905 ** using the built-in "simple" tokenizer:
113906 **
113907 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
113908 **
113909 ** will return the string:
113910 **
113911 **   "{0 i I 1 dont don't 2 see see 3 how how}"
113912 **   
113913 */
113914 static void testFunc(
113915   sqlite3_context *context,
113916   int argc,
113917   sqlite3_value **argv
113918 ){
113919   Fts3Hash *pHash;
113920   sqlite3_tokenizer_module *p;
113921   sqlite3_tokenizer *pTokenizer = 0;
113922   sqlite3_tokenizer_cursor *pCsr = 0;
113923
113924   const char *zErr = 0;
113925
113926   const char *zName;
113927   int nName;
113928   const char *zInput;
113929   int nInput;
113930
113931   const char *zArg = 0;
113932
113933   const char *zToken;
113934   int nToken;
113935   int iStart;
113936   int iEnd;
113937   int iPos;
113938
113939   Tcl_Obj *pRet;
113940
113941   assert( argc==2 || argc==3 );
113942
113943   nName = sqlite3_value_bytes(argv[0]);
113944   zName = (const char *)sqlite3_value_text(argv[0]);
113945   nInput = sqlite3_value_bytes(argv[argc-1]);
113946   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
113947
113948   if( argc==3 ){
113949     zArg = (const char *)sqlite3_value_text(argv[1]);
113950   }
113951
113952   pHash = (Fts3Hash *)sqlite3_user_data(context);
113953   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
113954
113955   if( !p ){
113956     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
113957     sqlite3_result_error(context, zErr, -1);
113958     sqlite3_free(zErr);
113959     return;
113960   }
113961
113962   pRet = Tcl_NewObj();
113963   Tcl_IncrRefCount(pRet);
113964
113965   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
113966     zErr = "error in xCreate()";
113967     goto finish;
113968   }
113969   pTokenizer->pModule = p;
113970   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
113971     zErr = "error in xOpen()";
113972     goto finish;
113973   }
113974   pCsr->pTokenizer = pTokenizer;
113975
113976   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
113977     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
113978     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
113979     zToken = &zInput[iStart];
113980     nToken = iEnd-iStart;
113981     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
113982   }
113983
113984   if( SQLITE_OK!=p->xClose(pCsr) ){
113985     zErr = "error in xClose()";
113986     goto finish;
113987   }
113988   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
113989     zErr = "error in xDestroy()";
113990     goto finish;
113991   }
113992
113993 finish:
113994   if( zErr ){
113995     sqlite3_result_error(context, zErr, -1);
113996   }else{
113997     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
113998   }
113999   Tcl_DecrRefCount(pRet);
114000 }
114001
114002 static
114003 int registerTokenizer(
114004   sqlite3 *db, 
114005   char *zName, 
114006   const sqlite3_tokenizer_module *p
114007 ){
114008   int rc;
114009   sqlite3_stmt *pStmt;
114010   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
114011
114012   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
114013   if( rc!=SQLITE_OK ){
114014     return rc;
114015   }
114016
114017   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
114018   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
114019   sqlite3_step(pStmt);
114020
114021   return sqlite3_finalize(pStmt);
114022 }
114023
114024 static
114025 int queryTokenizer(
114026   sqlite3 *db, 
114027   char *zName,  
114028   const sqlite3_tokenizer_module **pp
114029 ){
114030   int rc;
114031   sqlite3_stmt *pStmt;
114032   const char zSql[] = "SELECT fts3_tokenizer(?)";
114033
114034   *pp = 0;
114035   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
114036   if( rc!=SQLITE_OK ){
114037     return rc;
114038   }
114039
114040   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
114041   if( SQLITE_ROW==sqlite3_step(pStmt) ){
114042     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
114043       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
114044     }
114045   }
114046
114047   return sqlite3_finalize(pStmt);
114048 }
114049
114050 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
114051
114052 /*
114053 ** Implementation of the scalar function fts3_tokenizer_internal_test().
114054 ** This function is used for testing only, it is not included in the
114055 ** build unless SQLITE_TEST is defined.
114056 **
114057 ** The purpose of this is to test that the fts3_tokenizer() function
114058 ** can be used as designed by the C-code in the queryTokenizer and
114059 ** registerTokenizer() functions above. These two functions are repeated
114060 ** in the README.tokenizer file as an example, so it is important to
114061 ** test them.
114062 **
114063 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
114064 ** function with no arguments. An assert() will fail if a problem is
114065 ** detected. i.e.:
114066 **
114067 **     SELECT fts3_tokenizer_internal_test();
114068 **
114069 */
114070 static void intTestFunc(
114071   sqlite3_context *context,
114072   int argc,
114073   sqlite3_value **argv
114074 ){
114075   int rc;
114076   const sqlite3_tokenizer_module *p1;
114077   const sqlite3_tokenizer_module *p2;
114078   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
114079
114080   UNUSED_PARAMETER(argc);
114081   UNUSED_PARAMETER(argv);
114082
114083   /* Test the query function */
114084   sqlite3Fts3SimpleTokenizerModule(&p1);
114085   rc = queryTokenizer(db, "simple", &p2);
114086   assert( rc==SQLITE_OK );
114087   assert( p1==p2 );
114088   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
114089   assert( rc==SQLITE_ERROR );
114090   assert( p2==0 );
114091   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
114092
114093   /* Test the storage function */
114094   rc = registerTokenizer(db, "nosuchtokenizer", p1);
114095   assert( rc==SQLITE_OK );
114096   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
114097   assert( rc==SQLITE_OK );
114098   assert( p2==p1 );
114099
114100   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
114101 }
114102
114103 #endif
114104
114105 /*
114106 ** Set up SQL objects in database db used to access the contents of
114107 ** the hash table pointed to by argument pHash. The hash table must
114108 ** been initialised to use string keys, and to take a private copy 
114109 ** of the key when a value is inserted. i.e. by a call similar to:
114110 **
114111 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
114112 **
114113 ** This function adds a scalar function (see header comment above
114114 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
114115 ** defined at compilation time, a temporary virtual table (see header 
114116 ** comment above struct HashTableVtab) to the database schema. Both 
114117 ** provide read/write access to the contents of *pHash.
114118 **
114119 ** The third argument to this function, zName, is used as the name
114120 ** of both the scalar and, if created, the virtual table.
114121 */
114122 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
114123   sqlite3 *db, 
114124   Fts3Hash *pHash, 
114125   const char *zName
114126 ){
114127   int rc = SQLITE_OK;
114128   void *p = (void *)pHash;
114129   const int any = SQLITE_ANY;
114130
114131 #ifdef SQLITE_TEST
114132   char *zTest = 0;
114133   char *zTest2 = 0;
114134   void *pdb = (void *)db;
114135   zTest = sqlite3_mprintf("%s_test", zName);
114136   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
114137   if( !zTest || !zTest2 ){
114138     rc = SQLITE_NOMEM;
114139   }
114140 #endif
114141
114142   if( SQLITE_OK==rc ){
114143     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
114144   }
114145   if( SQLITE_OK==rc ){
114146     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
114147   }
114148 #ifdef SQLITE_TEST
114149   if( SQLITE_OK==rc ){
114150     rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
114151   }
114152   if( SQLITE_OK==rc ){
114153     rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
114154   }
114155   if( SQLITE_OK==rc ){
114156     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
114157   }
114158 #endif
114159
114160 #ifdef SQLITE_TEST
114161   sqlite3_free(zTest);
114162   sqlite3_free(zTest2);
114163 #endif
114164
114165   return rc;
114166 }
114167
114168 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
114169
114170 /************** End of fts3_tokenizer.c **************************************/
114171 /************** Begin file fts3_tokenizer1.c *********************************/
114172 /*
114173 ** 2006 Oct 10
114174 **
114175 ** The author disclaims copyright to this source code.  In place of
114176 ** a legal notice, here is a blessing:
114177 **
114178 **    May you do good and not evil.
114179 **    May you find forgiveness for yourself and forgive others.
114180 **    May you share freely, never taking more than you give.
114181 **
114182 ******************************************************************************
114183 **
114184 ** Implementation of the "simple" full-text-search tokenizer.
114185 */
114186
114187 /*
114188 ** The code in this file is only compiled if:
114189 **
114190 **     * The FTS3 module is being built as an extension
114191 **       (in which case SQLITE_CORE is not defined), or
114192 **
114193 **     * The FTS3 module is being built into the core of
114194 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
114195 */
114196 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114197
114198
114199
114200
114201 typedef struct simple_tokenizer {
114202   sqlite3_tokenizer base;
114203   char delim[128];             /* flag ASCII delimiters */
114204 } simple_tokenizer;
114205
114206 typedef struct simple_tokenizer_cursor {
114207   sqlite3_tokenizer_cursor base;
114208   const char *pInput;          /* input we are tokenizing */
114209   int nBytes;                  /* size of the input */
114210   int iOffset;                 /* current position in pInput */
114211   int iToken;                  /* index of next token to be returned */
114212   char *pToken;                /* storage for current token */
114213   int nTokenAllocated;         /* space allocated to zToken buffer */
114214 } simple_tokenizer_cursor;
114215
114216
114217 static int simpleDelim(simple_tokenizer *t, unsigned char c){
114218   return c<0x80 && t->delim[c];
114219 }
114220 static int fts3_isalnum(int x){
114221   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
114222 }
114223
114224 /*
114225 ** Create a new tokenizer instance.
114226 */
114227 static int simpleCreate(
114228   int argc, const char * const *argv,
114229   sqlite3_tokenizer **ppTokenizer
114230 ){
114231   simple_tokenizer *t;
114232
114233   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
114234   if( t==NULL ) return SQLITE_NOMEM;
114235   memset(t, 0, sizeof(*t));
114236
114237   /* TODO(shess) Delimiters need to remain the same from run to run,
114238   ** else we need to reindex.  One solution would be a meta-table to
114239   ** track such information in the database, then we'd only want this
114240   ** information on the initial create.
114241   */
114242   if( argc>1 ){
114243     int i, n = (int)strlen(argv[1]);
114244     for(i=0; i<n; i++){
114245       unsigned char ch = argv[1][i];
114246       /* We explicitly don't support UTF-8 delimiters for now. */
114247       if( ch>=0x80 ){
114248         sqlite3_free(t);
114249         return SQLITE_ERROR;
114250       }
114251       t->delim[ch] = 1;
114252     }
114253   } else {
114254     /* Mark non-alphanumeric ASCII characters as delimiters */
114255     int i;
114256     for(i=1; i<0x80; i++){
114257       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
114258     }
114259   }
114260
114261   *ppTokenizer = &t->base;
114262   return SQLITE_OK;
114263 }
114264
114265 /*
114266 ** Destroy a tokenizer
114267 */
114268 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
114269   sqlite3_free(pTokenizer);
114270   return SQLITE_OK;
114271 }
114272
114273 /*
114274 ** Prepare to begin tokenizing a particular string.  The input
114275 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
114276 ** used to incrementally tokenize this string is returned in 
114277 ** *ppCursor.
114278 */
114279 static int simpleOpen(
114280   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
114281   const char *pInput, int nBytes,        /* String to be tokenized */
114282   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
114283 ){
114284   simple_tokenizer_cursor *c;
114285
114286   UNUSED_PARAMETER(pTokenizer);
114287
114288   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
114289   if( c==NULL ) return SQLITE_NOMEM;
114290
114291   c->pInput = pInput;
114292   if( pInput==0 ){
114293     c->nBytes = 0;
114294   }else if( nBytes<0 ){
114295     c->nBytes = (int)strlen(pInput);
114296   }else{
114297     c->nBytes = nBytes;
114298   }
114299   c->iOffset = 0;                 /* start tokenizing at the beginning */
114300   c->iToken = 0;
114301   c->pToken = NULL;               /* no space allocated, yet. */
114302   c->nTokenAllocated = 0;
114303
114304   *ppCursor = &c->base;
114305   return SQLITE_OK;
114306 }
114307
114308 /*
114309 ** Close a tokenization cursor previously opened by a call to
114310 ** simpleOpen() above.
114311 */
114312 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
114313   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
114314   sqlite3_free(c->pToken);
114315   sqlite3_free(c);
114316   return SQLITE_OK;
114317 }
114318
114319 /*
114320 ** Extract the next token from a tokenization cursor.  The cursor must
114321 ** have been opened by a prior call to simpleOpen().
114322 */
114323 static int simpleNext(
114324   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
114325   const char **ppToken,               /* OUT: *ppToken is the token text */
114326   int *pnBytes,                       /* OUT: Number of bytes in token */
114327   int *piStartOffset,                 /* OUT: Starting offset of token */
114328   int *piEndOffset,                   /* OUT: Ending offset of token */
114329   int *piPosition                     /* OUT: Position integer of token */
114330 ){
114331   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
114332   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
114333   unsigned char *p = (unsigned char *)c->pInput;
114334
114335   while( c->iOffset<c->nBytes ){
114336     int iStartOffset;
114337
114338     /* Scan past delimiter characters */
114339     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
114340       c->iOffset++;
114341     }
114342
114343     /* Count non-delimiter characters. */
114344     iStartOffset = c->iOffset;
114345     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
114346       c->iOffset++;
114347     }
114348
114349     if( c->iOffset>iStartOffset ){
114350       int i, n = c->iOffset-iStartOffset;
114351       if( n>c->nTokenAllocated ){
114352         char *pNew;
114353         c->nTokenAllocated = n+20;
114354         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
114355         if( !pNew ) return SQLITE_NOMEM;
114356         c->pToken = pNew;
114357       }
114358       for(i=0; i<n; i++){
114359         /* TODO(shess) This needs expansion to handle UTF-8
114360         ** case-insensitivity.
114361         */
114362         unsigned char ch = p[iStartOffset+i];
114363         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
114364       }
114365       *ppToken = c->pToken;
114366       *pnBytes = n;
114367       *piStartOffset = iStartOffset;
114368       *piEndOffset = c->iOffset;
114369       *piPosition = c->iToken++;
114370
114371       return SQLITE_OK;
114372     }
114373   }
114374   return SQLITE_DONE;
114375 }
114376
114377 /*
114378 ** The set of routines that implement the simple tokenizer
114379 */
114380 static const sqlite3_tokenizer_module simpleTokenizerModule = {
114381   0,
114382   simpleCreate,
114383   simpleDestroy,
114384   simpleOpen,
114385   simpleClose,
114386   simpleNext,
114387 };
114388
114389 /*
114390 ** Allocate a new simple tokenizer.  Return a pointer to the new
114391 ** tokenizer in *ppModule
114392 */
114393 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
114394   sqlite3_tokenizer_module const**ppModule
114395 ){
114396   *ppModule = &simpleTokenizerModule;
114397 }
114398
114399 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
114400
114401 /************** End of fts3_tokenizer1.c *************************************/
114402 /************** Begin file fts3_write.c **************************************/
114403 /*
114404 ** 2009 Oct 23
114405 **
114406 ** The author disclaims copyright to this source code.  In place of
114407 ** a legal notice, here is a blessing:
114408 **
114409 **    May you do good and not evil.
114410 **    May you find forgiveness for yourself and forgive others.
114411 **    May you share freely, never taking more than you give.
114412 **
114413 ******************************************************************************
114414 **
114415 ** This file is part of the SQLite FTS3 extension module. Specifically,
114416 ** this file contains code to insert, update and delete rows from FTS3
114417 ** tables. It also contains code to merge FTS3 b-tree segments. Some
114418 ** of the sub-routines used to merge segments are also used by the query 
114419 ** code in fts3.c.
114420 */
114421
114422 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114423
114424
114425 /*
114426 ** When full-text index nodes are loaded from disk, the buffer that they
114427 ** are loaded into has the following number of bytes of padding at the end 
114428 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
114429 ** of 920 bytes is allocated for it.
114430 **
114431 ** This means that if we have a pointer into a buffer containing node data,
114432 ** it is always safe to read up to two varints from it without risking an
114433 ** overread, even if the node data is corrupted.
114434 */
114435 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
114436
114437 typedef struct PendingList PendingList;
114438 typedef struct SegmentNode SegmentNode;
114439 typedef struct SegmentWriter SegmentWriter;
114440
114441 /*
114442 ** Data structure used while accumulating terms in the pending-terms hash
114443 ** table. The hash table entry maps from term (a string) to a malloc'd
114444 ** instance of this structure.
114445 */
114446 struct PendingList {
114447   int nData;
114448   char *aData;
114449   int nSpace;
114450   sqlite3_int64 iLastDocid;
114451   sqlite3_int64 iLastCol;
114452   sqlite3_int64 iLastPos;
114453 };
114454
114455
114456 /*
114457 ** Each cursor has a (possibly empty) linked list of the following objects.
114458 */
114459 struct Fts3DeferredToken {
114460   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
114461   int iCol;                       /* Column token must occur in */
114462   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
114463   PendingList *pList;             /* Doclist is assembled here */
114464 };
114465
114466 /*
114467 ** An instance of this structure is used to iterate through the terms on
114468 ** a contiguous set of segment b-tree leaf nodes. Although the details of
114469 ** this structure are only manipulated by code in this file, opaque handles
114470 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
114471 ** terms when querying the full-text index. See functions:
114472 **
114473 **   sqlite3Fts3SegReaderNew()
114474 **   sqlite3Fts3SegReaderFree()
114475 **   sqlite3Fts3SegReaderCost()
114476 **   sqlite3Fts3SegReaderIterate()
114477 **
114478 ** Methods used to manipulate Fts3SegReader structures:
114479 **
114480 **   fts3SegReaderNext()
114481 **   fts3SegReaderFirstDocid()
114482 **   fts3SegReaderNextDocid()
114483 */
114484 struct Fts3SegReader {
114485   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
114486
114487   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
114488   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
114489   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
114490   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
114491
114492   char *aNode;                    /* Pointer to node data (or NULL) */
114493   int nNode;                      /* Size of buffer at aNode (or 0) */
114494   Fts3HashElem **ppNextElem;
114495
114496   /* Variables set by fts3SegReaderNext(). These may be read directly
114497   ** by the caller. They are valid from the time SegmentReaderNew() returns
114498   ** until SegmentReaderNext() returns something other than SQLITE_OK
114499   ** (i.e. SQLITE_DONE).
114500   */
114501   int nTerm;                      /* Number of bytes in current term */
114502   char *zTerm;                    /* Pointer to current term */
114503   int nTermAlloc;                 /* Allocated size of zTerm buffer */
114504   char *aDoclist;                 /* Pointer to doclist of current entry */
114505   int nDoclist;                   /* Size of doclist in current entry */
114506
114507   /* The following variables are used to iterate through the current doclist */
114508   char *pOffsetList;
114509   sqlite3_int64 iDocid;
114510 };
114511
114512 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
114513 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
114514
114515 /*
114516 ** An instance of this structure is used to create a segment b-tree in the
114517 ** database. The internal details of this type are only accessed by the
114518 ** following functions:
114519 **
114520 **   fts3SegWriterAdd()
114521 **   fts3SegWriterFlush()
114522 **   fts3SegWriterFree()
114523 */
114524 struct SegmentWriter {
114525   SegmentNode *pTree;             /* Pointer to interior tree structure */
114526   sqlite3_int64 iFirst;           /* First slot in %_segments written */
114527   sqlite3_int64 iFree;            /* Next free slot in %_segments */
114528   char *zTerm;                    /* Pointer to previous term buffer */
114529   int nTerm;                      /* Number of bytes in zTerm */
114530   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
114531   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
114532   int nSize;                      /* Size of allocation at aData */
114533   int nData;                      /* Bytes of data in aData */
114534   char *aData;                    /* Pointer to block from malloc() */
114535 };
114536
114537 /*
114538 ** Type SegmentNode is used by the following three functions to create
114539 ** the interior part of the segment b+-tree structures (everything except
114540 ** the leaf nodes). These functions and type are only ever used by code
114541 ** within the fts3SegWriterXXX() family of functions described above.
114542 **
114543 **   fts3NodeAddTerm()
114544 **   fts3NodeWrite()
114545 **   fts3NodeFree()
114546 */
114547 struct SegmentNode {
114548   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
114549   SegmentNode *pRight;            /* Pointer to right-sibling */
114550   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
114551   int nEntry;                     /* Number of terms written to node so far */
114552   char *zTerm;                    /* Pointer to previous term buffer */
114553   int nTerm;                      /* Number of bytes in zTerm */
114554   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
114555   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
114556   int nData;                      /* Bytes of valid data so far */
114557   char *aData;                    /* Node data */
114558 };
114559
114560 /*
114561 ** Valid values for the second argument to fts3SqlStmt().
114562 */
114563 #define SQL_DELETE_CONTENT             0
114564 #define SQL_IS_EMPTY                   1
114565 #define SQL_DELETE_ALL_CONTENT         2 
114566 #define SQL_DELETE_ALL_SEGMENTS        3
114567 #define SQL_DELETE_ALL_SEGDIR          4
114568 #define SQL_DELETE_ALL_DOCSIZE         5
114569 #define SQL_DELETE_ALL_STAT            6
114570 #define SQL_SELECT_CONTENT_BY_ROWID    7
114571 #define SQL_NEXT_SEGMENT_INDEX         8
114572 #define SQL_INSERT_SEGMENTS            9
114573 #define SQL_NEXT_SEGMENTS_ID          10
114574 #define SQL_INSERT_SEGDIR             11
114575 #define SQL_SELECT_LEVEL              12
114576 #define SQL_SELECT_ALL_LEVEL          13
114577 #define SQL_SELECT_LEVEL_COUNT        14
114578 #define SQL_SELECT_SEGDIR_COUNT_MAX   15
114579 #define SQL_DELETE_SEGDIR_BY_LEVEL    16
114580 #define SQL_DELETE_SEGMENTS_RANGE     17
114581 #define SQL_CONTENT_INSERT            18
114582 #define SQL_DELETE_DOCSIZE            19
114583 #define SQL_REPLACE_DOCSIZE           20
114584 #define SQL_SELECT_DOCSIZE            21
114585 #define SQL_SELECT_DOCTOTAL           22
114586 #define SQL_REPLACE_DOCTOTAL          23
114587
114588 /*
114589 ** This function is used to obtain an SQLite prepared statement handle
114590 ** for the statement identified by the second argument. If successful,
114591 ** *pp is set to the requested statement handle and SQLITE_OK returned.
114592 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
114593 **
114594 ** If argument apVal is not NULL, then it must point to an array with
114595 ** at least as many entries as the requested statement has bound 
114596 ** parameters. The values are bound to the statements parameters before
114597 ** returning.
114598 */
114599 static int fts3SqlStmt(
114600   Fts3Table *p,                   /* Virtual table handle */
114601   int eStmt,                      /* One of the SQL_XXX constants above */
114602   sqlite3_stmt **pp,              /* OUT: Statement handle */
114603   sqlite3_value **apVal           /* Values to bind to statement */
114604 ){
114605   const char *azSql[] = {
114606 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
114607 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
114608 /* 2  */  "DELETE FROM %Q.'%q_content'",
114609 /* 3  */  "DELETE FROM %Q.'%q_segments'",
114610 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
114611 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
114612 /* 6  */  "DELETE FROM %Q.'%q_stat'",
114613 /* 7  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
114614 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
114615 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
114616 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
114617 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
114618
114619           /* Return segments in order from oldest to newest.*/ 
114620 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
114621             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
114622 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
114623             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
114624
114625 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
114626 /* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
114627
114628 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
114629 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
114630 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
114631 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
114632 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
114633 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
114634 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
114635 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
114636   };
114637   int rc = SQLITE_OK;
114638   sqlite3_stmt *pStmt;
114639
114640   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
114641   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
114642   
114643   pStmt = p->aStmt[eStmt];
114644   if( !pStmt ){
114645     char *zSql;
114646     if( eStmt==SQL_CONTENT_INSERT ){
114647       int i;                      /* Iterator variable */  
114648       char *zVarlist;             /* The "?, ?, ..." string */
114649       zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
114650       if( !zVarlist ){
114651         *pp = 0;
114652         return SQLITE_NOMEM;
114653       }
114654       zVarlist[0] = '?';
114655       zVarlist[p->nColumn*2+1] = '\0';
114656       for(i=1; i<=p->nColumn; i++){
114657         zVarlist[i*2-1] = ',';
114658         zVarlist[i*2] = '?';
114659       }
114660       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
114661     }else{
114662       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
114663     }
114664     if( !zSql ){
114665       rc = SQLITE_NOMEM;
114666     }else{
114667       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
114668       sqlite3_free(zSql);
114669       assert( rc==SQLITE_OK || pStmt==0 );
114670       p->aStmt[eStmt] = pStmt;
114671     }
114672   }
114673   if( apVal ){
114674     int i;
114675     int nParam = sqlite3_bind_parameter_count(pStmt);
114676     for(i=0; rc==SQLITE_OK && i<nParam; i++){
114677       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
114678     }
114679   }
114680   *pp = pStmt;
114681   return rc;
114682 }
114683
114684 static int fts3SelectDocsize(
114685   Fts3Table *pTab,                /* FTS3 table handle */
114686   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
114687   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
114688   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
114689 ){
114690   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
114691   int rc;                         /* Return code */
114692
114693   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
114694
114695   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
114696   if( rc==SQLITE_OK ){
114697     if( eStmt==SQL_SELECT_DOCSIZE ){
114698       sqlite3_bind_int64(pStmt, 1, iDocid);
114699     }
114700     rc = sqlite3_step(pStmt);
114701     if( rc!=SQLITE_ROW ){
114702       rc = sqlite3_reset(pStmt);
114703       if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT;
114704       pStmt = 0;
114705     }else{
114706       rc = SQLITE_OK;
114707     }
114708   }
114709
114710   *ppStmt = pStmt;
114711   return rc;
114712 }
114713
114714 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
114715   Fts3Table *pTab,                /* Fts3 table handle */
114716   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
114717 ){
114718   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
114719 }
114720
114721 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
114722   Fts3Table *pTab,                /* Fts3 table handle */
114723   sqlite3_int64 iDocid,           /* Docid to read size data for */
114724   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
114725 ){
114726   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
114727 }
114728
114729 /*
114730 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
114731 ** array apVal[] to the SQL statement identified by eStmt, the statement
114732 ** is executed.
114733 **
114734 ** Returns SQLITE_OK if the statement is successfully executed, or an
114735 ** SQLite error code otherwise.
114736 */
114737 static void fts3SqlExec(
114738   int *pRC,                /* Result code */
114739   Fts3Table *p,            /* The FTS3 table */
114740   int eStmt,               /* Index of statement to evaluate */
114741   sqlite3_value **apVal    /* Parameters to bind */
114742 ){
114743   sqlite3_stmt *pStmt;
114744   int rc;
114745   if( *pRC ) return;
114746   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
114747   if( rc==SQLITE_OK ){
114748     sqlite3_step(pStmt);
114749     rc = sqlite3_reset(pStmt);
114750   }
114751   *pRC = rc;
114752 }
114753
114754
114755 /*
114756 ** This function ensures that the caller has obtained a shared-cache
114757 ** table-lock on the %_content table. This is required before reading
114758 ** data from the fts3 table. If this lock is not acquired first, then
114759 ** the caller may end up holding read-locks on the %_segments and %_segdir
114760 ** tables, but no read-lock on the %_content table. If this happens 
114761 ** a second connection will be able to write to the fts3 table, but
114762 ** attempting to commit those writes might return SQLITE_LOCKED or
114763 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
114764 ** write-locks on the %_segments and %_segdir ** tables). 
114765 **
114766 ** We try to avoid this because if FTS3 returns any error when committing
114767 ** a transaction, the whole transaction will be rolled back. And this is
114768 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
114769 ** still happen if the user reads data directly from the %_segments or
114770 ** %_segdir tables instead of going through FTS3 though.
114771 */
114772 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
114773   int rc;                         /* Return code */
114774   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
114775
114776   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
114777   if( rc==SQLITE_OK ){
114778     sqlite3_bind_null(pStmt, 1);
114779     sqlite3_step(pStmt);
114780     rc = sqlite3_reset(pStmt);
114781   }
114782   return rc;
114783 }
114784
114785 /*
114786 ** Set *ppStmt to a statement handle that may be used to iterate through
114787 ** all rows in the %_segdir table, from oldest to newest. If successful,
114788 ** return SQLITE_OK. If an error occurs while preparing the statement, 
114789 ** return an SQLite error code.
114790 **
114791 ** There is only ever one instance of this SQL statement compiled for
114792 ** each FTS3 table.
114793 **
114794 ** The statement returns the following columns from the %_segdir table:
114795 **
114796 **   0: idx
114797 **   1: start_block
114798 **   2: leaves_end_block
114799 **   3: end_block
114800 **   4: root
114801 */
114802 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
114803   return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
114804 }
114805
114806
114807 /*
114808 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
114809 ** if successful, or an SQLite error code otherwise.
114810 **
114811 ** This function also serves to allocate the PendingList structure itself.
114812 ** For example, to create a new PendingList structure containing two
114813 ** varints:
114814 **
114815 **   PendingList *p = 0;
114816 **   fts3PendingListAppendVarint(&p, 1);
114817 **   fts3PendingListAppendVarint(&p, 2);
114818 */
114819 static int fts3PendingListAppendVarint(
114820   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
114821   sqlite3_int64 i                 /* Value to append to data */
114822 ){
114823   PendingList *p = *pp;
114824
114825   /* Allocate or grow the PendingList as required. */
114826   if( !p ){
114827     p = sqlite3_malloc(sizeof(*p) + 100);
114828     if( !p ){
114829       return SQLITE_NOMEM;
114830     }
114831     p->nSpace = 100;
114832     p->aData = (char *)&p[1];
114833     p->nData = 0;
114834   }
114835   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
114836     int nNew = p->nSpace * 2;
114837     p = sqlite3_realloc(p, sizeof(*p) + nNew);
114838     if( !p ){
114839       sqlite3_free(*pp);
114840       *pp = 0;
114841       return SQLITE_NOMEM;
114842     }
114843     p->nSpace = nNew;
114844     p->aData = (char *)&p[1];
114845   }
114846
114847   /* Append the new serialized varint to the end of the list. */
114848   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
114849   p->aData[p->nData] = '\0';
114850   *pp = p;
114851   return SQLITE_OK;
114852 }
114853
114854 /*
114855 ** Add a docid/column/position entry to a PendingList structure. Non-zero
114856 ** is returned if the structure is sqlite3_realloced as part of adding
114857 ** the entry. Otherwise, zero.
114858 **
114859 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
114860 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
114861 ** it is set to SQLITE_OK.
114862 */
114863 static int fts3PendingListAppend(
114864   PendingList **pp,               /* IN/OUT: PendingList structure */
114865   sqlite3_int64 iDocid,           /* Docid for entry to add */
114866   sqlite3_int64 iCol,             /* Column for entry to add */
114867   sqlite3_int64 iPos,             /* Position of term for entry to add */
114868   int *pRc                        /* OUT: Return code */
114869 ){
114870   PendingList *p = *pp;
114871   int rc = SQLITE_OK;
114872
114873   assert( !p || p->iLastDocid<=iDocid );
114874
114875   if( !p || p->iLastDocid!=iDocid ){
114876     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
114877     if( p ){
114878       assert( p->nData<p->nSpace );
114879       assert( p->aData[p->nData]==0 );
114880       p->nData++;
114881     }
114882     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
114883       goto pendinglistappend_out;
114884     }
114885     p->iLastCol = -1;
114886     p->iLastPos = 0;
114887     p->iLastDocid = iDocid;
114888   }
114889   if( iCol>0 && p->iLastCol!=iCol ){
114890     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
114891      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
114892     ){
114893       goto pendinglistappend_out;
114894     }
114895     p->iLastCol = iCol;
114896     p->iLastPos = 0;
114897   }
114898   if( iCol>=0 ){
114899     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
114900     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
114901     if( rc==SQLITE_OK ){
114902       p->iLastPos = iPos;
114903     }
114904   }
114905
114906  pendinglistappend_out:
114907   *pRc = rc;
114908   if( p!=*pp ){
114909     *pp = p;
114910     return 1;
114911   }
114912   return 0;
114913 }
114914
114915 /*
114916 ** Tokenize the nul-terminated string zText and add all tokens to the
114917 ** pending-terms hash-table. The docid used is that currently stored in
114918 ** p->iPrevDocid, and the column is specified by argument iCol.
114919 **
114920 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
114921 */
114922 static int fts3PendingTermsAdd(
114923   Fts3Table *p,                   /* Table into which text will be inserted */
114924   const char *zText,              /* Text of document to be inserted */
114925   int iCol,                       /* Column into which text is being inserted */
114926   u32 *pnWord                     /* OUT: Number of tokens inserted */
114927 ){
114928   int rc;
114929   int iStart;
114930   int iEnd;
114931   int iPos;
114932   int nWord = 0;
114933
114934   char const *zToken;
114935   int nToken;
114936
114937   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
114938   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
114939   sqlite3_tokenizer_cursor *pCsr;
114940   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
114941       const char**,int*,int*,int*,int*);
114942
114943   assert( pTokenizer && pModule );
114944
114945   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
114946   if( rc!=SQLITE_OK ){
114947     return rc;
114948   }
114949   pCsr->pTokenizer = pTokenizer;
114950
114951   xNext = pModule->xNext;
114952   while( SQLITE_OK==rc
114953       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
114954   ){
114955     PendingList *pList;
114956  
114957     if( iPos>=nWord ) nWord = iPos+1;
114958
114959     /* Positions cannot be negative; we use -1 as a terminator internally.
114960     ** Tokens must have a non-zero length.
114961     */
114962     if( iPos<0 || !zToken || nToken<=0 ){
114963       rc = SQLITE_ERROR;
114964       break;
114965     }
114966
114967     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
114968     if( pList ){
114969       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
114970     }
114971     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
114972       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
114973         /* Malloc failed while inserting the new entry. This can only 
114974         ** happen if there was no previous entry for this token.
114975         */
114976         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
114977         sqlite3_free(pList);
114978         rc = SQLITE_NOMEM;
114979       }
114980     }
114981     if( rc==SQLITE_OK ){
114982       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
114983     }
114984   }
114985
114986   pModule->xClose(pCsr);
114987   *pnWord = nWord;
114988   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
114989 }
114990
114991 /* 
114992 ** Calling this function indicates that subsequent calls to 
114993 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
114994 ** contents of the document with docid iDocid.
114995 */
114996 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
114997   /* TODO(shess) Explore whether partially flushing the buffer on
114998   ** forced-flush would provide better performance.  I suspect that if
114999   ** we ordered the doclists by size and flushed the largest until the
115000   ** buffer was half empty, that would let the less frequent terms
115001   ** generate longer doclists.
115002   */
115003   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
115004     int rc = sqlite3Fts3PendingTermsFlush(p);
115005     if( rc!=SQLITE_OK ) return rc;
115006   }
115007   p->iPrevDocid = iDocid;
115008   return SQLITE_OK;
115009 }
115010
115011 /*
115012 ** Discard the contents of the pending-terms hash table. 
115013 */
115014 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
115015   Fts3HashElem *pElem;
115016   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
115017     sqlite3_free(fts3HashData(pElem));
115018   }
115019   fts3HashClear(&p->pendingTerms);
115020   p->nPendingData = 0;
115021 }
115022
115023 /*
115024 ** This function is called by the xUpdate() method as part of an INSERT
115025 ** operation. It adds entries for each term in the new record to the
115026 ** pendingTerms hash table.
115027 **
115028 ** Argument apVal is the same as the similarly named argument passed to
115029 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
115030 */
115031 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
115032   int i;                          /* Iterator variable */
115033   for(i=2; i<p->nColumn+2; i++){
115034     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
115035     if( zText ){
115036       int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
115037       if( rc!=SQLITE_OK ){
115038         return rc;
115039       }
115040     }
115041     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
115042   }
115043   return SQLITE_OK;
115044 }
115045
115046 /*
115047 ** This function is called by the xUpdate() method for an INSERT operation.
115048 ** The apVal parameter is passed a copy of the apVal argument passed by
115049 ** SQLite to the xUpdate() method. i.e:
115050 **
115051 **   apVal[0]                Not used for INSERT.
115052 **   apVal[1]                rowid
115053 **   apVal[2]                Left-most user-defined column
115054 **   ...
115055 **   apVal[p->nColumn+1]     Right-most user-defined column
115056 **   apVal[p->nColumn+2]     Hidden column with same name as table
115057 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
115058 */
115059 static int fts3InsertData(
115060   Fts3Table *p,                   /* Full-text table */
115061   sqlite3_value **apVal,          /* Array of values to insert */
115062   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
115063 ){
115064   int rc;                         /* Return code */
115065   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
115066
115067   /* Locate the statement handle used to insert data into the %_content
115068   ** table. The SQL for this statement is:
115069   **
115070   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
115071   **
115072   ** The statement features N '?' variables, where N is the number of user
115073   ** defined columns in the FTS3 table, plus one for the docid field.
115074   */
115075   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
115076   if( rc!=SQLITE_OK ){
115077     return rc;
115078   }
115079
115080   /* There is a quirk here. The users INSERT statement may have specified
115081   ** a value for the "rowid" field, for the "docid" field, or for both.
115082   ** Which is a problem, since "rowid" and "docid" are aliases for the
115083   ** same value. For example:
115084   **
115085   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
115086   **
115087   ** In FTS3, this is an error. It is an error to specify non-NULL values
115088   ** for both docid and some other rowid alias.
115089   */
115090   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
115091     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
115092      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
115093     ){
115094       /* A rowid/docid conflict. */
115095       return SQLITE_ERROR;
115096     }
115097     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
115098     if( rc!=SQLITE_OK ) return rc;
115099   }
115100
115101   /* Execute the statement to insert the record. Set *piDocid to the 
115102   ** new docid value. 
115103   */
115104   sqlite3_step(pContentInsert);
115105   rc = sqlite3_reset(pContentInsert);
115106
115107   *piDocid = sqlite3_last_insert_rowid(p->db);
115108   return rc;
115109 }
115110
115111
115112
115113 /*
115114 ** Remove all data from the FTS3 table. Clear the hash table containing
115115 ** pending terms.
115116 */
115117 static int fts3DeleteAll(Fts3Table *p){
115118   int rc = SQLITE_OK;             /* Return code */
115119
115120   /* Discard the contents of the pending-terms hash table. */
115121   sqlite3Fts3PendingTermsClear(p);
115122
115123   /* Delete everything from the %_content, %_segments and %_segdir tables. */
115124   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
115125   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
115126   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
115127   if( p->bHasDocsize ){
115128     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
115129   }
115130   if( p->bHasStat ){
115131     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
115132   }
115133   return rc;
115134 }
115135
115136 /*
115137 ** The first element in the apVal[] array is assumed to contain the docid
115138 ** (an integer) of a row about to be deleted. Remove all terms from the
115139 ** full-text index.
115140 */
115141 static void fts3DeleteTerms( 
115142   int *pRC,               /* Result code */
115143   Fts3Table *p,           /* The FTS table to delete from */
115144   sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
115145   u32 *aSz                /* Sizes of deleted document written here */
115146 ){
115147   int rc;
115148   sqlite3_stmt *pSelect;
115149
115150   if( *pRC ) return;
115151   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
115152   if( rc==SQLITE_OK ){
115153     if( SQLITE_ROW==sqlite3_step(pSelect) ){
115154       int i;
115155       for(i=1; i<=p->nColumn; i++){
115156         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
115157         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
115158         if( rc!=SQLITE_OK ){
115159           sqlite3_reset(pSelect);
115160           *pRC = rc;
115161           return;
115162         }
115163         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
115164       }
115165     }
115166     rc = sqlite3_reset(pSelect);
115167   }else{
115168     sqlite3_reset(pSelect);
115169   }
115170   *pRC = rc;
115171 }
115172
115173 /*
115174 ** Forward declaration to account for the circular dependency between
115175 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
115176 */
115177 static int fts3SegmentMerge(Fts3Table *, int);
115178
115179 /* 
115180 ** This function allocates a new level iLevel index in the segdir table.
115181 ** Usually, indexes are allocated within a level sequentially starting
115182 ** with 0, so the allocated index is one greater than the value returned
115183 ** by:
115184 **
115185 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
115186 **
115187 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
115188 ** level, they are merged into a single level (iLevel+1) segment and the 
115189 ** allocated index is 0.
115190 **
115191 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
115192 ** returned. Otherwise, an SQLite error code is returned.
115193 */
115194 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
115195   int rc;                         /* Return Code */
115196   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
115197   int iNext = 0;                  /* Result of query pNextIdx */
115198
115199   /* Set variable iNext to the next available segdir index at level iLevel. */
115200   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
115201   if( rc==SQLITE_OK ){
115202     sqlite3_bind_int(pNextIdx, 1, iLevel);
115203     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
115204       iNext = sqlite3_column_int(pNextIdx, 0);
115205     }
115206     rc = sqlite3_reset(pNextIdx);
115207   }
115208
115209   if( rc==SQLITE_OK ){
115210     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
115211     ** full, merge all segments in level iLevel into a single iLevel+1
115212     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
115213     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
115214     */
115215     if( iNext>=FTS3_MERGE_COUNT ){
115216       rc = fts3SegmentMerge(p, iLevel);
115217       *piIdx = 0;
115218     }else{
115219       *piIdx = iNext;
115220     }
115221   }
115222
115223   return rc;
115224 }
115225
115226 /*
115227 ** The %_segments table is declared as follows:
115228 **
115229 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
115230 **
115231 ** This function reads data from a single row of the %_segments table. The
115232 ** specific row is identified by the iBlockid parameter. If paBlob is not
115233 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
115234 ** with the contents of the blob stored in the "block" column of the 
115235 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
115236 ** to the size of the blob in bytes before returning.
115237 **
115238 ** If an error occurs, or the table does not contain the specified row,
115239 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
115240 ** paBlob is non-NULL, then it is the responsibility of the caller to
115241 ** eventually free the returned buffer.
115242 **
115243 ** This function may leave an open sqlite3_blob* handle in the
115244 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
115245 ** to this function. The handle may be closed by calling the
115246 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
115247 ** performance improvement, but the blob handle should always be closed
115248 ** before control is returned to the user (to prevent a lock being held
115249 ** on the database file for longer than necessary). Thus, any virtual table
115250 ** method (xFilter etc.) that may directly or indirectly call this function
115251 ** must call sqlite3Fts3SegmentsClose() before returning.
115252 */
115253 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
115254   Fts3Table *p,                   /* FTS3 table handle */
115255   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
115256   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
115257   int *pnBlob                     /* OUT: Size of blob data */
115258 ){
115259   int rc;                         /* Return code */
115260
115261   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
115262   assert( pnBlob);
115263
115264   if( p->pSegments ){
115265     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
115266   }else{
115267     if( 0==p->zSegmentsTbl ){
115268       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
115269       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
115270     }
115271     rc = sqlite3_blob_open(
115272        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
115273     );
115274   }
115275
115276   if( rc==SQLITE_OK ){
115277     int nByte = sqlite3_blob_bytes(p->pSegments);
115278     if( paBlob ){
115279       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
115280       if( !aByte ){
115281         rc = SQLITE_NOMEM;
115282       }else{
115283         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
115284         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
115285         if( rc!=SQLITE_OK ){
115286           sqlite3_free(aByte);
115287           aByte = 0;
115288         }
115289       }
115290       *paBlob = aByte;
115291     }
115292     *pnBlob = nByte;
115293   }
115294
115295   return rc;
115296 }
115297
115298 /*
115299 ** Close the blob handle at p->pSegments, if it is open. See comments above
115300 ** the sqlite3Fts3ReadBlock() function for details.
115301 */
115302 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
115303   sqlite3_blob_close(p->pSegments);
115304   p->pSegments = 0;
115305 }
115306
115307 /*
115308 ** Move the iterator passed as the first argument to the next term in the
115309 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
115310 ** SQLITE_DONE. Otherwise, an SQLite error code.
115311 */
115312 static int fts3SegReaderNext(Fts3Table *p, Fts3SegReader *pReader){
115313   char *pNext;                    /* Cursor variable */
115314   int nPrefix;                    /* Number of bytes in term prefix */
115315   int nSuffix;                    /* Number of bytes in term suffix */
115316
115317   if( !pReader->aDoclist ){
115318     pNext = pReader->aNode;
115319   }else{
115320     pNext = &pReader->aDoclist[pReader->nDoclist];
115321   }
115322
115323   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
115324     int rc;                       /* Return code from Fts3ReadBlock() */
115325
115326     if( fts3SegReaderIsPending(pReader) ){
115327       Fts3HashElem *pElem = *(pReader->ppNextElem);
115328       if( pElem==0 ){
115329         pReader->aNode = 0;
115330       }else{
115331         PendingList *pList = (PendingList *)fts3HashData(pElem);
115332         pReader->zTerm = (char *)fts3HashKey(pElem);
115333         pReader->nTerm = fts3HashKeysize(pElem);
115334         pReader->nNode = pReader->nDoclist = pList->nData + 1;
115335         pReader->aNode = pReader->aDoclist = pList->aData;
115336         pReader->ppNextElem++;
115337         assert( pReader->aNode );
115338       }
115339       return SQLITE_OK;
115340     }
115341
115342     if( !fts3SegReaderIsRootOnly(pReader) ){
115343       sqlite3_free(pReader->aNode);
115344     }
115345     pReader->aNode = 0;
115346
115347     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
115348     ** blocks have already been traversed.  */
115349     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
115350     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
115351       return SQLITE_OK;
115352     }
115353
115354     rc = sqlite3Fts3ReadBlock(
115355         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode
115356     );
115357     if( rc!=SQLITE_OK ) return rc;
115358     pNext = pReader->aNode;
115359   }
115360   
115361   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
115362   ** safe (no risk of overread) even if the node data is corrupted.  
115363   */
115364   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
115365   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
115366   if( nPrefix<0 || nSuffix<=0 
115367    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
115368   ){
115369     return SQLITE_CORRUPT;
115370   }
115371
115372   if( nPrefix+nSuffix>pReader->nTermAlloc ){
115373     int nNew = (nPrefix+nSuffix)*2;
115374     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
115375     if( !zNew ){
115376       return SQLITE_NOMEM;
115377     }
115378     pReader->zTerm = zNew;
115379     pReader->nTermAlloc = nNew;
115380   }
115381   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
115382   pReader->nTerm = nPrefix+nSuffix;
115383   pNext += nSuffix;
115384   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
115385   pReader->aDoclist = pNext;
115386   pReader->pOffsetList = 0;
115387
115388   /* Check that the doclist does not appear to extend past the end of the
115389   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
115390   ** of these statements is untrue, then the data structure is corrupt.
115391   */
115392   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
115393    || pReader->aDoclist[pReader->nDoclist-1]
115394   ){
115395     return SQLITE_CORRUPT;
115396   }
115397   return SQLITE_OK;
115398 }
115399
115400 /*
115401 ** Set the SegReader to point to the first docid in the doclist associated
115402 ** with the current term.
115403 */
115404 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
115405   int n;
115406   assert( pReader->aDoclist );
115407   assert( !pReader->pOffsetList );
115408   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
115409   pReader->pOffsetList = &pReader->aDoclist[n];
115410 }
115411
115412 /*
115413 ** Advance the SegReader to point to the next docid in the doclist
115414 ** associated with the current term.
115415 ** 
115416 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
115417 ** *ppOffsetList is set to point to the first column-offset list
115418 ** in the doclist entry (i.e. immediately past the docid varint).
115419 ** *pnOffsetList is set to the length of the set of column-offset
115420 ** lists, not including the nul-terminator byte. For example:
115421 */
115422 static void fts3SegReaderNextDocid(
115423   Fts3SegReader *pReader,
115424   char **ppOffsetList,
115425   int *pnOffsetList
115426 ){
115427   char *p = pReader->pOffsetList;
115428   char c = 0;
115429
115430   /* Pointer p currently points at the first byte of an offset list. The
115431   ** following two lines advance it to point one byte past the end of
115432   ** the same offset list.
115433   */
115434   while( *p | c ) c = *p++ & 0x80;
115435   p++;
115436
115437   /* If required, populate the output variables with a pointer to and the
115438   ** size of the previous offset-list.
115439   */
115440   if( ppOffsetList ){
115441     *ppOffsetList = pReader->pOffsetList;
115442     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
115443   }
115444
115445   /* If there are no more entries in the doclist, set pOffsetList to
115446   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
115447   ** Fts3SegReader.pOffsetList to point to the next offset list before
115448   ** returning.
115449   */
115450   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
115451     pReader->pOffsetList = 0;
115452   }else{
115453     sqlite3_int64 iDelta;
115454     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
115455     pReader->iDocid += iDelta;
115456   }
115457 }
115458
115459 /*
115460 ** This function is called to estimate the amount of data that will be 
115461 ** loaded from the disk If SegReaderIterate() is called on this seg-reader,
115462 ** in units of average document size.
115463 ** 
115464 ** This can be used as follows: If the caller has a small doclist that 
115465 ** contains references to N documents, and is considering merging it with
115466 ** a large doclist (size X "average documents"), it may opt not to load
115467 ** the large doclist if X>N.
115468 */
115469 SQLITE_PRIVATE int sqlite3Fts3SegReaderCost(
115470   Fts3Cursor *pCsr,               /* FTS3 cursor handle */
115471   Fts3SegReader *pReader,         /* Segment-reader handle */
115472   int *pnCost                     /* IN/OUT: Number of bytes read */
115473 ){
115474   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
115475   int rc = SQLITE_OK;             /* Return code */
115476   int nCost = 0;                  /* Cost in bytes to return */
115477   int pgsz = p->nPgsz;            /* Database page size */
115478
115479   /* If this seg-reader is reading the pending-terms table, or if all data
115480   ** for the segment is stored on the root page of the b-tree, then the cost
115481   ** is zero. In this case all required data is already in main memory.
115482   */
115483   if( p->bHasStat 
115484    && !fts3SegReaderIsPending(pReader) 
115485    && !fts3SegReaderIsRootOnly(pReader) 
115486   ){
115487     int nBlob = 0;
115488     sqlite3_int64 iBlock;
115489
115490     if( pCsr->nRowAvg==0 ){
115491       /* The average document size, which is required to calculate the cost
115492       ** of each doclist, has not yet been determined. Read the required 
115493       ** data from the %_stat table to calculate it.
115494       **
115495       ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
115496       ** varints, where nCol is the number of columns in the FTS3 table.
115497       ** The first varint is the number of documents currently stored in
115498       ** the table. The following nCol varints contain the total amount of
115499       ** data stored in all rows of each column of the table, from left
115500       ** to right.
115501       */
115502       sqlite3_stmt *pStmt;
115503       rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
115504       if( rc ) return rc;
115505       if( sqlite3_step(pStmt)==SQLITE_ROW ){
115506         sqlite3_int64 nDoc = 0;
115507         sqlite3_int64 nByte = 0;
115508         const char *a = sqlite3_column_blob(pStmt, 0);
115509         if( a ){
115510           const char *pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
115511           a += sqlite3Fts3GetVarint(a, &nDoc);
115512           while( a<pEnd ){
115513             a += sqlite3Fts3GetVarint(a, &nByte);
115514           }
115515         }
115516
115517         pCsr->nRowAvg = (int)(((nByte / nDoc) + pgsz - 1) / pgsz);
115518       }
115519       rc = sqlite3_reset(pStmt);
115520       if( rc!=SQLITE_OK || pCsr->nRowAvg==0 ) return rc;
115521     }
115522
115523     /* Assume that a blob flows over onto overflow pages if it is larger
115524     ** than (pgsz-35) bytes in size (the file-format documentation
115525     ** confirms this).
115526     */
115527     for(iBlock=pReader->iStartBlock; iBlock<=pReader->iLeafEndBlock; iBlock++){
115528       rc = sqlite3Fts3ReadBlock(p, iBlock, 0, &nBlob);
115529       if( rc!=SQLITE_OK ) break;
115530       if( (nBlob+35)>pgsz ){
115531         int nOvfl = (nBlob + 34)/pgsz;
115532         nCost += ((nOvfl + pCsr->nRowAvg - 1)/pCsr->nRowAvg);
115533       }
115534     }
115535   }
115536
115537   *pnCost += nCost;
115538   return rc;
115539 }
115540
115541 /*
115542 ** Free all allocations associated with the iterator passed as the 
115543 ** second argument.
115544 */
115545 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
115546   if( pReader && !fts3SegReaderIsPending(pReader) ){
115547     sqlite3_free(pReader->zTerm);
115548     if( !fts3SegReaderIsRootOnly(pReader) ){
115549       sqlite3_free(pReader->aNode);
115550     }
115551   }
115552   sqlite3_free(pReader);
115553 }
115554
115555 /*
115556 ** Allocate a new SegReader object.
115557 */
115558 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
115559   int iAge,                       /* Segment "age". */
115560   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
115561   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
115562   sqlite3_int64 iEndBlock,        /* Final block of segment */
115563   const char *zRoot,              /* Buffer containing root node */
115564   int nRoot,                      /* Size of buffer containing root node */
115565   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
115566 ){
115567   int rc = SQLITE_OK;             /* Return code */
115568   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
115569   int nExtra = 0;                 /* Bytes to allocate segment root node */
115570
115571   assert( iStartLeaf<=iEndLeaf );
115572   if( iStartLeaf==0 ){
115573     nExtra = nRoot + FTS3_NODE_PADDING;
115574   }
115575
115576   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
115577   if( !pReader ){
115578     return SQLITE_NOMEM;
115579   }
115580   memset(pReader, 0, sizeof(Fts3SegReader));
115581   pReader->iIdx = iAge;
115582   pReader->iStartBlock = iStartLeaf;
115583   pReader->iLeafEndBlock = iEndLeaf;
115584   pReader->iEndBlock = iEndBlock;
115585
115586   if( nExtra ){
115587     /* The entire segment is stored in the root node. */
115588     pReader->aNode = (char *)&pReader[1];
115589     pReader->nNode = nRoot;
115590     memcpy(pReader->aNode, zRoot, nRoot);
115591     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
115592   }else{
115593     pReader->iCurrentBlock = iStartLeaf-1;
115594   }
115595
115596   if( rc==SQLITE_OK ){
115597     *ppReader = pReader;
115598   }else{
115599     sqlite3Fts3SegReaderFree(pReader);
115600   }
115601   return rc;
115602 }
115603
115604 /*
115605 ** This is a comparison function used as a qsort() callback when sorting
115606 ** an array of pending terms by term. This occurs as part of flushing
115607 ** the contents of the pending-terms hash table to the database.
115608 */
115609 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
115610   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
115611   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
115612   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
115613   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
115614
115615   int n = (n1<n2 ? n1 : n2);
115616   int c = memcmp(z1, z2, n);
115617   if( c==0 ){
115618     c = n1 - n2;
115619   }
115620   return c;
115621 }
115622
115623 /*
115624 ** This function is used to allocate an Fts3SegReader that iterates through
115625 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
115626 */
115627 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
115628   Fts3Table *p,                   /* Virtual table handle */
115629   const char *zTerm,              /* Term to search for */
115630   int nTerm,                      /* Size of buffer zTerm */
115631   int isPrefix,                   /* True for a term-prefix query */
115632   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
115633 ){
115634   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
115635   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
115636   int nElem = 0;                  /* Size of array at aElem */
115637   int rc = SQLITE_OK;             /* Return Code */
115638
115639   if( isPrefix ){
115640     int nAlloc = 0;               /* Size of allocated array at aElem */
115641     Fts3HashElem *pE = 0;         /* Iterator variable */
115642
115643     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
115644       char *zKey = (char *)fts3HashKey(pE);
115645       int nKey = fts3HashKeysize(pE);
115646       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
115647         if( nElem==nAlloc ){
115648           Fts3HashElem **aElem2;
115649           nAlloc += 16;
115650           aElem2 = (Fts3HashElem **)sqlite3_realloc(
115651               aElem, nAlloc*sizeof(Fts3HashElem *)
115652           );
115653           if( !aElem2 ){
115654             rc = SQLITE_NOMEM;
115655             nElem = 0;
115656             break;
115657           }
115658           aElem = aElem2;
115659         }
115660         aElem[nElem++] = pE;
115661       }
115662     }
115663
115664     /* If more than one term matches the prefix, sort the Fts3HashElem
115665     ** objects in term order using qsort(). This uses the same comparison
115666     ** callback as is used when flushing terms to disk.
115667     */
115668     if( nElem>1 ){
115669       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
115670     }
115671
115672   }else{
115673     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
115674     if( pE ){
115675       aElem = &pE;
115676       nElem = 1;
115677     }
115678   }
115679
115680   if( nElem>0 ){
115681     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
115682     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
115683     if( !pReader ){
115684       rc = SQLITE_NOMEM;
115685     }else{
115686       memset(pReader, 0, nByte);
115687       pReader->iIdx = 0x7FFFFFFF;
115688       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
115689       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
115690     }
115691   }
115692
115693   if( isPrefix ){
115694     sqlite3_free(aElem);
115695   }
115696   *ppReader = pReader;
115697   return rc;
115698 }
115699
115700
115701 /*
115702 ** The second argument to this function is expected to be a statement of
115703 ** the form:
115704 **
115705 **   SELECT 
115706 **     idx,                  -- col 0
115707 **     start_block,          -- col 1
115708 **     leaves_end_block,     -- col 2
115709 **     end_block,            -- col 3
115710 **     root                  -- col 4
115711 **   FROM %_segdir ...
115712 **
115713 ** This function allocates and initializes a Fts3SegReader structure to
115714 ** iterate through the terms stored in the segment identified by the
115715 ** current row that pStmt is pointing to. 
115716 **
115717 ** If successful, the Fts3SegReader is left pointing to the first term
115718 ** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
115719 ** code is returned.
115720 */
115721 static int fts3SegReaderNew(
115722   sqlite3_stmt *pStmt,            /* See above */
115723   int iAge,                       /* Segment "age". */
115724   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
115725 ){
115726   return sqlite3Fts3SegReaderNew(iAge, 
115727       sqlite3_column_int64(pStmt, 1),
115728       sqlite3_column_int64(pStmt, 2),
115729       sqlite3_column_int64(pStmt, 3),
115730       sqlite3_column_blob(pStmt, 4),
115731       sqlite3_column_bytes(pStmt, 4),
115732       ppReader
115733   );
115734 }
115735
115736 /*
115737 ** Compare the entries pointed to by two Fts3SegReader structures. 
115738 ** Comparison is as follows:
115739 **
115740 **   1) EOF is greater than not EOF.
115741 **
115742 **   2) The current terms (if any) are compared using memcmp(). If one
115743 **      term is a prefix of another, the longer term is considered the
115744 **      larger.
115745 **
115746 **   3) By segment age. An older segment is considered larger.
115747 */
115748 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
115749   int rc;
115750   if( pLhs->aNode && pRhs->aNode ){
115751     int rc2 = pLhs->nTerm - pRhs->nTerm;
115752     if( rc2<0 ){
115753       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
115754     }else{
115755       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
115756     }
115757     if( rc==0 ){
115758       rc = rc2;
115759     }
115760   }else{
115761     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
115762   }
115763   if( rc==0 ){
115764     rc = pRhs->iIdx - pLhs->iIdx;
115765   }
115766   assert( rc!=0 );
115767   return rc;
115768 }
115769
115770 /*
115771 ** A different comparison function for SegReader structures. In this
115772 ** version, it is assumed that each SegReader points to an entry in
115773 ** a doclist for identical terms. Comparison is made as follows:
115774 **
115775 **   1) EOF (end of doclist in this case) is greater than not EOF.
115776 **
115777 **   2) By current docid.
115778 **
115779 **   3) By segment age. An older segment is considered larger.
115780 */
115781 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
115782   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
115783   if( rc==0 ){
115784     if( pLhs->iDocid==pRhs->iDocid ){
115785       rc = pRhs->iIdx - pLhs->iIdx;
115786     }else{
115787       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
115788     }
115789   }
115790   assert( pLhs->aNode && pRhs->aNode );
115791   return rc;
115792 }
115793
115794 /*
115795 ** Compare the term that the Fts3SegReader object passed as the first argument
115796 ** points to with the term specified by arguments zTerm and nTerm. 
115797 **
115798 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
115799 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
115800 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
115801 */
115802 static int fts3SegReaderTermCmp(
115803   Fts3SegReader *pSeg,            /* Segment reader object */
115804   const char *zTerm,              /* Term to compare to */
115805   int nTerm                       /* Size of term zTerm in bytes */
115806 ){
115807   int res = 0;
115808   if( pSeg->aNode ){
115809     if( pSeg->nTerm>nTerm ){
115810       res = memcmp(pSeg->zTerm, zTerm, nTerm);
115811     }else{
115812       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
115813     }
115814     if( res==0 ){
115815       res = pSeg->nTerm-nTerm;
115816     }
115817   }
115818   return res;
115819 }
115820
115821 /*
115822 ** Argument apSegment is an array of nSegment elements. It is known that
115823 ** the final (nSegment-nSuspect) members are already in sorted order
115824 ** (according to the comparison function provided). This function shuffles
115825 ** the array around until all entries are in sorted order.
115826 */
115827 static void fts3SegReaderSort(
115828   Fts3SegReader **apSegment,                     /* Array to sort entries of */
115829   int nSegment,                                  /* Size of apSegment array */
115830   int nSuspect,                                  /* Unsorted entry count */
115831   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
115832 ){
115833   int i;                          /* Iterator variable */
115834
115835   assert( nSuspect<=nSegment );
115836
115837   if( nSuspect==nSegment ) nSuspect--;
115838   for(i=nSuspect-1; i>=0; i--){
115839     int j;
115840     for(j=i; j<(nSegment-1); j++){
115841       Fts3SegReader *pTmp;
115842       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
115843       pTmp = apSegment[j+1];
115844       apSegment[j+1] = apSegment[j];
115845       apSegment[j] = pTmp;
115846     }
115847   }
115848
115849 #ifndef NDEBUG
115850   /* Check that the list really is sorted now. */
115851   for(i=0; i<(nSuspect-1); i++){
115852     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
115853   }
115854 #endif
115855 }
115856
115857 /* 
115858 ** Insert a record into the %_segments table.
115859 */
115860 static int fts3WriteSegment(
115861   Fts3Table *p,                   /* Virtual table handle */
115862   sqlite3_int64 iBlock,           /* Block id for new block */
115863   char *z,                        /* Pointer to buffer containing block data */
115864   int n                           /* Size of buffer z in bytes */
115865 ){
115866   sqlite3_stmt *pStmt;
115867   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
115868   if( rc==SQLITE_OK ){
115869     sqlite3_bind_int64(pStmt, 1, iBlock);
115870     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
115871     sqlite3_step(pStmt);
115872     rc = sqlite3_reset(pStmt);
115873   }
115874   return rc;
115875 }
115876
115877 /* 
115878 ** Insert a record into the %_segdir table.
115879 */
115880 static int fts3WriteSegdir(
115881   Fts3Table *p,                   /* Virtual table handle */
115882   int iLevel,                     /* Value for "level" field */
115883   int iIdx,                       /* Value for "idx" field */
115884   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
115885   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
115886   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
115887   char *zRoot,                    /* Blob value for "root" field */
115888   int nRoot                       /* Number of bytes in buffer zRoot */
115889 ){
115890   sqlite3_stmt *pStmt;
115891   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
115892   if( rc==SQLITE_OK ){
115893     sqlite3_bind_int(pStmt, 1, iLevel);
115894     sqlite3_bind_int(pStmt, 2, iIdx);
115895     sqlite3_bind_int64(pStmt, 3, iStartBlock);
115896     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
115897     sqlite3_bind_int64(pStmt, 5, iEndBlock);
115898     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
115899     sqlite3_step(pStmt);
115900     rc = sqlite3_reset(pStmt);
115901   }
115902   return rc;
115903 }
115904
115905 /*
115906 ** Return the size of the common prefix (if any) shared by zPrev and
115907 ** zNext, in bytes. For example, 
115908 **
115909 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
115910 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
115911 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
115912 */
115913 static int fts3PrefixCompress(
115914   const char *zPrev,              /* Buffer containing previous term */
115915   int nPrev,                      /* Size of buffer zPrev in bytes */
115916   const char *zNext,              /* Buffer containing next term */
115917   int nNext                       /* Size of buffer zNext in bytes */
115918 ){
115919   int n;
115920   UNUSED_PARAMETER(nNext);
115921   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
115922   return n;
115923 }
115924
115925 /*
115926 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
115927 ** (according to memcmp) than the previous term.
115928 */
115929 static int fts3NodeAddTerm(
115930   Fts3Table *p,                   /* Virtual table handle */
115931   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
115932   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
115933   const char *zTerm,              /* Pointer to buffer containing term */
115934   int nTerm                       /* Size of term in bytes */
115935 ){
115936   SegmentNode *pTree = *ppTree;
115937   int rc;
115938   SegmentNode *pNew;
115939
115940   /* First try to append the term to the current node. Return early if 
115941   ** this is possible.
115942   */
115943   if( pTree ){
115944     int nData = pTree->nData;     /* Current size of node in bytes */
115945     int nReq = nData;             /* Required space after adding zTerm */
115946     int nPrefix;                  /* Number of bytes of prefix compression */
115947     int nSuffix;                  /* Suffix length */
115948
115949     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
115950     nSuffix = nTerm-nPrefix;
115951
115952     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
115953     if( nReq<=p->nNodeSize || !pTree->zTerm ){
115954
115955       if( nReq>p->nNodeSize ){
115956         /* An unusual case: this is the first term to be added to the node
115957         ** and the static node buffer (p->nNodeSize bytes) is not large
115958         ** enough. Use a separately malloced buffer instead This wastes
115959         ** p->nNodeSize bytes, but since this scenario only comes about when
115960         ** the database contain two terms that share a prefix of almost 2KB, 
115961         ** this is not expected to be a serious problem. 
115962         */
115963         assert( pTree->aData==(char *)&pTree[1] );
115964         pTree->aData = (char *)sqlite3_malloc(nReq);
115965         if( !pTree->aData ){
115966           return SQLITE_NOMEM;
115967         }
115968       }
115969
115970       if( pTree->zTerm ){
115971         /* There is no prefix-length field for first term in a node */
115972         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
115973       }
115974
115975       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
115976       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
115977       pTree->nData = nData + nSuffix;
115978       pTree->nEntry++;
115979
115980       if( isCopyTerm ){
115981         if( pTree->nMalloc<nTerm ){
115982           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
115983           if( !zNew ){
115984             return SQLITE_NOMEM;
115985           }
115986           pTree->nMalloc = nTerm*2;
115987           pTree->zMalloc = zNew;
115988         }
115989         pTree->zTerm = pTree->zMalloc;
115990         memcpy(pTree->zTerm, zTerm, nTerm);
115991         pTree->nTerm = nTerm;
115992       }else{
115993         pTree->zTerm = (char *)zTerm;
115994         pTree->nTerm = nTerm;
115995       }
115996       return SQLITE_OK;
115997     }
115998   }
115999
116000   /* If control flows to here, it was not possible to append zTerm to the
116001   ** current node. Create a new node (a right-sibling of the current node).
116002   ** If this is the first node in the tree, the term is added to it.
116003   **
116004   ** Otherwise, the term is not added to the new node, it is left empty for
116005   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
116006   ** has no parent, one is created here.
116007   */
116008   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
116009   if( !pNew ){
116010     return SQLITE_NOMEM;
116011   }
116012   memset(pNew, 0, sizeof(SegmentNode));
116013   pNew->nData = 1 + FTS3_VARINT_MAX;
116014   pNew->aData = (char *)&pNew[1];
116015
116016   if( pTree ){
116017     SegmentNode *pParent = pTree->pParent;
116018     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
116019     if( pTree->pParent==0 ){
116020       pTree->pParent = pParent;
116021     }
116022     pTree->pRight = pNew;
116023     pNew->pLeftmost = pTree->pLeftmost;
116024     pNew->pParent = pParent;
116025     pNew->zMalloc = pTree->zMalloc;
116026     pNew->nMalloc = pTree->nMalloc;
116027     pTree->zMalloc = 0;
116028   }else{
116029     pNew->pLeftmost = pNew;
116030     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
116031   }
116032
116033   *ppTree = pNew;
116034   return rc;
116035 }
116036
116037 /*
116038 ** Helper function for fts3NodeWrite().
116039 */
116040 static int fts3TreeFinishNode(
116041   SegmentNode *pTree, 
116042   int iHeight, 
116043   sqlite3_int64 iLeftChild
116044 ){
116045   int nStart;
116046   assert( iHeight>=1 && iHeight<128 );
116047   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
116048   pTree->aData[nStart] = (char)iHeight;
116049   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
116050   return nStart;
116051 }
116052
116053 /*
116054 ** Write the buffer for the segment node pTree and all of its peers to the
116055 ** database. Then call this function recursively to write the parent of 
116056 ** pTree and its peers to the database. 
116057 **
116058 ** Except, if pTree is a root node, do not write it to the database. Instead,
116059 ** set output variables *paRoot and *pnRoot to contain the root node.
116060 **
116061 ** If successful, SQLITE_OK is returned and output variable *piLast is
116062 ** set to the largest blockid written to the database (or zero if no
116063 ** blocks were written to the db). Otherwise, an SQLite error code is 
116064 ** returned.
116065 */
116066 static int fts3NodeWrite(
116067   Fts3Table *p,                   /* Virtual table handle */
116068   SegmentNode *pTree,             /* SegmentNode handle */
116069   int iHeight,                    /* Height of this node in tree */
116070   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
116071   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
116072   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
116073   char **paRoot,                  /* OUT: Data for root node */
116074   int *pnRoot                     /* OUT: Size of root node in bytes */
116075 ){
116076   int rc = SQLITE_OK;
116077
116078   if( !pTree->pParent ){
116079     /* Root node of the tree. */
116080     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
116081     *piLast = iFree-1;
116082     *pnRoot = pTree->nData - nStart;
116083     *paRoot = &pTree->aData[nStart];
116084   }else{
116085     SegmentNode *pIter;
116086     sqlite3_int64 iNextFree = iFree;
116087     sqlite3_int64 iNextLeaf = iLeaf;
116088     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
116089       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
116090       int nWrite = pIter->nData - nStart;
116091   
116092       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
116093       iNextFree++;
116094       iNextLeaf += (pIter->nEntry+1);
116095     }
116096     if( rc==SQLITE_OK ){
116097       assert( iNextLeaf==iFree );
116098       rc = fts3NodeWrite(
116099           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
116100       );
116101     }
116102   }
116103
116104   return rc;
116105 }
116106
116107 /*
116108 ** Free all memory allocations associated with the tree pTree.
116109 */
116110 static void fts3NodeFree(SegmentNode *pTree){
116111   if( pTree ){
116112     SegmentNode *p = pTree->pLeftmost;
116113     fts3NodeFree(p->pParent);
116114     while( p ){
116115       SegmentNode *pRight = p->pRight;
116116       if( p->aData!=(char *)&p[1] ){
116117         sqlite3_free(p->aData);
116118       }
116119       assert( pRight==0 || p->zMalloc==0 );
116120       sqlite3_free(p->zMalloc);
116121       sqlite3_free(p);
116122       p = pRight;
116123     }
116124   }
116125 }
116126
116127 /*
116128 ** Add a term to the segment being constructed by the SegmentWriter object
116129 ** *ppWriter. When adding the first term to a segment, *ppWriter should
116130 ** be passed NULL. This function will allocate a new SegmentWriter object
116131 ** and return it via the input/output variable *ppWriter in this case.
116132 **
116133 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
116134 */
116135 static int fts3SegWriterAdd(
116136   Fts3Table *p,                   /* Virtual table handle */
116137   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
116138   int isCopyTerm,                 /* True if buffer zTerm must be copied */
116139   const char *zTerm,              /* Pointer to buffer containing term */
116140   int nTerm,                      /* Size of term in bytes */
116141   const char *aDoclist,           /* Pointer to buffer containing doclist */
116142   int nDoclist                    /* Size of doclist in bytes */
116143 ){
116144   int nPrefix;                    /* Size of term prefix in bytes */
116145   int nSuffix;                    /* Size of term suffix in bytes */
116146   int nReq;                       /* Number of bytes required on leaf page */
116147   int nData;
116148   SegmentWriter *pWriter = *ppWriter;
116149
116150   if( !pWriter ){
116151     int rc;
116152     sqlite3_stmt *pStmt;
116153
116154     /* Allocate the SegmentWriter structure */
116155     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
116156     if( !pWriter ) return SQLITE_NOMEM;
116157     memset(pWriter, 0, sizeof(SegmentWriter));
116158     *ppWriter = pWriter;
116159
116160     /* Allocate a buffer in which to accumulate data */
116161     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
116162     if( !pWriter->aData ) return SQLITE_NOMEM;
116163     pWriter->nSize = p->nNodeSize;
116164
116165     /* Find the next free blockid in the %_segments table */
116166     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
116167     if( rc!=SQLITE_OK ) return rc;
116168     if( SQLITE_ROW==sqlite3_step(pStmt) ){
116169       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
116170       pWriter->iFirst = pWriter->iFree;
116171     }
116172     rc = sqlite3_reset(pStmt);
116173     if( rc!=SQLITE_OK ) return rc;
116174   }
116175   nData = pWriter->nData;
116176
116177   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
116178   nSuffix = nTerm-nPrefix;
116179
116180   /* Figure out how many bytes are required by this new entry */
116181   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
116182     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
116183     nSuffix +                               /* Term suffix */
116184     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
116185     nDoclist;                               /* Doclist data */
116186
116187   if( nData>0 && nData+nReq>p->nNodeSize ){
116188     int rc;
116189
116190     /* The current leaf node is full. Write it out to the database. */
116191     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
116192     if( rc!=SQLITE_OK ) return rc;
116193
116194     /* Add the current term to the interior node tree. The term added to
116195     ** the interior tree must:
116196     **
116197     **   a) be greater than the largest term on the leaf node just written
116198     **      to the database (still available in pWriter->zTerm), and
116199     **
116200     **   b) be less than or equal to the term about to be added to the new
116201     **      leaf node (zTerm/nTerm).
116202     **
116203     ** In other words, it must be the prefix of zTerm 1 byte longer than
116204     ** the common prefix (if any) of zTerm and pWriter->zTerm.
116205     */
116206     assert( nPrefix<nTerm );
116207     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
116208     if( rc!=SQLITE_OK ) return rc;
116209
116210     nData = 0;
116211     pWriter->nTerm = 0;
116212
116213     nPrefix = 0;
116214     nSuffix = nTerm;
116215     nReq = 1 +                              /* varint containing prefix size */
116216       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
116217       nTerm +                               /* Term suffix */
116218       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
116219       nDoclist;                             /* Doclist data */
116220   }
116221
116222   /* If the buffer currently allocated is too small for this entry, realloc
116223   ** the buffer to make it large enough.
116224   */
116225   if( nReq>pWriter->nSize ){
116226     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
116227     if( !aNew ) return SQLITE_NOMEM;
116228     pWriter->aData = aNew;
116229     pWriter->nSize = nReq;
116230   }
116231   assert( nData+nReq<=pWriter->nSize );
116232
116233   /* Append the prefix-compressed term and doclist to the buffer. */
116234   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
116235   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
116236   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
116237   nData += nSuffix;
116238   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
116239   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
116240   pWriter->nData = nData + nDoclist;
116241
116242   /* Save the current term so that it can be used to prefix-compress the next.
116243   ** If the isCopyTerm parameter is true, then the buffer pointed to by
116244   ** zTerm is transient, so take a copy of the term data. Otherwise, just
116245   ** store a copy of the pointer.
116246   */
116247   if( isCopyTerm ){
116248     if( nTerm>pWriter->nMalloc ){
116249       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
116250       if( !zNew ){
116251         return SQLITE_NOMEM;
116252       }
116253       pWriter->nMalloc = nTerm*2;
116254       pWriter->zMalloc = zNew;
116255       pWriter->zTerm = zNew;
116256     }
116257     assert( pWriter->zTerm==pWriter->zMalloc );
116258     memcpy(pWriter->zTerm, zTerm, nTerm);
116259   }else{
116260     pWriter->zTerm = (char *)zTerm;
116261   }
116262   pWriter->nTerm = nTerm;
116263
116264   return SQLITE_OK;
116265 }
116266
116267 /*
116268 ** Flush all data associated with the SegmentWriter object pWriter to the
116269 ** database. This function must be called after all terms have been added
116270 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
116271 ** returned. Otherwise, an SQLite error code.
116272 */
116273 static int fts3SegWriterFlush(
116274   Fts3Table *p,                   /* Virtual table handle */
116275   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
116276   int iLevel,                     /* Value for 'level' column of %_segdir */
116277   int iIdx                        /* Value for 'idx' column of %_segdir */
116278 ){
116279   int rc;                         /* Return code */
116280   if( pWriter->pTree ){
116281     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
116282     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
116283     char *zRoot = NULL;           /* Pointer to buffer containing root node */
116284     int nRoot = 0;                /* Size of buffer zRoot */
116285
116286     iLastLeaf = pWriter->iFree;
116287     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
116288     if( rc==SQLITE_OK ){
116289       rc = fts3NodeWrite(p, pWriter->pTree, 1,
116290           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
116291     }
116292     if( rc==SQLITE_OK ){
116293       rc = fts3WriteSegdir(
116294           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
116295     }
116296   }else{
116297     /* The entire tree fits on the root node. Write it to the segdir table. */
116298     rc = fts3WriteSegdir(
116299         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
116300   }
116301   return rc;
116302 }
116303
116304 /*
116305 ** Release all memory held by the SegmentWriter object passed as the 
116306 ** first argument.
116307 */
116308 static void fts3SegWriterFree(SegmentWriter *pWriter){
116309   if( pWriter ){
116310     sqlite3_free(pWriter->aData);
116311     sqlite3_free(pWriter->zMalloc);
116312     fts3NodeFree(pWriter->pTree);
116313     sqlite3_free(pWriter);
116314   }
116315 }
116316
116317 /*
116318 ** The first value in the apVal[] array is assumed to contain an integer.
116319 ** This function tests if there exist any documents with docid values that
116320 ** are different from that integer. i.e. if deleting the document with docid
116321 ** apVal[0] would mean the FTS3 table were empty.
116322 **
116323 ** If successful, *pisEmpty is set to true if the table is empty except for
116324 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
116325 ** error occurs, an SQLite error code is returned.
116326 */
116327 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
116328   sqlite3_stmt *pStmt;
116329   int rc;
116330   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
116331   if( rc==SQLITE_OK ){
116332     if( SQLITE_ROW==sqlite3_step(pStmt) ){
116333       *pisEmpty = sqlite3_column_int(pStmt, 0);
116334     }
116335     rc = sqlite3_reset(pStmt);
116336   }
116337   return rc;
116338 }
116339
116340 /*
116341 ** Set *pnSegment to the number of segments of level iLevel in the database.
116342 **
116343 ** Return SQLITE_OK if successful, or an SQLite error code if not.
116344 */
116345 static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
116346   sqlite3_stmt *pStmt;
116347   int rc;
116348
116349   assert( iLevel>=0 );
116350   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
116351   if( rc!=SQLITE_OK ) return rc;
116352   sqlite3_bind_int(pStmt, 1, iLevel);
116353   if( SQLITE_ROW==sqlite3_step(pStmt) ){
116354     *pnSegment = sqlite3_column_int(pStmt, 0);
116355   }
116356   return sqlite3_reset(pStmt);
116357 }
116358
116359 /*
116360 ** Set *pnSegment to the total number of segments in the database. Set
116361 ** *pnMax to the largest segment level in the database (segment levels
116362 ** are stored in the 'level' column of the %_segdir table).
116363 **
116364 ** Return SQLITE_OK if successful, or an SQLite error code if not.
116365 */
116366 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
116367   sqlite3_stmt *pStmt;
116368   int rc;
116369
116370   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
116371   if( rc!=SQLITE_OK ) return rc;
116372   if( SQLITE_ROW==sqlite3_step(pStmt) ){
116373     *pnSegment = sqlite3_column_int(pStmt, 0);
116374     *pnMax = sqlite3_column_int(pStmt, 1);
116375   }
116376   return sqlite3_reset(pStmt);
116377 }
116378
116379 /*
116380 ** This function is used after merging multiple segments into a single large
116381 ** segment to delete the old, now redundant, segment b-trees. Specifically,
116382 ** it:
116383 ** 
116384 **   1) Deletes all %_segments entries for the segments associated with 
116385 **      each of the SegReader objects in the array passed as the third 
116386 **      argument, and
116387 **
116388 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
116389 **      entries regardless of level if (iLevel<0).
116390 **
116391 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
116392 */
116393 static int fts3DeleteSegdir(
116394   Fts3Table *p,                   /* Virtual table handle */
116395   int iLevel,                     /* Level of %_segdir entries to delete */
116396   Fts3SegReader **apSegment,      /* Array of SegReader objects */
116397   int nReader                     /* Size of array apSegment */
116398 ){
116399   int rc;                         /* Return Code */
116400   int i;                          /* Iterator variable */
116401   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
116402
116403   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
116404   for(i=0; rc==SQLITE_OK && i<nReader; i++){
116405     Fts3SegReader *pSegment = apSegment[i];
116406     if( pSegment->iStartBlock ){
116407       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
116408       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
116409       sqlite3_step(pDelete);
116410       rc = sqlite3_reset(pDelete);
116411     }
116412   }
116413   if( rc!=SQLITE_OK ){
116414     return rc;
116415   }
116416
116417   if( iLevel>=0 ){
116418     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
116419     if( rc==SQLITE_OK ){
116420       sqlite3_bind_int(pDelete, 1, iLevel);
116421       sqlite3_step(pDelete);
116422       rc = sqlite3_reset(pDelete);
116423     }
116424   }else{
116425     fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
116426   }
116427
116428   return rc;
116429 }
116430
116431 /*
116432 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
116433 ** a position list that may (or may not) feature multiple columns. This
116434 ** function adjusts the pointer *ppList and the length *pnList so that they
116435 ** identify the subset of the position list that corresponds to column iCol.
116436 **
116437 ** If there are no entries in the input position list for column iCol, then
116438 ** *pnList is set to zero before returning.
116439 */
116440 static void fts3ColumnFilter(
116441   int iCol,                       /* Column to filter on */
116442   char **ppList,                  /* IN/OUT: Pointer to position list */
116443   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
116444 ){
116445   char *pList = *ppList;
116446   int nList = *pnList;
116447   char *pEnd = &pList[nList];
116448   int iCurrent = 0;
116449   char *p = pList;
116450
116451   assert( iCol>=0 );
116452   while( 1 ){
116453     char c = 0;
116454     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
116455   
116456     if( iCol==iCurrent ){
116457       nList = (int)(p - pList);
116458       break;
116459     }
116460
116461     nList -= (int)(p - pList);
116462     pList = p;
116463     if( nList==0 ){
116464       break;
116465     }
116466     p = &pList[1];
116467     p += sqlite3Fts3GetVarint32(p, &iCurrent);
116468   }
116469
116470   *ppList = pList;
116471   *pnList = nList;
116472 }
116473
116474 /*
116475 ** sqlite3Fts3SegReaderIterate() callback used when merging multiple 
116476 ** segments to create a single, larger segment.
116477 */
116478 static int fts3MergeCallback(
116479   Fts3Table *p,                   /* FTS3 Virtual table handle */
116480   void *pContext,                 /* Pointer to SegmentWriter* to write with */
116481   char *zTerm,                    /* Term to write to the db */
116482   int nTerm,                      /* Number of bytes in zTerm */
116483   char *aDoclist,                 /* Doclist associated with zTerm */
116484   int nDoclist                    /* Number of bytes in doclist */
116485 ){
116486   SegmentWriter **ppW = (SegmentWriter **)pContext;
116487   return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
116488 }
116489
116490 /*
116491 ** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
116492 ** of the pending-terms hash table to the database.
116493 */
116494 static int fts3FlushCallback(
116495   Fts3Table *p,                   /* FTS3 Virtual table handle */
116496   void *pContext,                 /* Pointer to SegmentWriter* to write with */
116497   char *zTerm,                    /* Term to write to the db */
116498   int nTerm,                      /* Number of bytes in zTerm */
116499   char *aDoclist,                 /* Doclist associated with zTerm */
116500   int nDoclist                    /* Number of bytes in doclist */
116501 ){
116502   SegmentWriter **ppW = (SegmentWriter **)pContext;
116503   return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
116504 }
116505
116506 /*
116507 ** This function is used to iterate through a contiguous set of terms 
116508 ** stored in the full-text index. It merges data contained in one or 
116509 ** more segments to support this.
116510 **
116511 ** The second argument is passed an array of pointers to SegReader objects
116512 ** allocated with sqlite3Fts3SegReaderNew(). This function merges the range 
116513 ** of terms selected by each SegReader. If a single term is present in
116514 ** more than one segment, the associated doclists are merged. For each
116515 ** term and (possibly merged) doclist in the merged range, the callback
116516 ** function xFunc is invoked with its arguments set as follows.
116517 **
116518 **   arg 0: Copy of 'p' parameter passed to this function
116519 **   arg 1: Copy of 'pContext' parameter passed to this function
116520 **   arg 2: Pointer to buffer containing term
116521 **   arg 3: Size of arg 2 buffer in bytes
116522 **   arg 4: Pointer to buffer containing doclist
116523 **   arg 5: Size of arg 2 buffer in bytes
116524 **
116525 ** The 4th argument to this function is a pointer to a structure of type
116526 ** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
116527 ** further restrict the range of terms that callbacks are made for and
116528 ** modify the behaviour of this function. See comments above structure
116529 ** definition for details.
116530 */
116531 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
116532   Fts3Table *p,                   /* Virtual table handle */
116533   Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
116534   int nSegment,                   /* Size of apSegment array */
116535   Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
116536   int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
116537   void *pContext                  /* Callback context (2nd argument) */
116538 ){
116539   int i;                          /* Iterator variable */
116540   char *aBuffer = 0;              /* Buffer to merge doclists in */
116541   int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
116542   int rc = SQLITE_OK;             /* Return code */
116543
116544   int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
116545   int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
116546   int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
116547   int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
116548
116549   /* If there are zero segments, this function is a no-op. This scenario
116550   ** comes about only when reading from an empty database.
116551   */
116552   if( nSegment==0 ) goto finished;
116553
116554   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
116555   ** for, then advance each segment iterator until it points to a term of
116556   ** equal or greater value than the specified term. This prevents many
116557   ** unnecessary merge/sort operations for the case where single segment
116558   ** b-tree leaf nodes contain more than one term.
116559   */
116560   for(i=0; i<nSegment; i++){
116561     int nTerm = pFilter->nTerm;
116562     const char *zTerm = pFilter->zTerm;
116563     Fts3SegReader *pSeg = apSegment[i];
116564     do {
116565       rc = fts3SegReaderNext(p, pSeg);
116566       if( rc!=SQLITE_OK ) goto finished;
116567     }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
116568   }
116569
116570   fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
116571   while( apSegment[0]->aNode ){
116572     int nTerm = apSegment[0]->nTerm;
116573     char *zTerm = apSegment[0]->zTerm;
116574     int nMerge = 1;
116575
116576     /* If this is a prefix-search, and if the term that apSegment[0] points
116577     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
116578     ** required callbacks have been made. In this case exit early.
116579     **
116580     ** Similarly, if this is a search for an exact match, and the first term
116581     ** of segment apSegment[0] is not a match, exit early.
116582     */
116583     if( pFilter->zTerm ){
116584       if( nTerm<pFilter->nTerm 
116585        || (!isPrefix && nTerm>pFilter->nTerm)
116586        || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm) 
116587     ){
116588         goto finished;
116589       }
116590     }
116591
116592     while( nMerge<nSegment 
116593         && apSegment[nMerge]->aNode
116594         && apSegment[nMerge]->nTerm==nTerm 
116595         && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
116596     ){
116597       nMerge++;
116598     }
116599
116600     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
116601     if( nMerge==1 && !isIgnoreEmpty ){
116602       Fts3SegReader *p0 = apSegment[0];
116603       rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
116604       if( rc!=SQLITE_OK ) goto finished;
116605     }else{
116606       int nDoclist = 0;           /* Size of doclist */
116607       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
116608
116609       /* The current term of the first nMerge entries in the array
116610       ** of Fts3SegReader objects is the same. The doclists must be merged
116611       ** and a single term added to the new segment.
116612       */
116613       for(i=0; i<nMerge; i++){
116614         fts3SegReaderFirstDocid(apSegment[i]);
116615       }
116616       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
116617       while( apSegment[0]->pOffsetList ){
116618         int j;                    /* Number of segments that share a docid */
116619         char *pList;
116620         int nList;
116621         int nByte;
116622         sqlite3_int64 iDocid = apSegment[0]->iDocid;
116623         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
116624         j = 1;
116625         while( j<nMerge
116626             && apSegment[j]->pOffsetList
116627             && apSegment[j]->iDocid==iDocid
116628         ){
116629           fts3SegReaderNextDocid(apSegment[j], 0, 0);
116630           j++;
116631         }
116632
116633         if( isColFilter ){
116634           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
116635         }
116636
116637         if( !isIgnoreEmpty || nList>0 ){
116638           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
116639           if( nDoclist+nByte>nAlloc ){
116640             char *aNew;
116641             nAlloc = nDoclist+nByte*2;
116642             aNew = sqlite3_realloc(aBuffer, nAlloc);
116643             if( !aNew ){
116644               rc = SQLITE_NOMEM;
116645               goto finished;
116646             }
116647             aBuffer = aNew;
116648           }
116649           nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
116650           iPrev = iDocid;
116651           if( isRequirePos ){
116652             memcpy(&aBuffer[nDoclist], pList, nList);
116653             nDoclist += nList;
116654             aBuffer[nDoclist++] = '\0';
116655           }
116656         }
116657
116658         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
116659       }
116660
116661       if( nDoclist>0 ){
116662         rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
116663         if( rc!=SQLITE_OK ) goto finished;
116664       }
116665     }
116666
116667     /* If there is a term specified to filter on, and this is not a prefix
116668     ** search, return now. The callback that corresponds to the required
116669     ** term (if such a term exists in the index) has already been made.
116670     */
116671     if( pFilter->zTerm && !isPrefix ){
116672       goto finished;
116673     }
116674
116675     for(i=0; i<nMerge; i++){
116676       rc = fts3SegReaderNext(p, apSegment[i]);
116677       if( rc!=SQLITE_OK ) goto finished;
116678     }
116679     fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
116680   }
116681
116682  finished:
116683   sqlite3_free(aBuffer);
116684   return rc;
116685 }
116686
116687 /*
116688 ** Merge all level iLevel segments in the database into a single 
116689 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
116690 ** single segment with a level equal to the numerically largest level 
116691 ** currently present in the database.
116692 **
116693 ** If this function is called with iLevel<0, but there is only one
116694 ** segment in the database, SQLITE_DONE is returned immediately. 
116695 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
116696 ** an SQLite error code is returned.
116697 */
116698 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
116699   int i;                          /* Iterator variable */
116700   int rc;                         /* Return code */
116701   int iIdx;                       /* Index of new segment */
116702   int iNewLevel = 0;              /* Level to create new segment at */
116703   sqlite3_stmt *pStmt = 0;
116704   SegmentWriter *pWriter = 0;
116705   int nSegment = 0;               /* Number of segments being merged */
116706   Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
116707   Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
116708   Fts3SegFilter filter;           /* Segment term filter condition */
116709
116710   if( iLevel<0 ){
116711     /* This call is to merge all segments in the database to a single
116712     ** segment. The level of the new segment is equal to the the numerically 
116713     ** greatest segment level currently present in the database. The index
116714     ** of the new segment is always 0.
116715     */
116716     iIdx = 0;
116717     rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
116718     if( rc!=SQLITE_OK ) goto finished;
116719     rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
116720     if( rc!=SQLITE_OK ) goto finished;
116721     nSegment += (pPending!=0);
116722     if( nSegment<=1 ){
116723       return SQLITE_DONE;
116724     }
116725   }else{
116726     /* This call is to merge all segments at level iLevel. Find the next
116727     ** available segment index at level iLevel+1. The call to
116728     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
116729     ** a single iLevel+2 segment if necessary.
116730     */
116731     iNewLevel = iLevel+1;
116732     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
116733     if( rc!=SQLITE_OK ) goto finished;
116734     rc = fts3SegmentCount(p, iLevel, &nSegment);
116735     if( rc!=SQLITE_OK ) goto finished;
116736   }
116737   assert( nSegment>0 );
116738   assert( iNewLevel>=0 );
116739
116740   /* Allocate space for an array of pointers to segment iterators. */
116741   apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
116742   if( !apSegment ){
116743     rc = SQLITE_NOMEM;
116744     goto finished;
116745   }
116746   memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
116747
116748   /* Allocate a Fts3SegReader structure for each segment being merged. A 
116749   ** Fts3SegReader stores the state data required to iterate through all 
116750   ** entries on all leaves of a single segment. 
116751   */
116752   assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
116753   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
116754   if( rc!=SQLITE_OK ) goto finished;
116755   sqlite3_bind_int(pStmt, 1, iLevel);
116756   for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
116757     rc = fts3SegReaderNew(pStmt, i, &apSegment[i]);
116758     if( rc!=SQLITE_OK ){
116759       goto finished;
116760     }
116761   }
116762   rc = sqlite3_reset(pStmt);
116763   if( pPending ){
116764     apSegment[i] = pPending;
116765     pPending = 0;
116766   }
116767   pStmt = 0;
116768   if( rc!=SQLITE_OK ) goto finished;
116769
116770   memset(&filter, 0, sizeof(Fts3SegFilter));
116771   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
116772   filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
116773   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
116774       &filter, fts3MergeCallback, (void *)&pWriter
116775   );
116776   if( rc!=SQLITE_OK ) goto finished;
116777
116778   rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
116779   if( rc==SQLITE_OK ){
116780     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
116781   }
116782
116783  finished:
116784   fts3SegWriterFree(pWriter);
116785   if( apSegment ){
116786     for(i=0; i<nSegment; i++){
116787       sqlite3Fts3SegReaderFree(apSegment[i]);
116788     }
116789     sqlite3_free(apSegment);
116790   }
116791   sqlite3Fts3SegReaderFree(pPending);
116792   sqlite3_reset(pStmt);
116793   return rc;
116794 }
116795
116796
116797 /* 
116798 ** Flush the contents of pendingTerms to a level 0 segment.
116799 */
116800 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
116801   int rc;                         /* Return Code */
116802   int idx;                        /* Index of new segment created */
116803   SegmentWriter *pWriter = 0;     /* Used to write the segment */
116804   Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
116805
116806   /* Allocate a SegReader object to iterate through the contents of the
116807   ** pending-terms table. If an error occurs, or if there are no terms
116808   ** in the pending-terms table, return immediately.
116809   */
116810   rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
116811   if( rc!=SQLITE_OK || pReader==0 ){
116812     return rc;
116813   }
116814
116815   /* Determine the next index at level 0. If level 0 is already full, this
116816   ** call may merge all existing level 0 segments into a single level 1
116817   ** segment.
116818   */
116819   rc = fts3AllocateSegdirIdx(p, 0, &idx);
116820
116821   /* If no errors have occured, iterate through the contents of the 
116822   ** pending-terms hash table using the Fts3SegReader iterator. The callback
116823   ** writes each term (along with its doclist) to the database via the
116824   ** SegmentWriter handle pWriter.
116825   */
116826   if( rc==SQLITE_OK ){
116827     void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
116828     Fts3SegFilter f;              /* SegReaderIterate() parameters */
116829
116830     memset(&f, 0, sizeof(Fts3SegFilter));
116831     f.flags = FTS3_SEGMENT_REQUIRE_POS;
116832     rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
116833   }
116834   assert( pWriter || rc!=SQLITE_OK );
116835
116836   /* If no errors have occured, flush the SegmentWriter object to the
116837   ** database. Then delete the SegmentWriter and Fts3SegReader objects
116838   ** allocated by this function.
116839   */
116840   if( rc==SQLITE_OK ){
116841     rc = fts3SegWriterFlush(p, pWriter, 0, idx);
116842   }
116843   fts3SegWriterFree(pWriter);
116844   sqlite3Fts3SegReaderFree(pReader);
116845
116846   if( rc==SQLITE_OK ){
116847     sqlite3Fts3PendingTermsClear(p);
116848   }
116849   return rc;
116850 }
116851
116852 /*
116853 ** Encode N integers as varints into a blob.
116854 */
116855 static void fts3EncodeIntArray(
116856   int N,             /* The number of integers to encode */
116857   u32 *a,            /* The integer values */
116858   char *zBuf,        /* Write the BLOB here */
116859   int *pNBuf         /* Write number of bytes if zBuf[] used here */
116860 ){
116861   int i, j;
116862   for(i=j=0; i<N; i++){
116863     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
116864   }
116865   *pNBuf = j;
116866 }
116867
116868 /*
116869 ** Decode a blob of varints into N integers
116870 */
116871 static void fts3DecodeIntArray(
116872   int N,             /* The number of integers to decode */
116873   u32 *a,            /* Write the integer values */
116874   const char *zBuf,  /* The BLOB containing the varints */
116875   int nBuf           /* size of the BLOB */
116876 ){
116877   int i, j;
116878   UNUSED_PARAMETER(nBuf);
116879   for(i=j=0; i<N; i++){
116880     sqlite3_int64 x;
116881     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
116882     assert(j<=nBuf);
116883     a[i] = (u32)(x & 0xffffffff);
116884   }
116885 }
116886
116887 /*
116888 ** Insert the sizes (in tokens) for each column of the document
116889 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
116890 ** a blob of varints.
116891 */
116892 static void fts3InsertDocsize(
116893   int *pRC,         /* Result code */
116894   Fts3Table *p,     /* Table into which to insert */
116895   u32 *aSz          /* Sizes of each column */
116896 ){
116897   char *pBlob;             /* The BLOB encoding of the document size */
116898   int nBlob;               /* Number of bytes in the BLOB */
116899   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
116900   int rc;                  /* Result code from subfunctions */
116901
116902   if( *pRC ) return;
116903   pBlob = sqlite3_malloc( 10*p->nColumn );
116904   if( pBlob==0 ){
116905     *pRC = SQLITE_NOMEM;
116906     return;
116907   }
116908   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
116909   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
116910   if( rc ){
116911     sqlite3_free(pBlob);
116912     *pRC = rc;
116913     return;
116914   }
116915   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
116916   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
116917   sqlite3_step(pStmt);
116918   *pRC = sqlite3_reset(pStmt);
116919 }
116920
116921 /*
116922 ** Record 0 of the %_stat table contains a blob consisting of N varints,
116923 ** where N is the number of user defined columns in the fts3 table plus
116924 ** two. If nCol is the number of user defined columns, then values of the 
116925 ** varints are set as follows:
116926 **
116927 **   Varint 0:       Total number of rows in the table.
116928 **
116929 **   Varint 1..nCol: For each column, the total number of tokens stored in
116930 **                   the column for all rows of the table.
116931 **
116932 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
116933 **                   columns of all rows of the table.
116934 **
116935 */
116936 static void fts3UpdateDocTotals(
116937   int *pRC,                       /* The result code */
116938   Fts3Table *p,                   /* Table being updated */
116939   u32 *aSzIns,                    /* Size increases */
116940   u32 *aSzDel,                    /* Size decreases */
116941   int nChng                       /* Change in the number of documents */
116942 ){
116943   char *pBlob;             /* Storage for BLOB written into %_stat */
116944   int nBlob;               /* Size of BLOB written into %_stat */
116945   u32 *a;                  /* Array of integers that becomes the BLOB */
116946   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
116947   int i;                   /* Loop counter */
116948   int rc;                  /* Result code from subfunctions */
116949
116950   const int nStat = p->nColumn+2;
116951
116952   if( *pRC ) return;
116953   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
116954   if( a==0 ){
116955     *pRC = SQLITE_NOMEM;
116956     return;
116957   }
116958   pBlob = (char*)&a[nStat];
116959   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
116960   if( rc ){
116961     sqlite3_free(a);
116962     *pRC = rc;
116963     return;
116964   }
116965   if( sqlite3_step(pStmt)==SQLITE_ROW ){
116966     fts3DecodeIntArray(nStat, a,
116967          sqlite3_column_blob(pStmt, 0),
116968          sqlite3_column_bytes(pStmt, 0));
116969   }else{
116970     memset(a, 0, sizeof(u32)*(nStat) );
116971   }
116972   sqlite3_reset(pStmt);
116973   if( nChng<0 && a[0]<(u32)(-nChng) ){
116974     a[0] = 0;
116975   }else{
116976     a[0] += nChng;
116977   }
116978   for(i=0; i<p->nColumn+1; i++){
116979     u32 x = a[i+1];
116980     if( x+aSzIns[i] < aSzDel[i] ){
116981       x = 0;
116982     }else{
116983       x = x + aSzIns[i] - aSzDel[i];
116984     }
116985     a[i+1] = x;
116986   }
116987   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
116988   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
116989   if( rc ){
116990     sqlite3_free(a);
116991     *pRC = rc;
116992     return;
116993   }
116994   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
116995   sqlite3_step(pStmt);
116996   *pRC = sqlite3_reset(pStmt);
116997   sqlite3_free(a);
116998 }
116999
117000 /*
117001 ** Handle a 'special' INSERT of the form:
117002 **
117003 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
117004 **
117005 ** Argument pVal contains the result of <expr>. Currently the only 
117006 ** meaningful value to insert is the text 'optimize'.
117007 */
117008 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
117009   int rc;                         /* Return Code */
117010   const char *zVal = (const char *)sqlite3_value_text(pVal);
117011   int nVal = sqlite3_value_bytes(pVal);
117012
117013   if( !zVal ){
117014     return SQLITE_NOMEM;
117015   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
117016     rc = fts3SegmentMerge(p, -1);
117017     if( rc==SQLITE_DONE ){
117018       rc = SQLITE_OK;
117019     }else{
117020       sqlite3Fts3PendingTermsClear(p);
117021     }
117022 #ifdef SQLITE_TEST
117023   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
117024     p->nNodeSize = atoi(&zVal[9]);
117025     rc = SQLITE_OK;
117026   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
117027     p->nMaxPendingData = atoi(&zVal[11]);
117028     rc = SQLITE_OK;
117029 #endif
117030   }else{
117031     rc = SQLITE_ERROR;
117032   }
117033
117034   sqlite3Fts3SegmentsClose(p);
117035   return rc;
117036 }
117037
117038 /*
117039 ** Return the deferred doclist associated with deferred token pDeferred.
117040 ** This function assumes that sqlite3Fts3CacheDeferredDoclists() has already
117041 ** been called to allocate and populate the doclist.
117042 */
117043 SQLITE_PRIVATE char *sqlite3Fts3DeferredDoclist(Fts3DeferredToken *pDeferred, int *pnByte){
117044   if( pDeferred->pList ){
117045     *pnByte = pDeferred->pList->nData;
117046     return pDeferred->pList->aData;
117047   }
117048   *pnByte = 0;
117049   return 0;
117050 }
117051
117052 /*
117053 ** Helper fucntion for FreeDeferredDoclists(). This function removes all
117054 ** references to deferred doclists from within the tree of Fts3Expr 
117055 ** structures headed by 
117056 */
117057 static void fts3DeferredDoclistClear(Fts3Expr *pExpr){
117058   if( pExpr ){
117059     fts3DeferredDoclistClear(pExpr->pLeft);
117060     fts3DeferredDoclistClear(pExpr->pRight);
117061     if( pExpr->isLoaded ){
117062       sqlite3_free(pExpr->aDoclist);
117063       pExpr->isLoaded = 0;
117064       pExpr->aDoclist = 0;
117065       pExpr->nDoclist = 0;
117066       pExpr->pCurrent = 0;
117067       pExpr->iCurrent = 0;
117068     }
117069   }
117070 }
117071
117072 /*
117073 ** Delete all cached deferred doclists. Deferred doclists are cached
117074 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
117075 */
117076 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
117077   Fts3DeferredToken *pDef;
117078   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
117079     sqlite3_free(pDef->pList);
117080     pDef->pList = 0;
117081   }
117082   if( pCsr->pDeferred ){
117083     fts3DeferredDoclistClear(pCsr->pExpr);
117084   }
117085 }
117086
117087 /*
117088 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
117089 ** this list using sqlite3Fts3DeferToken().
117090 */
117091 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
117092   Fts3DeferredToken *pDef;
117093   Fts3DeferredToken *pNext;
117094   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
117095     pNext = pDef->pNext;
117096     sqlite3_free(pDef->pList);
117097     sqlite3_free(pDef);
117098   }
117099   pCsr->pDeferred = 0;
117100 }
117101
117102 /*
117103 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
117104 ** based on the row that pCsr currently points to.
117105 **
117106 ** A deferred-doclist is like any other doclist with position information
117107 ** included, except that it only contains entries for a single row of the
117108 ** table, not for all rows.
117109 */
117110 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
117111   int rc = SQLITE_OK;             /* Return code */
117112   if( pCsr->pDeferred ){
117113     int i;                        /* Used to iterate through table columns */
117114     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
117115     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
117116   
117117     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
117118     sqlite3_tokenizer *pT = p->pTokenizer;
117119     sqlite3_tokenizer_module const *pModule = pT->pModule;
117120    
117121     assert( pCsr->isRequireSeek==0 );
117122     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
117123   
117124     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
117125       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
117126       sqlite3_tokenizer_cursor *pTC = 0;
117127   
117128       rc = pModule->xOpen(pT, zText, -1, &pTC);
117129       while( rc==SQLITE_OK ){
117130         char const *zToken;       /* Buffer containing token */
117131         int nToken;               /* Number of bytes in token */
117132         int iDum1, iDum2;         /* Dummy variables */
117133         int iPos;                 /* Position of token in zText */
117134   
117135         pTC->pTokenizer = pT;
117136         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
117137         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
117138           Fts3PhraseToken *pPT = pDef->pToken;
117139           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
117140            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
117141            && (0==memcmp(zToken, pPT->z, pPT->n))
117142           ){
117143             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
117144           }
117145         }
117146       }
117147       if( pTC ) pModule->xClose(pTC);
117148       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
117149     }
117150   
117151     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
117152       if( pDef->pList ){
117153         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
117154       }
117155     }
117156   }
117157
117158   return rc;
117159 }
117160
117161 /*
117162 ** Add an entry for token pToken to the pCsr->pDeferred list.
117163 */
117164 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
117165   Fts3Cursor *pCsr,               /* Fts3 table cursor */
117166   Fts3PhraseToken *pToken,        /* Token to defer */
117167   int iCol                        /* Column that token must appear in (or -1) */
117168 ){
117169   Fts3DeferredToken *pDeferred;
117170   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
117171   if( !pDeferred ){
117172     return SQLITE_NOMEM;
117173   }
117174   memset(pDeferred, 0, sizeof(*pDeferred));
117175   pDeferred->pToken = pToken;
117176   pDeferred->pNext = pCsr->pDeferred; 
117177   pDeferred->iCol = iCol;
117178   pCsr->pDeferred = pDeferred;
117179
117180   assert( pToken->pDeferred==0 );
117181   pToken->pDeferred = pDeferred;
117182
117183   return SQLITE_OK;
117184 }
117185
117186
117187 /*
117188 ** This function does the work for the xUpdate method of FTS3 virtual
117189 ** tables.
117190 */
117191 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
117192   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
117193   int nArg,                       /* Size of argument array */
117194   sqlite3_value **apVal,          /* Array of arguments */
117195   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
117196 ){
117197   Fts3Table *p = (Fts3Table *)pVtab;
117198   int rc = SQLITE_OK;             /* Return Code */
117199   int isRemove = 0;               /* True for an UPDATE or DELETE */
117200   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
117201   u32 *aSzIns;                    /* Sizes of inserted documents */
117202   u32 *aSzDel;                    /* Sizes of deleted documents */
117203   int nChng = 0;                  /* Net change in number of documents */
117204
117205   assert( p->pSegments==0 );
117206
117207   /* Allocate space to hold the change in document sizes */
117208   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
117209   if( aSzIns==0 ) return SQLITE_NOMEM;
117210   aSzDel = &aSzIns[p->nColumn+1];
117211   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
117212
117213   /* If this is a DELETE or UPDATE operation, remove the old record. */
117214   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
117215     int isEmpty = 0;
117216     rc = fts3IsEmpty(p, apVal, &isEmpty);
117217     if( rc==SQLITE_OK ){
117218       if( isEmpty ){
117219         /* Deleting this row means the whole table is empty. In this case
117220         ** delete the contents of all three tables and throw away any
117221         ** data in the pendingTerms hash table.
117222         */
117223         rc = fts3DeleteAll(p);
117224       }else{
117225         isRemove = 1;
117226         iRemove = sqlite3_value_int64(apVal[0]);
117227         rc = fts3PendingTermsDocid(p, iRemove);
117228         fts3DeleteTerms(&rc, p, apVal, aSzDel);
117229         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
117230         if( p->bHasDocsize ){
117231           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
117232         }
117233         nChng--;
117234       }
117235     }
117236   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
117237     sqlite3_free(aSzIns);
117238     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
117239   }
117240   
117241   /* If this is an INSERT or UPDATE operation, insert the new record. */
117242   if( nArg>1 && rc==SQLITE_OK ){
117243     rc = fts3InsertData(p, apVal, pRowid);
117244     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
117245       rc = fts3PendingTermsDocid(p, *pRowid);
117246     }
117247     if( rc==SQLITE_OK ){
117248       rc = fts3InsertTerms(p, apVal, aSzIns);
117249     }
117250     if( p->bHasDocsize ){
117251       fts3InsertDocsize(&rc, p, aSzIns);
117252     }
117253     nChng++;
117254   }
117255
117256   if( p->bHasStat ){
117257     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
117258   }
117259
117260   sqlite3_free(aSzIns);
117261   sqlite3Fts3SegmentsClose(p);
117262   return rc;
117263 }
117264
117265 /* 
117266 ** Flush any data in the pending-terms hash table to disk. If successful,
117267 ** merge all segments in the database (including the new segment, if 
117268 ** there was any data to flush) into a single segment. 
117269 */
117270 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
117271   int rc;
117272   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
117273   if( rc==SQLITE_OK ){
117274     rc = fts3SegmentMerge(p, -1);
117275     if( rc==SQLITE_OK ){
117276       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
117277       if( rc==SQLITE_OK ){
117278         sqlite3Fts3PendingTermsClear(p);
117279       }
117280     }else{
117281       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
117282       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
117283     }
117284   }
117285   sqlite3Fts3SegmentsClose(p);
117286   return rc;
117287 }
117288
117289 #endif
117290
117291 /************** End of fts3_write.c ******************************************/
117292 /************** Begin file fts3_snippet.c ************************************/
117293 /*
117294 ** 2009 Oct 23
117295 **
117296 ** The author disclaims copyright to this source code.  In place of
117297 ** a legal notice, here is a blessing:
117298 **
117299 **    May you do good and not evil.
117300 **    May you find forgiveness for yourself and forgive others.
117301 **    May you share freely, never taking more than you give.
117302 **
117303 ******************************************************************************
117304 */
117305
117306 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
117307
117308
117309 /*
117310 ** Characters that may appear in the second argument to matchinfo().
117311 */
117312 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
117313 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
117314 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
117315 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
117316 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
117317 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
117318 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
117319
117320 /*
117321 ** The default value for the second argument to matchinfo(). 
117322 */
117323 #define FTS3_MATCHINFO_DEFAULT   "pcx"
117324
117325
117326 /*
117327 ** Used as an fts3ExprIterate() context when loading phrase doclists to
117328 ** Fts3Expr.aDoclist[]/nDoclist.
117329 */
117330 typedef struct LoadDoclistCtx LoadDoclistCtx;
117331 struct LoadDoclistCtx {
117332   Fts3Cursor *pCsr;               /* FTS3 Cursor */
117333   int nPhrase;                    /* Number of phrases seen so far */
117334   int nToken;                     /* Number of tokens seen so far */
117335 };
117336
117337 /*
117338 ** The following types are used as part of the implementation of the 
117339 ** fts3BestSnippet() routine.
117340 */
117341 typedef struct SnippetIter SnippetIter;
117342 typedef struct SnippetPhrase SnippetPhrase;
117343 typedef struct SnippetFragment SnippetFragment;
117344
117345 struct SnippetIter {
117346   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
117347   int iCol;                       /* Extract snippet from this column */
117348   int nSnippet;                   /* Requested snippet length (in tokens) */
117349   int nPhrase;                    /* Number of phrases in query */
117350   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
117351   int iCurrent;                   /* First token of current snippet */
117352 };
117353
117354 struct SnippetPhrase {
117355   int nToken;                     /* Number of tokens in phrase */
117356   char *pList;                    /* Pointer to start of phrase position list */
117357   int iHead;                      /* Next value in position list */
117358   char *pHead;                    /* Position list data following iHead */
117359   int iTail;                      /* Next value in trailing position list */
117360   char *pTail;                    /* Position list data following iTail */
117361 };
117362
117363 struct SnippetFragment {
117364   int iCol;                       /* Column snippet is extracted from */
117365   int iPos;                       /* Index of first token in snippet */
117366   u64 covered;                    /* Mask of query phrases covered */
117367   u64 hlmask;                     /* Mask of snippet terms to highlight */
117368 };
117369
117370 /*
117371 ** This type is used as an fts3ExprIterate() context object while 
117372 ** accumulating the data returned by the matchinfo() function.
117373 */
117374 typedef struct MatchInfo MatchInfo;
117375 struct MatchInfo {
117376   Fts3Cursor *pCursor;            /* FTS3 Cursor */
117377   int nCol;                       /* Number of columns in table */
117378   int nPhrase;                    /* Number of matchable phrases in query */
117379   sqlite3_int64 nDoc;             /* Number of docs in database */
117380   u32 *aMatchinfo;                /* Pre-allocated buffer */
117381 };
117382
117383
117384
117385 /*
117386 ** The snippet() and offsets() functions both return text values. An instance
117387 ** of the following structure is used to accumulate those values while the
117388 ** functions are running. See fts3StringAppend() for details.
117389 */
117390 typedef struct StrBuffer StrBuffer;
117391 struct StrBuffer {
117392   char *z;                        /* Pointer to buffer containing string */
117393   int n;                          /* Length of z in bytes (excl. nul-term) */
117394   int nAlloc;                     /* Allocated size of buffer z in bytes */
117395 };
117396
117397
117398 /*
117399 ** This function is used to help iterate through a position-list. A position
117400 ** list is a list of unique integers, sorted from smallest to largest. Each
117401 ** element of the list is represented by an FTS3 varint that takes the value
117402 ** of the difference between the current element and the previous one plus
117403 ** two. For example, to store the position-list:
117404 **
117405 **     4 9 113
117406 **
117407 ** the three varints:
117408 **
117409 **     6 7 106
117410 **
117411 ** are encoded.
117412 **
117413 ** When this function is called, *pp points to the start of an element of
117414 ** the list. *piPos contains the value of the previous entry in the list.
117415 ** After it returns, *piPos contains the value of the next element of the
117416 ** list and *pp is advanced to the following varint.
117417 */
117418 static void fts3GetDeltaPosition(char **pp, int *piPos){
117419   int iVal;
117420   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
117421   *piPos += (iVal-2);
117422 }
117423
117424 /*
117425 ** Helper function for fts3ExprIterate() (see below).
117426 */
117427 static int fts3ExprIterate2(
117428   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
117429   int *piPhrase,                  /* Pointer to phrase counter */
117430   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
117431   void *pCtx                      /* Second argument to pass to callback */
117432 ){
117433   int rc;                         /* Return code */
117434   int eType = pExpr->eType;       /* Type of expression node pExpr */
117435
117436   if( eType!=FTSQUERY_PHRASE ){
117437     assert( pExpr->pLeft && pExpr->pRight );
117438     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
117439     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
117440       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
117441     }
117442   }else{
117443     rc = x(pExpr, *piPhrase, pCtx);
117444     (*piPhrase)++;
117445   }
117446   return rc;
117447 }
117448
117449 /*
117450 ** Iterate through all phrase nodes in an FTS3 query, except those that
117451 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
117452 ** For each phrase node found, the supplied callback function is invoked.
117453 **
117454 ** If the callback function returns anything other than SQLITE_OK, 
117455 ** the iteration is abandoned and the error code returned immediately.
117456 ** Otherwise, SQLITE_OK is returned after a callback has been made for
117457 ** all eligible phrase nodes.
117458 */
117459 static int fts3ExprIterate(
117460   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
117461   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
117462   void *pCtx                      /* Second argument to pass to callback */
117463 ){
117464   int iPhrase = 0;                /* Variable used as the phrase counter */
117465   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
117466 }
117467
117468 /*
117469 ** The argument to this function is always a phrase node. Its doclist 
117470 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
117471 ** to the left of this one in the query tree have already been loaded.
117472 **
117473 ** If this phrase node is part of a series of phrase nodes joined by 
117474 ** NEAR operators (and is not the left-most of said series), then elements are
117475 ** removed from the phrases doclist consistent with the NEAR restriction. If
117476 ** required, elements may be removed from the doclists of phrases to the
117477 ** left of this one that are part of the same series of NEAR operator 
117478 ** connected phrases.
117479 **
117480 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
117481 */
117482 static int fts3ExprNearTrim(Fts3Expr *pExpr){
117483   int rc = SQLITE_OK;
117484   Fts3Expr *pParent = pExpr->pParent;
117485
117486   assert( pExpr->eType==FTSQUERY_PHRASE );
117487   while( rc==SQLITE_OK
117488    && pParent 
117489    && pParent->eType==FTSQUERY_NEAR 
117490    && pParent->pRight==pExpr 
117491   ){
117492     /* This expression (pExpr) is the right-hand-side of a NEAR operator. 
117493     ** Find the expression to the left of the same operator.
117494     */
117495     int nNear = pParent->nNear;
117496     Fts3Expr *pLeft = pParent->pLeft;
117497
117498     if( pLeft->eType!=FTSQUERY_PHRASE ){
117499       assert( pLeft->eType==FTSQUERY_NEAR );
117500       assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
117501       pLeft = pLeft->pRight;
117502     }
117503
117504     rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
117505
117506     pExpr = pLeft;
117507     pParent = pExpr->pParent;
117508   }
117509
117510   return rc;
117511 }
117512
117513 /*
117514 ** This is an fts3ExprIterate() callback used while loading the doclists
117515 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
117516 ** fts3ExprLoadDoclists().
117517 */
117518 static int fts3ExprLoadDoclistsCb1(Fts3Expr *pExpr, int iPhrase, void *ctx){
117519   int rc = SQLITE_OK;
117520   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
117521
117522   UNUSED_PARAMETER(iPhrase);
117523
117524   p->nPhrase++;
117525   p->nToken += pExpr->pPhrase->nToken;
117526
117527   if( pExpr->isLoaded==0 ){
117528     rc = sqlite3Fts3ExprLoadDoclist(p->pCsr, pExpr);
117529     pExpr->isLoaded = 1;
117530     if( rc==SQLITE_OK ){
117531       rc = fts3ExprNearTrim(pExpr);
117532     }
117533   }
117534
117535   return rc;
117536 }
117537
117538 /*
117539 ** This is an fts3ExprIterate() callback used while loading the doclists
117540 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
117541 ** fts3ExprLoadDoclists().
117542 */
117543 static int fts3ExprLoadDoclistsCb2(Fts3Expr *pExpr, int iPhrase, void *ctx){
117544   UNUSED_PARAMETER(iPhrase);
117545   UNUSED_PARAMETER(ctx);
117546   if( pExpr->aDoclist ){
117547     pExpr->pCurrent = pExpr->aDoclist;
117548     pExpr->iCurrent = 0;
117549     pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent, &pExpr->iCurrent);
117550   }
117551   return SQLITE_OK;
117552 }
117553
117554 /*
117555 ** Load the doclists for each phrase in the query associated with FTS3 cursor
117556 ** pCsr. 
117557 **
117558 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
117559 ** phrases in the expression (all phrases except those directly or 
117560 ** indirectly descended from the right-hand-side of a NOT operator). If 
117561 ** pnToken is not NULL, then it is set to the number of tokens in all
117562 ** matchable phrases of the expression.
117563 */
117564 static int fts3ExprLoadDoclists(
117565   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
117566   int *pnPhrase,                  /* OUT: Number of phrases in query */
117567   int *pnToken                    /* OUT: Number of tokens in query */
117568 ){
117569   int rc;                         /* Return Code */
117570   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
117571   sCtx.pCsr = pCsr;
117572   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb1, (void *)&sCtx);
117573   if( rc==SQLITE_OK ){
117574     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb2, 0);
117575   }
117576   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
117577   if( pnToken ) *pnToken = sCtx.nToken;
117578   return rc;
117579 }
117580
117581 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
117582   (*(int *)ctx)++;
117583   UNUSED_PARAMETER(pExpr);
117584   UNUSED_PARAMETER(iPhrase);
117585   return SQLITE_OK;
117586 }
117587 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
117588   int nPhrase = 0;
117589   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
117590   return nPhrase;
117591 }
117592
117593 /*
117594 ** Advance the position list iterator specified by the first two 
117595 ** arguments so that it points to the first element with a value greater
117596 ** than or equal to parameter iNext.
117597 */
117598 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
117599   char *pIter = *ppIter;
117600   if( pIter ){
117601     int iIter = *piIter;
117602
117603     while( iIter<iNext ){
117604       if( 0==(*pIter & 0xFE) ){
117605         iIter = -1;
117606         pIter = 0;
117607         break;
117608       }
117609       fts3GetDeltaPosition(&pIter, &iIter);
117610     }
117611
117612     *piIter = iIter;
117613     *ppIter = pIter;
117614   }
117615 }
117616
117617 /*
117618 ** Advance the snippet iterator to the next candidate snippet.
117619 */
117620 static int fts3SnippetNextCandidate(SnippetIter *pIter){
117621   int i;                          /* Loop counter */
117622
117623   if( pIter->iCurrent<0 ){
117624     /* The SnippetIter object has just been initialized. The first snippet
117625     ** candidate always starts at offset 0 (even if this candidate has a
117626     ** score of 0.0).
117627     */
117628     pIter->iCurrent = 0;
117629
117630     /* Advance the 'head' iterator of each phrase to the first offset that
117631     ** is greater than or equal to (iNext+nSnippet).
117632     */
117633     for(i=0; i<pIter->nPhrase; i++){
117634       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
117635       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
117636     }
117637   }else{
117638     int iStart;
117639     int iEnd = 0x7FFFFFFF;
117640
117641     for(i=0; i<pIter->nPhrase; i++){
117642       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
117643       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
117644         iEnd = pPhrase->iHead;
117645       }
117646     }
117647     if( iEnd==0x7FFFFFFF ){
117648       return 1;
117649     }
117650
117651     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
117652     for(i=0; i<pIter->nPhrase; i++){
117653       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
117654       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
117655       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
117656     }
117657   }
117658
117659   return 0;
117660 }
117661
117662 /*
117663 ** Retrieve information about the current candidate snippet of snippet 
117664 ** iterator pIter.
117665 */
117666 static void fts3SnippetDetails(
117667   SnippetIter *pIter,             /* Snippet iterator */
117668   u64 mCovered,                   /* Bitmask of phrases already covered */
117669   int *piToken,                   /* OUT: First token of proposed snippet */
117670   int *piScore,                   /* OUT: "Score" for this snippet */
117671   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
117672   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
117673 ){
117674   int iStart = pIter->iCurrent;   /* First token of snippet */
117675   int iScore = 0;                 /* Score of this snippet */
117676   int i;                          /* Loop counter */
117677   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
117678   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
117679
117680   for(i=0; i<pIter->nPhrase; i++){
117681     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
117682     if( pPhrase->pTail ){
117683       char *pCsr = pPhrase->pTail;
117684       int iCsr = pPhrase->iTail;
117685
117686       while( iCsr<(iStart+pIter->nSnippet) ){
117687         int j;
117688         u64 mPhrase = (u64)1 << i;
117689         u64 mPos = (u64)1 << (iCsr - iStart);
117690         assert( iCsr>=iStart );
117691         if( (mCover|mCovered)&mPhrase ){
117692           iScore++;
117693         }else{
117694           iScore += 1000;
117695         }
117696         mCover |= mPhrase;
117697
117698         for(j=0; j<pPhrase->nToken; j++){
117699           mHighlight |= (mPos>>j);
117700         }
117701
117702         if( 0==(*pCsr & 0x0FE) ) break;
117703         fts3GetDeltaPosition(&pCsr, &iCsr);
117704       }
117705     }
117706   }
117707
117708   /* Set the output variables before returning. */
117709   *piToken = iStart;
117710   *piScore = iScore;
117711   *pmCover = mCover;
117712   *pmHighlight = mHighlight;
117713 }
117714
117715 /*
117716 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
117717 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
117718 */
117719 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
117720   SnippetIter *p = (SnippetIter *)ctx;
117721   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
117722   char *pCsr;
117723
117724   pPhrase->nToken = pExpr->pPhrase->nToken;
117725
117726   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
117727   if( pCsr ){
117728     int iFirst = 0;
117729     pPhrase->pList = pCsr;
117730     fts3GetDeltaPosition(&pCsr, &iFirst);
117731     pPhrase->pHead = pCsr;
117732     pPhrase->pTail = pCsr;
117733     pPhrase->iHead = iFirst;
117734     pPhrase->iTail = iFirst;
117735   }else{
117736     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
117737   }
117738
117739   return SQLITE_OK;
117740 }
117741
117742 /*
117743 ** Select the fragment of text consisting of nFragment contiguous tokens 
117744 ** from column iCol that represent the "best" snippet. The best snippet
117745 ** is the snippet with the highest score, where scores are calculated
117746 ** by adding:
117747 **
117748 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
117749 **
117750 **   (b) +1000 points for the first occurence of each matchable phrase in 
117751 **       the snippet for which the corresponding mCovered bit is not set.
117752 **
117753 ** The selected snippet parameters are stored in structure *pFragment before
117754 ** returning. The score of the selected snippet is stored in *piScore
117755 ** before returning.
117756 */
117757 static int fts3BestSnippet(
117758   int nSnippet,                   /* Desired snippet length */
117759   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
117760   int iCol,                       /* Index of column to create snippet from */
117761   u64 mCovered,                   /* Mask of phrases already covered */
117762   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
117763   SnippetFragment *pFragment,     /* OUT: Best snippet found */
117764   int *piScore                    /* OUT: Score of snippet pFragment */
117765 ){
117766   int rc;                         /* Return Code */
117767   int nList;                      /* Number of phrases in expression */
117768   SnippetIter sIter;              /* Iterates through snippet candidates */
117769   int nByte;                      /* Number of bytes of space to allocate */
117770   int iBestScore = -1;            /* Best snippet score found so far */
117771   int i;                          /* Loop counter */
117772
117773   memset(&sIter, 0, sizeof(sIter));
117774
117775   /* Iterate through the phrases in the expression to count them. The same
117776   ** callback makes sure the doclists are loaded for each phrase.
117777   */
117778   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
117779   if( rc!=SQLITE_OK ){
117780     return rc;
117781   }
117782
117783   /* Now that it is known how many phrases there are, allocate and zero
117784   ** the required space using malloc().
117785   */
117786   nByte = sizeof(SnippetPhrase) * nList;
117787   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
117788   if( !sIter.aPhrase ){
117789     return SQLITE_NOMEM;
117790   }
117791   memset(sIter.aPhrase, 0, nByte);
117792
117793   /* Initialize the contents of the SnippetIter object. Then iterate through
117794   ** the set of phrases in the expression to populate the aPhrase[] array.
117795   */
117796   sIter.pCsr = pCsr;
117797   sIter.iCol = iCol;
117798   sIter.nSnippet = nSnippet;
117799   sIter.nPhrase = nList;
117800   sIter.iCurrent = -1;
117801   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
117802
117803   /* Set the *pmSeen output variable. */
117804   for(i=0; i<nList; i++){
117805     if( sIter.aPhrase[i].pHead ){
117806       *pmSeen |= (u64)1 << i;
117807     }
117808   }
117809
117810   /* Loop through all candidate snippets. Store the best snippet in 
117811   ** *pFragment. Store its associated 'score' in iBestScore.
117812   */
117813   pFragment->iCol = iCol;
117814   while( !fts3SnippetNextCandidate(&sIter) ){
117815     int iPos;
117816     int iScore;
117817     u64 mCover;
117818     u64 mHighlight;
117819     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
117820     assert( iScore>=0 );
117821     if( iScore>iBestScore ){
117822       pFragment->iPos = iPos;
117823       pFragment->hlmask = mHighlight;
117824       pFragment->covered = mCover;
117825       iBestScore = iScore;
117826     }
117827   }
117828
117829   sqlite3_free(sIter.aPhrase);
117830   *piScore = iBestScore;
117831   return SQLITE_OK;
117832 }
117833
117834
117835 /*
117836 ** Append a string to the string-buffer passed as the first argument.
117837 **
117838 ** If nAppend is negative, then the length of the string zAppend is
117839 ** determined using strlen().
117840 */
117841 static int fts3StringAppend(
117842   StrBuffer *pStr,                /* Buffer to append to */
117843   const char *zAppend,            /* Pointer to data to append to buffer */
117844   int nAppend                     /* Size of zAppend in bytes (or -1) */
117845 ){
117846   if( nAppend<0 ){
117847     nAppend = (int)strlen(zAppend);
117848   }
117849
117850   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
117851   ** to grow the buffer until so that it is big enough to accomadate the
117852   ** appended data.
117853   */
117854   if( pStr->n+nAppend+1>=pStr->nAlloc ){
117855     int nAlloc = pStr->nAlloc+nAppend+100;
117856     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
117857     if( !zNew ){
117858       return SQLITE_NOMEM;
117859     }
117860     pStr->z = zNew;
117861     pStr->nAlloc = nAlloc;
117862   }
117863
117864   /* Append the data to the string buffer. */
117865   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
117866   pStr->n += nAppend;
117867   pStr->z[pStr->n] = '\0';
117868
117869   return SQLITE_OK;
117870 }
117871
117872 /*
117873 ** The fts3BestSnippet() function often selects snippets that end with a
117874 ** query term. That is, the final term of the snippet is always a term
117875 ** that requires highlighting. For example, if 'X' is a highlighted term
117876 ** and '.' is a non-highlighted term, BestSnippet() may select:
117877 **
117878 **     ........X.....X
117879 **
117880 ** This function "shifts" the beginning of the snippet forward in the 
117881 ** document so that there are approximately the same number of 
117882 ** non-highlighted terms to the right of the final highlighted term as there
117883 ** are to the left of the first highlighted term. For example, to this:
117884 **
117885 **     ....X.....X....
117886 **
117887 ** This is done as part of extracting the snippet text, not when selecting
117888 ** the snippet. Snippet selection is done based on doclists only, so there
117889 ** is no way for fts3BestSnippet() to know whether or not the document 
117890 ** actually contains terms that follow the final highlighted term. 
117891 */
117892 static int fts3SnippetShift(
117893   Fts3Table *pTab,                /* FTS3 table snippet comes from */
117894   int nSnippet,                   /* Number of tokens desired for snippet */
117895   const char *zDoc,               /* Document text to extract snippet from */
117896   int nDoc,                       /* Size of buffer zDoc in bytes */
117897   int *piPos,                     /* IN/OUT: First token of snippet */
117898   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
117899 ){
117900   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
117901
117902   if( hlmask ){
117903     int nLeft;                    /* Tokens to the left of first highlight */
117904     int nRight;                   /* Tokens to the right of last highlight */
117905     int nDesired;                 /* Ideal number of tokens to shift forward */
117906
117907     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
117908     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
117909     nDesired = (nLeft-nRight)/2;
117910
117911     /* Ideally, the start of the snippet should be pushed forward in the
117912     ** document nDesired tokens. This block checks if there are actually
117913     ** nDesired tokens to the right of the snippet. If so, *piPos and
117914     ** *pHlMask are updated to shift the snippet nDesired tokens to the
117915     ** right. Otherwise, the snippet is shifted by the number of tokens
117916     ** available.
117917     */
117918     if( nDesired>0 ){
117919       int nShift;                 /* Number of tokens to shift snippet by */
117920       int iCurrent = 0;           /* Token counter */
117921       int rc;                     /* Return Code */
117922       sqlite3_tokenizer_module *pMod;
117923       sqlite3_tokenizer_cursor *pC;
117924       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
117925
117926       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
117927       ** or more tokens in zDoc/nDoc.
117928       */
117929       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
117930       if( rc!=SQLITE_OK ){
117931         return rc;
117932       }
117933       pC->pTokenizer = pTab->pTokenizer;
117934       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
117935         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
117936         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
117937       }
117938       pMod->xClose(pC);
117939       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
117940
117941       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
117942       assert( nShift<=nDesired );
117943       if( nShift>0 ){
117944         *piPos += nShift;
117945         *pHlmask = hlmask >> nShift;
117946       }
117947     }
117948   }
117949   return SQLITE_OK;
117950 }
117951
117952 /*
117953 ** Extract the snippet text for fragment pFragment from cursor pCsr and
117954 ** append it to string buffer pOut.
117955 */
117956 static int fts3SnippetText(
117957   Fts3Cursor *pCsr,               /* FTS3 Cursor */
117958   SnippetFragment *pFragment,     /* Snippet to extract */
117959   int iFragment,                  /* Fragment number */
117960   int isLast,                     /* True for final fragment in snippet */
117961   int nSnippet,                   /* Number of tokens in extracted snippet */
117962   const char *zOpen,              /* String inserted before highlighted term */
117963   const char *zClose,             /* String inserted after highlighted term */
117964   const char *zEllipsis,          /* String inserted between snippets */
117965   StrBuffer *pOut                 /* Write output here */
117966 ){
117967   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
117968   int rc;                         /* Return code */
117969   const char *zDoc;               /* Document text to extract snippet from */
117970   int nDoc;                       /* Size of zDoc in bytes */
117971   int iCurrent = 0;               /* Current token number of document */
117972   int iEnd = 0;                   /* Byte offset of end of current token */
117973   int isShiftDone = 0;            /* True after snippet is shifted */
117974   int iPos = pFragment->iPos;     /* First token of snippet */
117975   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
117976   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
117977   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
117978   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
117979   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
117980   int DUMMY1;                     /* Dummy argument used with tokenizer */
117981   
117982   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
117983   if( zDoc==0 ){
117984     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
117985       return SQLITE_NOMEM;
117986     }
117987     return SQLITE_OK;
117988   }
117989   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
117990
117991   /* Open a token cursor on the document. */
117992   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
117993   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
117994   if( rc!=SQLITE_OK ){
117995     return rc;
117996   }
117997   pC->pTokenizer = pTab->pTokenizer;
117998
117999   while( rc==SQLITE_OK ){
118000     int iBegin;                   /* Offset in zDoc of start of token */
118001     int iFin;                     /* Offset in zDoc of end of token */
118002     int isHighlight;              /* True for highlighted terms */
118003
118004     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
118005     if( rc!=SQLITE_OK ){
118006       if( rc==SQLITE_DONE ){
118007         /* Special case - the last token of the snippet is also the last token
118008         ** of the column. Append any punctuation that occurred between the end
118009         ** of the previous token and the end of the document to the output. 
118010         ** Then break out of the loop. */
118011         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
118012       }
118013       break;
118014     }
118015     if( iCurrent<iPos ){ continue; }
118016
118017     if( !isShiftDone ){
118018       int n = nDoc - iBegin;
118019       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
118020       isShiftDone = 1;
118021
118022       /* Now that the shift has been done, check if the initial "..." are
118023       ** required. They are required if (a) this is not the first fragment,
118024       ** or (b) this fragment does not begin at position 0 of its column. 
118025       */
118026       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
118027         rc = fts3StringAppend(pOut, zEllipsis, -1);
118028       }
118029       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
118030     }
118031
118032     if( iCurrent>=(iPos+nSnippet) ){
118033       if( isLast ){
118034         rc = fts3StringAppend(pOut, zEllipsis, -1);
118035       }
118036       break;
118037     }
118038
118039     /* Set isHighlight to true if this term should be highlighted. */
118040     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
118041
118042     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
118043     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
118044     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
118045     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
118046
118047     iEnd = iFin;
118048   }
118049
118050   pMod->xClose(pC);
118051   return rc;
118052 }
118053
118054
118055 /*
118056 ** This function is used to count the entries in a column-list (a 
118057 ** delta-encoded list of term offsets within a single column of a single 
118058 ** row). When this function is called, *ppCollist should point to the
118059 ** beginning of the first varint in the column-list (the varint that
118060 ** contains the position of the first matching term in the column data).
118061 ** Before returning, *ppCollist is set to point to the first byte after
118062 ** the last varint in the column-list (either the 0x00 signifying the end
118063 ** of the position-list, or the 0x01 that precedes the column number of
118064 ** the next column in the position-list).
118065 **
118066 ** The number of elements in the column-list is returned.
118067 */
118068 static int fts3ColumnlistCount(char **ppCollist){
118069   char *pEnd = *ppCollist;
118070   char c = 0;
118071   int nEntry = 0;
118072
118073   /* A column-list is terminated by either a 0x01 or 0x00. */
118074   while( 0xFE & (*pEnd | c) ){
118075     c = *pEnd++ & 0x80;
118076     if( !c ) nEntry++;
118077   }
118078
118079   *ppCollist = pEnd;
118080   return nEntry;
118081 }
118082
118083 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
118084   char *pCsr = *pp;
118085   while( *pCsr ){
118086     int nHit;
118087     sqlite3_int64 iCol = 0;
118088     if( *pCsr==0x01 ){
118089       pCsr++;
118090       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
118091     }
118092     nHit = fts3ColumnlistCount(&pCsr);
118093     assert( nHit>0 );
118094     if( isGlobal ){
118095       aOut[iCol*3+1]++;
118096     }
118097     aOut[iCol*3] += nHit;
118098   }
118099   pCsr++;
118100   *pp = pCsr;
118101 }
118102
118103 /*
118104 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
118105 ** for a single query. 
118106 **
118107 ** fts3ExprIterate() callback to load the 'global' elements of a
118108 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
118109 ** of the matchinfo array that are constant for all rows returned by the 
118110 ** current query.
118111 **
118112 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
118113 ** function populates Matchinfo.aMatchinfo[] as follows:
118114 **
118115 **   for(iCol=0; iCol<nCol; iCol++){
118116 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
118117 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
118118 **   }
118119 **
118120 ** where X is the number of matches for phrase iPhrase is column iCol of all
118121 ** rows of the table. Y is the number of rows for which column iCol contains
118122 ** at least one instance of phrase iPhrase.
118123 **
118124 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
118125 ** Y values are set to nDoc, where nDoc is the number of documents in the 
118126 ** file system. This is done because the full-text index doclist is required
118127 ** to calculate these values properly, and the full-text index doclist is
118128 ** not available for deferred tokens.
118129 */
118130 static int fts3ExprGlobalHitsCb(
118131   Fts3Expr *pExpr,                /* Phrase expression node */
118132   int iPhrase,                    /* Phrase number (numbered from zero) */
118133   void *pCtx                      /* Pointer to MatchInfo structure */
118134 ){
118135   MatchInfo *p = (MatchInfo *)pCtx;
118136   Fts3Cursor *pCsr = p->pCursor;
118137   char *pIter;
118138   char *pEnd;
118139   char *pFree = 0;
118140   u32 *aOut = &p->aMatchinfo[3*iPhrase*p->nCol];
118141
118142   assert( pExpr->isLoaded );
118143   assert( pExpr->eType==FTSQUERY_PHRASE );
118144
118145   if( pCsr->pDeferred ){
118146     Fts3Phrase *pPhrase = pExpr->pPhrase;
118147     int ii;
118148     for(ii=0; ii<pPhrase->nToken; ii++){
118149       if( pPhrase->aToken[ii].bFulltext ) break;
118150     }
118151     if( ii<pPhrase->nToken ){
118152       int nFree = 0;
118153       int rc = sqlite3Fts3ExprLoadFtDoclist(pCsr, pExpr, &pFree, &nFree);
118154       if( rc!=SQLITE_OK ) return rc;
118155       pIter = pFree;
118156       pEnd = &pFree[nFree];
118157     }else{
118158       int iCol;                   /* Column index */
118159       for(iCol=0; iCol<p->nCol; iCol++){
118160         aOut[iCol*3 + 1] = (u32)p->nDoc;
118161         aOut[iCol*3 + 2] = (u32)p->nDoc;
118162       }
118163       return SQLITE_OK;
118164     }
118165   }else{
118166     pIter = pExpr->aDoclist;
118167     pEnd = &pExpr->aDoclist[pExpr->nDoclist];
118168   }
118169
118170   /* Fill in the global hit count matrix row for this phrase. */
118171   while( pIter<pEnd ){
118172     while( *pIter++ & 0x80 );      /* Skip past docid. */
118173     fts3LoadColumnlistCounts(&pIter, &aOut[1], 1);
118174   }
118175
118176   sqlite3_free(pFree);
118177   return SQLITE_OK;
118178 }
118179
118180 /*
118181 ** fts3ExprIterate() callback used to collect the "local" part of the
118182 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
118183 ** array that are different for each row returned by the query.
118184 */
118185 static int fts3ExprLocalHitsCb(
118186   Fts3Expr *pExpr,                /* Phrase expression node */
118187   int iPhrase,                    /* Phrase number */
118188   void *pCtx                      /* Pointer to MatchInfo structure */
118189 ){
118190   MatchInfo *p = (MatchInfo *)pCtx;
118191
118192   if( pExpr->aDoclist ){
118193     char *pCsr;
118194     int iStart = iPhrase * p->nCol * 3;
118195     int i;
118196
118197     for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
118198
118199     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
118200     if( pCsr ){
118201       fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
118202     }
118203   }
118204
118205   return SQLITE_OK;
118206 }
118207
118208 static int fts3MatchinfoCheck(
118209   Fts3Table *pTab, 
118210   char cArg,
118211   char **pzErr
118212 ){
118213   if( (cArg==FTS3_MATCHINFO_NPHRASE)
118214    || (cArg==FTS3_MATCHINFO_NCOL)
118215    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
118216    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
118217    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
118218    || (cArg==FTS3_MATCHINFO_LCS)
118219    || (cArg==FTS3_MATCHINFO_HITS)
118220   ){
118221     return SQLITE_OK;
118222   }
118223   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
118224   return SQLITE_ERROR;
118225 }
118226
118227 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
118228   int nVal;                       /* Number of integers output by cArg */
118229
118230   switch( cArg ){
118231     case FTS3_MATCHINFO_NDOC:
118232     case FTS3_MATCHINFO_NPHRASE: 
118233     case FTS3_MATCHINFO_NCOL: 
118234       nVal = 1;
118235       break;
118236
118237     case FTS3_MATCHINFO_AVGLENGTH:
118238     case FTS3_MATCHINFO_LENGTH:
118239     case FTS3_MATCHINFO_LCS:
118240       nVal = pInfo->nCol;
118241       break;
118242
118243     default:
118244       assert( cArg==FTS3_MATCHINFO_HITS );
118245       nVal = pInfo->nCol * pInfo->nPhrase * 3;
118246       break;
118247   }
118248
118249   return nVal;
118250 }
118251
118252 static int fts3MatchinfoSelectDoctotal(
118253   Fts3Table *pTab,
118254   sqlite3_stmt **ppStmt,
118255   sqlite3_int64 *pnDoc,
118256   const char **paLen
118257 ){
118258   sqlite3_stmt *pStmt;
118259   const char *a;
118260   sqlite3_int64 nDoc;
118261
118262   if( !*ppStmt ){
118263     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
118264     if( rc!=SQLITE_OK ) return rc;
118265   }
118266   pStmt = *ppStmt;
118267
118268   a = sqlite3_column_blob(pStmt, 0);
118269   a += sqlite3Fts3GetVarint(a, &nDoc);
118270   *pnDoc = (u32)nDoc;
118271
118272   if( paLen ) *paLen = a;
118273   return SQLITE_OK;
118274 }
118275
118276 /*
118277 ** An instance of the following structure is used to store state while 
118278 ** iterating through a multi-column position-list corresponding to the
118279 ** hits for a single phrase on a single row in order to calculate the
118280 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
118281 */
118282 typedef struct LcsIterator LcsIterator;
118283 struct LcsIterator {
118284   Fts3Expr *pExpr;                /* Pointer to phrase expression */
118285   char *pRead;                    /* Cursor used to iterate through aDoclist */
118286   int iPosOffset;                 /* Tokens count up to end of this phrase */
118287   int iCol;                       /* Current column number */
118288   int iPos;                       /* Current position */
118289 };
118290
118291 /* 
118292 ** If LcsIterator.iCol is set to the following value, the iterator has
118293 ** finished iterating through all offsets for all columns.
118294 */
118295 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
118296
118297 static int fts3MatchinfoLcsCb(
118298   Fts3Expr *pExpr,                /* Phrase expression node */
118299   int iPhrase,                    /* Phrase number (numbered from zero) */
118300   void *pCtx                      /* Pointer to MatchInfo structure */
118301 ){
118302   LcsIterator *aIter = (LcsIterator *)pCtx;
118303   aIter[iPhrase].pExpr = pExpr;
118304   return SQLITE_OK;
118305 }
118306
118307 /*
118308 ** Advance the iterator passed as an argument to the next position. Return
118309 ** 1 if the iterator is at EOF or if it now points to the start of the
118310 ** position list for the next column.
118311 */
118312 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
118313   char *pRead = pIter->pRead;
118314   sqlite3_int64 iRead;
118315   int rc = 0;
118316
118317   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
118318   if( iRead==0 ){
118319     pIter->iCol = LCS_ITERATOR_FINISHED;
118320     rc = 1;
118321   }else{
118322     if( iRead==1 ){
118323       pRead += sqlite3Fts3GetVarint(pRead, &iRead);
118324       pIter->iCol = (int)iRead;
118325       pIter->iPos = pIter->iPosOffset;
118326       pRead += sqlite3Fts3GetVarint(pRead, &iRead);
118327       rc = 1;
118328     }
118329     pIter->iPos += (int)(iRead-2);
118330   }
118331
118332   pIter->pRead = pRead;
118333   return rc;
118334 }
118335   
118336 /*
118337 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
118338 **
118339 ** If the call is successful, the longest-common-substring lengths for each
118340 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
118341 ** array before returning. SQLITE_OK is returned in this case.
118342 **
118343 ** Otherwise, if an error occurs, an SQLite error code is returned and the
118344 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
118345 ** undefined.
118346 */
118347 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
118348   LcsIterator *aIter;
118349   int i;
118350   int iCol;
118351   int nToken = 0;
118352
118353   /* Allocate and populate the array of LcsIterator objects. The array
118354   ** contains one element for each matchable phrase in the query.
118355   **/
118356   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
118357   if( !aIter ) return SQLITE_NOMEM;
118358   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
118359   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
118360   for(i=0; i<pInfo->nPhrase; i++){
118361     LcsIterator *pIter = &aIter[i];
118362     nToken -= pIter->pExpr->pPhrase->nToken;
118363     pIter->iPosOffset = nToken;
118364     pIter->pRead = sqlite3Fts3FindPositions(pIter->pExpr, pCsr->iPrevId, -1);
118365     if( pIter->pRead ){
118366       pIter->iPos = pIter->iPosOffset;
118367       fts3LcsIteratorAdvance(&aIter[i]);
118368     }else{
118369       pIter->iCol = LCS_ITERATOR_FINISHED;
118370     }
118371   }
118372
118373   for(iCol=0; iCol<pInfo->nCol; iCol++){
118374     int nLcs = 0;                 /* LCS value for this column */
118375     int nLive = 0;                /* Number of iterators in aIter not at EOF */
118376
118377     /* Loop through the iterators in aIter[]. Set nLive to the number of
118378     ** iterators that point to a position-list corresponding to column iCol.
118379     */
118380     for(i=0; i<pInfo->nPhrase; i++){
118381       assert( aIter[i].iCol>=iCol );
118382       if( aIter[i].iCol==iCol ) nLive++;
118383     }
118384
118385     /* The following loop runs until all iterators in aIter[] have finished
118386     ** iterating through positions in column iCol. Exactly one of the 
118387     ** iterators is advanced each time the body of the loop is run.
118388     */
118389     while( nLive>0 ){
118390       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
118391       int nThisLcs = 0;           /* LCS for the current iterator positions */
118392
118393       for(i=0; i<pInfo->nPhrase; i++){
118394         LcsIterator *pIter = &aIter[i];
118395         if( iCol!=pIter->iCol ){  
118396           /* This iterator is already at EOF for this column. */
118397           nThisLcs = 0;
118398         }else{
118399           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
118400             pAdv = pIter;
118401           }
118402           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
118403             nThisLcs++;
118404           }else{
118405             nThisLcs = 1;
118406           }
118407           if( nThisLcs>nLcs ) nLcs = nThisLcs;
118408         }
118409       }
118410       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
118411     }
118412
118413     pInfo->aMatchinfo[iCol] = nLcs;
118414   }
118415
118416   sqlite3_free(aIter);
118417   return SQLITE_OK;
118418 }
118419
118420 /*
118421 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
118422 ** be returned by the matchinfo() function. Argument zArg contains the 
118423 ** format string passed as the second argument to matchinfo (or the
118424 ** default value "pcx" if no second argument was specified). The format
118425 ** string has already been validated and the pInfo->aMatchinfo[] array
118426 ** is guaranteed to be large enough for the output.
118427 **
118428 ** If bGlobal is true, then populate all fields of the matchinfo() output.
118429 ** If it is false, then assume that those fields that do not change between
118430 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
118431 ** have already been populated.
118432 **
118433 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
118434 ** occurs. If a value other than SQLITE_OK is returned, the state the
118435 ** pInfo->aMatchinfo[] buffer is left in is undefined.
118436 */
118437 static int fts3MatchinfoValues(
118438   Fts3Cursor *pCsr,               /* FTS3 cursor object */
118439   int bGlobal,                    /* True to grab the global stats */
118440   MatchInfo *pInfo,               /* Matchinfo context object */
118441   const char *zArg                /* Matchinfo format string */
118442 ){
118443   int rc = SQLITE_OK;
118444   int i;
118445   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118446   sqlite3_stmt *pSelect = 0;
118447
118448   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
118449
118450     switch( zArg[i] ){
118451       case FTS3_MATCHINFO_NPHRASE:
118452         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
118453         break;
118454
118455       case FTS3_MATCHINFO_NCOL:
118456         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
118457         break;
118458         
118459       case FTS3_MATCHINFO_NDOC:
118460         if( bGlobal ){
118461           sqlite3_int64 nDoc;
118462           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
118463           pInfo->aMatchinfo[0] = (u32)nDoc;
118464         }
118465         break;
118466
118467       case FTS3_MATCHINFO_AVGLENGTH: 
118468         if( bGlobal ){
118469           sqlite3_int64 nDoc;     /* Number of rows in table */
118470           const char *a;          /* Aggregate column length array */
118471
118472           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
118473           if( rc==SQLITE_OK ){
118474             int iCol;
118475             for(iCol=0; iCol<pInfo->nCol; iCol++){
118476               sqlite3_int64 nToken;
118477               a += sqlite3Fts3GetVarint(a, &nToken);
118478               pInfo->aMatchinfo[iCol] = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
118479             }
118480           }
118481         }
118482         break;
118483
118484       case FTS3_MATCHINFO_LENGTH: {
118485         sqlite3_stmt *pSelectDocsize = 0;
118486         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
118487         if( rc==SQLITE_OK ){
118488           int iCol;
118489           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
118490           for(iCol=0; iCol<pInfo->nCol; iCol++){
118491             sqlite3_int64 nToken;
118492             a += sqlite3Fts3GetVarint(a, &nToken);
118493             pInfo->aMatchinfo[iCol] = (u32)nToken;
118494           }
118495         }
118496         sqlite3_reset(pSelectDocsize);
118497         break;
118498       }
118499
118500       case FTS3_MATCHINFO_LCS:
118501         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
118502         if( rc==SQLITE_OK ){
118503           rc = fts3MatchinfoLcs(pCsr, pInfo);
118504         }
118505         break;
118506
118507       default: {
118508         Fts3Expr *pExpr;
118509         assert( zArg[i]==FTS3_MATCHINFO_HITS );
118510         pExpr = pCsr->pExpr;
118511         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
118512         if( rc!=SQLITE_OK ) break;
118513         if( bGlobal ){
118514           if( pCsr->pDeferred ){
118515             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
118516             if( rc!=SQLITE_OK ) break;
118517           }
118518           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
118519           if( rc!=SQLITE_OK ) break;
118520         }
118521         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
118522         break;
118523       }
118524     }
118525
118526     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
118527   }
118528
118529   sqlite3_reset(pSelect);
118530   return rc;
118531 }
118532
118533
118534 /*
118535 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
118536 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
118537 */
118538 static int fts3GetMatchinfo(
118539   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
118540   const char *zArg                /* Second argument to matchinfo() function */
118541 ){
118542   MatchInfo sInfo;
118543   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118544   int rc = SQLITE_OK;
118545   int bGlobal = 0;                /* Collect 'global' stats as well as local */
118546
118547   memset(&sInfo, 0, sizeof(MatchInfo));
118548   sInfo.pCursor = pCsr;
118549   sInfo.nCol = pTab->nColumn;
118550
118551   /* If there is cached matchinfo() data, but the format string for the 
118552   ** cache does not match the format string for this request, discard 
118553   ** the cached data. */
118554   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
118555     assert( pCsr->aMatchinfo );
118556     sqlite3_free(pCsr->aMatchinfo);
118557     pCsr->zMatchinfo = 0;
118558     pCsr->aMatchinfo = 0;
118559   }
118560
118561   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
118562   ** matchinfo function has been called for this query. In this case 
118563   ** allocate the array used to accumulate the matchinfo data and
118564   ** initialize those elements that are constant for every row.
118565   */
118566   if( pCsr->aMatchinfo==0 ){
118567     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
118568     int nArg;                     /* Bytes in zArg */
118569     int i;                        /* Used to iterate through zArg */
118570
118571     /* Determine the number of phrases in the query */
118572     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
118573     sInfo.nPhrase = pCsr->nPhrase;
118574
118575     /* Determine the number of integers in the buffer returned by this call. */
118576     for(i=0; zArg[i]; i++){
118577       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
118578     }
118579
118580     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
118581     nArg = (int)strlen(zArg);
118582     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
118583     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
118584
118585     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
118586     pCsr->nMatchinfo = nMatchinfo;
118587     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
118588     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
118589     pCsr->isMatchinfoNeeded = 1;
118590     bGlobal = 1;
118591   }
118592
118593   sInfo.aMatchinfo = pCsr->aMatchinfo;
118594   sInfo.nPhrase = pCsr->nPhrase;
118595   if( pCsr->isMatchinfoNeeded ){
118596     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
118597     pCsr->isMatchinfoNeeded = 0;
118598   }
118599
118600   return rc;
118601 }
118602
118603 /*
118604 ** Implementation of snippet() function.
118605 */
118606 SQLITE_PRIVATE void sqlite3Fts3Snippet(
118607   sqlite3_context *pCtx,          /* SQLite function call context */
118608   Fts3Cursor *pCsr,               /* Cursor object */
118609   const char *zStart,             /* Snippet start text - "<b>" */
118610   const char *zEnd,               /* Snippet end text - "</b>" */
118611   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
118612   int iCol,                       /* Extract snippet from this column */
118613   int nToken                      /* Approximate number of tokens in snippet */
118614 ){
118615   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118616   int rc = SQLITE_OK;
118617   int i;
118618   StrBuffer res = {0, 0, 0};
118619
118620   /* The returned text includes up to four fragments of text extracted from
118621   ** the data in the current row. The first iteration of the for(...) loop
118622   ** below attempts to locate a single fragment of text nToken tokens in 
118623   ** size that contains at least one instance of all phrases in the query
118624   ** expression that appear in the current row. If such a fragment of text
118625   ** cannot be found, the second iteration of the loop attempts to locate
118626   ** a pair of fragments, and so on.
118627   */
118628   int nSnippet = 0;               /* Number of fragments in this snippet */
118629   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
118630   int nFToken = -1;               /* Number of tokens in each fragment */
118631
118632   if( !pCsr->pExpr ){
118633     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
118634     return;
118635   }
118636
118637   for(nSnippet=1; 1; nSnippet++){
118638
118639     int iSnip;                    /* Loop counter 0..nSnippet-1 */
118640     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
118641     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
118642
118643     if( nToken>=0 ){
118644       nFToken = (nToken+nSnippet-1) / nSnippet;
118645     }else{
118646       nFToken = -1 * nToken;
118647     }
118648
118649     for(iSnip=0; iSnip<nSnippet; iSnip++){
118650       int iBestScore = -1;        /* Best score of columns checked so far */
118651       int iRead;                  /* Used to iterate through columns */
118652       SnippetFragment *pFragment = &aSnippet[iSnip];
118653
118654       memset(pFragment, 0, sizeof(*pFragment));
118655
118656       /* Loop through all columns of the table being considered for snippets.
118657       ** If the iCol argument to this function was negative, this means all
118658       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
118659       */
118660       for(iRead=0; iRead<pTab->nColumn; iRead++){
118661         SnippetFragment sF = {0, 0, 0, 0};
118662         int iS;
118663         if( iCol>=0 && iRead!=iCol ) continue;
118664
118665         /* Find the best snippet of nFToken tokens in column iRead. */
118666         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
118667         if( rc!=SQLITE_OK ){
118668           goto snippet_out;
118669         }
118670         if( iS>iBestScore ){
118671           *pFragment = sF;
118672           iBestScore = iS;
118673         }
118674       }
118675
118676       mCovered |= pFragment->covered;
118677     }
118678
118679     /* If all query phrases seen by fts3BestSnippet() are present in at least
118680     ** one of the nSnippet snippet fragments, break out of the loop.
118681     */
118682     assert( (mCovered&mSeen)==mCovered );
118683     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
118684   }
118685
118686   assert( nFToken>0 );
118687
118688   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
118689     rc = fts3SnippetText(pCsr, &aSnippet[i], 
118690         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
118691     );
118692   }
118693
118694  snippet_out:
118695   sqlite3Fts3SegmentsClose(pTab);
118696   if( rc!=SQLITE_OK ){
118697     sqlite3_result_error_code(pCtx, rc);
118698     sqlite3_free(res.z);
118699   }else{
118700     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
118701   }
118702 }
118703
118704
118705 typedef struct TermOffset TermOffset;
118706 typedef struct TermOffsetCtx TermOffsetCtx;
118707
118708 struct TermOffset {
118709   char *pList;                    /* Position-list */
118710   int iPos;                       /* Position just read from pList */
118711   int iOff;                       /* Offset of this term from read positions */
118712 };
118713
118714 struct TermOffsetCtx {
118715   int iCol;                       /* Column of table to populate aTerm for */
118716   int iTerm;
118717   sqlite3_int64 iDocid;
118718   TermOffset *aTerm;
118719 };
118720
118721 /*
118722 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
118723 */
118724 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
118725   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
118726   int nTerm;                      /* Number of tokens in phrase */
118727   int iTerm;                      /* For looping through nTerm phrase terms */
118728   char *pList;                    /* Pointer to position list for phrase */
118729   int iPos = 0;                   /* First position in position-list */
118730
118731   UNUSED_PARAMETER(iPhrase);
118732   pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
118733   nTerm = pExpr->pPhrase->nToken;
118734   if( pList ){
118735     fts3GetDeltaPosition(&pList, &iPos);
118736     assert( iPos>=0 );
118737   }
118738
118739   for(iTerm=0; iTerm<nTerm; iTerm++){
118740     TermOffset *pT = &p->aTerm[p->iTerm++];
118741     pT->iOff = nTerm-iTerm-1;
118742     pT->pList = pList;
118743     pT->iPos = iPos;
118744   }
118745
118746   return SQLITE_OK;
118747 }
118748
118749 /*
118750 ** Implementation of offsets() function.
118751 */
118752 SQLITE_PRIVATE void sqlite3Fts3Offsets(
118753   sqlite3_context *pCtx,          /* SQLite function call context */
118754   Fts3Cursor *pCsr                /* Cursor object */
118755 ){
118756   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118757   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
118758   const char *ZDUMMY;             /* Dummy argument used with xNext() */
118759   int NDUMMY;                     /* Dummy argument used with xNext() */
118760   int rc;                         /* Return Code */
118761   int nToken;                     /* Number of tokens in query */
118762   int iCol;                       /* Column currently being processed */
118763   StrBuffer res = {0, 0, 0};      /* Result string */
118764   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
118765
118766   if( !pCsr->pExpr ){
118767     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
118768     return;
118769   }
118770
118771   memset(&sCtx, 0, sizeof(sCtx));
118772   assert( pCsr->isRequireSeek==0 );
118773
118774   /* Count the number of terms in the query */
118775   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
118776   if( rc!=SQLITE_OK ) goto offsets_out;
118777
118778   /* Allocate the array of TermOffset iterators. */
118779   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
118780   if( 0==sCtx.aTerm ){
118781     rc = SQLITE_NOMEM;
118782     goto offsets_out;
118783   }
118784   sCtx.iDocid = pCsr->iPrevId;
118785
118786   /* Loop through the table columns, appending offset information to 
118787   ** string-buffer res for each column.
118788   */
118789   for(iCol=0; iCol<pTab->nColumn; iCol++){
118790     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
118791     int iStart;
118792     int iEnd;
118793     int iCurrent;
118794     const char *zDoc;
118795     int nDoc;
118796
118797     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
118798     ** no way that this operation can fail, so the return code from
118799     ** fts3ExprIterate() can be discarded.
118800     */
118801     sCtx.iCol = iCol;
118802     sCtx.iTerm = 0;
118803     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
118804
118805     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
118806     ** in column iCol, jump immediately to the next iteration of the loop.
118807     ** If an OOM occurs while retrieving the data (this can happen if SQLite
118808     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
118809     ** to the caller. 
118810     */
118811     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
118812     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
118813     if( zDoc==0 ){
118814       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
118815         continue;
118816       }
118817       rc = SQLITE_NOMEM;
118818       goto offsets_out;
118819     }
118820
118821     /* Initialize a tokenizer iterator to iterate through column iCol. */
118822     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
118823     if( rc!=SQLITE_OK ) goto offsets_out;
118824     pC->pTokenizer = pTab->pTokenizer;
118825
118826     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
118827     while( rc==SQLITE_OK ){
118828       int i;                      /* Used to loop through terms */
118829       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
118830       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
118831
118832       for(i=0; i<nToken; i++){
118833         TermOffset *pT = &sCtx.aTerm[i];
118834         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
118835           iMinPos = pT->iPos-pT->iOff;
118836           pTerm = pT;
118837         }
118838       }
118839
118840       if( !pTerm ){
118841         /* All offsets for this column have been gathered. */
118842         break;
118843       }else{
118844         assert( iCurrent<=iMinPos );
118845         if( 0==(0xFE&*pTerm->pList) ){
118846           pTerm->pList = 0;
118847         }else{
118848           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
118849         }
118850         while( rc==SQLITE_OK && iCurrent<iMinPos ){
118851           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
118852         }
118853         if( rc==SQLITE_OK ){
118854           char aBuffer[64];
118855           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
118856               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
118857           );
118858           rc = fts3StringAppend(&res, aBuffer, -1);
118859         }else if( rc==SQLITE_DONE ){
118860           rc = SQLITE_CORRUPT;
118861         }
118862       }
118863     }
118864     if( rc==SQLITE_DONE ){
118865       rc = SQLITE_OK;
118866     }
118867
118868     pMod->xClose(pC);
118869     if( rc!=SQLITE_OK ) goto offsets_out;
118870   }
118871
118872  offsets_out:
118873   sqlite3_free(sCtx.aTerm);
118874   assert( rc!=SQLITE_DONE );
118875   sqlite3Fts3SegmentsClose(pTab);
118876   if( rc!=SQLITE_OK ){
118877     sqlite3_result_error_code(pCtx,  rc);
118878     sqlite3_free(res.z);
118879   }else{
118880     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
118881   }
118882   return;
118883 }
118884
118885 /*
118886 ** Implementation of matchinfo() function.
118887 */
118888 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
118889   sqlite3_context *pContext,      /* Function call context */
118890   Fts3Cursor *pCsr,               /* FTS3 table cursor */
118891   const char *zArg                /* Second arg to matchinfo() function */
118892 ){
118893   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118894   int rc;
118895   int i;
118896   const char *zFormat;
118897
118898   if( zArg ){
118899     for(i=0; zArg[i]; i++){
118900       char *zErr = 0;
118901       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
118902         sqlite3_result_error(pContext, zErr, -1);
118903         sqlite3_free(zErr);
118904         return;
118905       }
118906     }
118907     zFormat = zArg;
118908   }else{
118909     zFormat = FTS3_MATCHINFO_DEFAULT;
118910   }
118911
118912   if( !pCsr->pExpr ){
118913     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
118914     return;
118915   }
118916
118917   /* Retrieve matchinfo() data. */
118918   rc = fts3GetMatchinfo(pCsr, zFormat);
118919   sqlite3Fts3SegmentsClose(pTab);
118920
118921   if( rc!=SQLITE_OK ){
118922     sqlite3_result_error_code(pContext, rc);
118923   }else{
118924     int n = pCsr->nMatchinfo * sizeof(u32);
118925     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
118926   }
118927 }
118928
118929 #endif
118930
118931 /************** End of fts3_snippet.c ****************************************/
118932 /************** Begin file rtree.c *******************************************/
118933 /*
118934 ** 2001 September 15
118935 **
118936 ** The author disclaims copyright to this source code.  In place of
118937 ** a legal notice, here is a blessing:
118938 **
118939 **    May you do good and not evil.
118940 **    May you find forgiveness for yourself and forgive others.
118941 **    May you share freely, never taking more than you give.
118942 **
118943 *************************************************************************
118944 ** This file contains code for implementations of the r-tree and r*-tree
118945 ** algorithms packaged as an SQLite virtual table module.
118946 */
118947
118948 /*
118949 ** Database Format of R-Tree Tables
118950 ** --------------------------------
118951 **
118952 ** The data structure for a single virtual r-tree table is stored in three 
118953 ** native SQLite tables declared as follows. In each case, the '%' character
118954 ** in the table name is replaced with the user-supplied name of the r-tree
118955 ** table.
118956 **
118957 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
118958 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
118959 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
118960 **
118961 ** The data for each node of the r-tree structure is stored in the %_node
118962 ** table. For each node that is not the root node of the r-tree, there is
118963 ** an entry in the %_parent table associating the node with its parent.
118964 ** And for each row of data in the table, there is an entry in the %_rowid
118965 ** table that maps from the entries rowid to the id of the node that it
118966 ** is stored on.
118967 **
118968 ** The root node of an r-tree always exists, even if the r-tree table is
118969 ** empty. The nodeno of the root node is always 1. All other nodes in the
118970 ** table must be the same size as the root node. The content of each node
118971 ** is formatted as follows:
118972 **
118973 **   1. If the node is the root node (node 1), then the first 2 bytes
118974 **      of the node contain the tree depth as a big-endian integer.
118975 **      For non-root nodes, the first 2 bytes are left unused.
118976 **
118977 **   2. The next 2 bytes contain the number of entries currently 
118978 **      stored in the node.
118979 **
118980 **   3. The remainder of the node contains the node entries. Each entry
118981 **      consists of a single 8-byte integer followed by an even number
118982 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
118983 **      of a record. For internal nodes it is the node number of a
118984 **      child page.
118985 */
118986
118987 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
118988
118989 /*
118990 ** This file contains an implementation of a couple of different variants
118991 ** of the r-tree algorithm. See the README file for further details. The 
118992 ** same data-structure is used for all, but the algorithms for insert and
118993 ** delete operations vary. The variants used are selected at compile time 
118994 ** by defining the following symbols:
118995 */
118996
118997 /* Either, both or none of the following may be set to activate 
118998 ** r*tree variant algorithms.
118999 */
119000 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
119001 #define VARIANT_RSTARTREE_REINSERT      1
119002
119003 /* 
119004 ** Exactly one of the following must be set to 1.
119005 */
119006 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
119007 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
119008 #define VARIANT_RSTARTREE_SPLIT         1
119009
119010 #define VARIANT_GUTTMAN_SPLIT \
119011         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
119012
119013 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
119014   #define PickNext QuadraticPickNext
119015   #define PickSeeds QuadraticPickSeeds
119016   #define AssignCells splitNodeGuttman
119017 #endif
119018 #if VARIANT_GUTTMAN_LINEAR_SPLIT
119019   #define PickNext LinearPickNext
119020   #define PickSeeds LinearPickSeeds
119021   #define AssignCells splitNodeGuttman
119022 #endif
119023 #if VARIANT_RSTARTREE_SPLIT
119024   #define AssignCells splitNodeStartree
119025 #endif
119026
119027 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
119028 # define NDEBUG 1
119029 #endif
119030
119031 #ifndef SQLITE_CORE
119032   SQLITE_EXTENSION_INIT1
119033 #else
119034 #endif
119035
119036
119037 #ifndef SQLITE_AMALGAMATION
119038 #include "sqlite3rtree.h"
119039 typedef sqlite3_int64 i64;
119040 typedef unsigned char u8;
119041 typedef unsigned int u32;
119042 #endif
119043
119044 /*  The following macro is used to suppress compiler warnings.
119045 */
119046 #ifndef UNUSED_PARAMETER
119047 # define UNUSED_PARAMETER(x) (void)(x)
119048 #endif
119049
119050 typedef struct Rtree Rtree;
119051 typedef struct RtreeCursor RtreeCursor;
119052 typedef struct RtreeNode RtreeNode;
119053 typedef struct RtreeCell RtreeCell;
119054 typedef struct RtreeConstraint RtreeConstraint;
119055 typedef struct RtreeMatchArg RtreeMatchArg;
119056 typedef struct RtreeGeomCallback RtreeGeomCallback;
119057 typedef union RtreeCoord RtreeCoord;
119058
119059 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
119060 #define RTREE_MAX_DIMENSIONS 5
119061
119062 /* Size of hash table Rtree.aHash. This hash table is not expected to
119063 ** ever contain very many entries, so a fixed number of buckets is 
119064 ** used.
119065 */
119066 #define HASHSIZE 128
119067
119068 /* 
119069 ** An rtree virtual-table object.
119070 */
119071 struct Rtree {
119072   sqlite3_vtab base;
119073   sqlite3 *db;                /* Host database connection */
119074   int iNodeSize;              /* Size in bytes of each node in the node table */
119075   int nDim;                   /* Number of dimensions */
119076   int nBytesPerCell;          /* Bytes consumed per cell */
119077   int iDepth;                 /* Current depth of the r-tree structure */
119078   char *zDb;                  /* Name of database containing r-tree table */
119079   char *zName;                /* Name of r-tree table */ 
119080   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
119081   int nBusy;                  /* Current number of users of this structure */
119082
119083   /* List of nodes removed during a CondenseTree operation. List is
119084   ** linked together via the pointer normally used for hash chains -
119085   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
119086   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
119087   */
119088   RtreeNode *pDeleted;
119089   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
119090
119091   /* Statements to read/write/delete a record from xxx_node */
119092   sqlite3_stmt *pReadNode;
119093   sqlite3_stmt *pWriteNode;
119094   sqlite3_stmt *pDeleteNode;
119095
119096   /* Statements to read/write/delete a record from xxx_rowid */
119097   sqlite3_stmt *pReadRowid;
119098   sqlite3_stmt *pWriteRowid;
119099   sqlite3_stmt *pDeleteRowid;
119100
119101   /* Statements to read/write/delete a record from xxx_parent */
119102   sqlite3_stmt *pReadParent;
119103   sqlite3_stmt *pWriteParent;
119104   sqlite3_stmt *pDeleteParent;
119105
119106   int eCoordType;
119107 };
119108
119109 /* Possible values for eCoordType: */
119110 #define RTREE_COORD_REAL32 0
119111 #define RTREE_COORD_INT32  1
119112
119113 /*
119114 ** The minimum number of cells allowed for a node is a third of the 
119115 ** maximum. In Gutman's notation:
119116 **
119117 **     m = M/3
119118 **
119119 ** If an R*-tree "Reinsert" operation is required, the same number of
119120 ** cells are removed from the overfull node and reinserted into the tree.
119121 */
119122 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
119123 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
119124 #define RTREE_MAXCELLS 51
119125
119126 /*
119127 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
119128 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
119129 ** Therefore all non-root nodes must contain at least 3 entries. Since 
119130 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
119131 ** 40 or less.
119132 */
119133 #define RTREE_MAX_DEPTH 40
119134
119135 /* 
119136 ** An rtree cursor object.
119137 */
119138 struct RtreeCursor {
119139   sqlite3_vtab_cursor base;
119140   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
119141   int iCell;                        /* Index of current cell in pNode */
119142   int iStrategy;                    /* Copy of idxNum search parameter */
119143   int nConstraint;                  /* Number of entries in aConstraint */
119144   RtreeConstraint *aConstraint;     /* Search constraints. */
119145 };
119146
119147 union RtreeCoord {
119148   float f;
119149   int i;
119150 };
119151
119152 /*
119153 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
119154 ** formatted as a double. This macro assumes that local variable pRtree points
119155 ** to the Rtree structure associated with the RtreeCoord.
119156 */
119157 #define DCOORD(coord) (                           \
119158   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
119159     ((double)coord.f) :                           \
119160     ((double)coord.i)                             \
119161 )
119162
119163 /*
119164 ** A search constraint.
119165 */
119166 struct RtreeConstraint {
119167   int iCoord;                     /* Index of constrained coordinate */
119168   int op;                         /* Constraining operation */
119169   double rValue;                  /* Constraint value. */
119170   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
119171   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
119172 };
119173
119174 /* Possible values for RtreeConstraint.op */
119175 #define RTREE_EQ    0x41
119176 #define RTREE_LE    0x42
119177 #define RTREE_LT    0x43
119178 #define RTREE_GE    0x44
119179 #define RTREE_GT    0x45
119180 #define RTREE_MATCH 0x46
119181
119182 /* 
119183 ** An rtree structure node.
119184 */
119185 struct RtreeNode {
119186   RtreeNode *pParent;               /* Parent node */
119187   i64 iNode;
119188   int nRef;
119189   int isDirty;
119190   u8 *zData;
119191   RtreeNode *pNext;                 /* Next node in this hash chain */
119192 };
119193 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
119194
119195 /* 
119196 ** Structure to store a deserialized rtree record.
119197 */
119198 struct RtreeCell {
119199   i64 iRowid;
119200   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
119201 };
119202
119203
119204 /*
119205 ** Value for the first field of every RtreeMatchArg object. The MATCH
119206 ** operator tests that the first field of a blob operand matches this
119207 ** value to avoid operating on invalid blobs (which could cause a segfault).
119208 */
119209 #define RTREE_GEOMETRY_MAGIC 0x891245AB
119210
119211 /*
119212 ** An instance of this structure must be supplied as a blob argument to
119213 ** the right-hand-side of an SQL MATCH operator used to constrain an
119214 ** r-tree query.
119215 */
119216 struct RtreeMatchArg {
119217   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
119218   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
119219   void *pContext;
119220   int nParam;
119221   double aParam[1];
119222 };
119223
119224 /*
119225 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
119226 ** a single instance of the following structure is allocated. It is used
119227 ** as the context for the user-function created by by s_r_g_c(). The object
119228 ** is eventually deleted by the destructor mechanism provided by
119229 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
119230 ** the geometry callback function).
119231 */
119232 struct RtreeGeomCallback {
119233   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
119234   void *pContext;
119235 };
119236
119237 #ifndef MAX
119238 # define MAX(x,y) ((x) < (y) ? (y) : (x))
119239 #endif
119240 #ifndef MIN
119241 # define MIN(x,y) ((x) > (y) ? (y) : (x))
119242 #endif
119243
119244 /*
119245 ** Functions to deserialize a 16 bit integer, 32 bit real number and
119246 ** 64 bit integer. The deserialized value is returned.
119247 */
119248 static int readInt16(u8 *p){
119249   return (p[0]<<8) + p[1];
119250 }
119251 static void readCoord(u8 *p, RtreeCoord *pCoord){
119252   u32 i = (
119253     (((u32)p[0]) << 24) + 
119254     (((u32)p[1]) << 16) + 
119255     (((u32)p[2]) <<  8) + 
119256     (((u32)p[3]) <<  0)
119257   );
119258   *(u32 *)pCoord = i;
119259 }
119260 static i64 readInt64(u8 *p){
119261   return (
119262     (((i64)p[0]) << 56) + 
119263     (((i64)p[1]) << 48) + 
119264     (((i64)p[2]) << 40) + 
119265     (((i64)p[3]) << 32) + 
119266     (((i64)p[4]) << 24) + 
119267     (((i64)p[5]) << 16) + 
119268     (((i64)p[6]) <<  8) + 
119269     (((i64)p[7]) <<  0)
119270   );
119271 }
119272
119273 /*
119274 ** Functions to serialize a 16 bit integer, 32 bit real number and
119275 ** 64 bit integer. The value returned is the number of bytes written
119276 ** to the argument buffer (always 2, 4 and 8 respectively).
119277 */
119278 static int writeInt16(u8 *p, int i){
119279   p[0] = (i>> 8)&0xFF;
119280   p[1] = (i>> 0)&0xFF;
119281   return 2;
119282 }
119283 static int writeCoord(u8 *p, RtreeCoord *pCoord){
119284   u32 i;
119285   assert( sizeof(RtreeCoord)==4 );
119286   assert( sizeof(u32)==4 );
119287   i = *(u32 *)pCoord;
119288   p[0] = (i>>24)&0xFF;
119289   p[1] = (i>>16)&0xFF;
119290   p[2] = (i>> 8)&0xFF;
119291   p[3] = (i>> 0)&0xFF;
119292   return 4;
119293 }
119294 static int writeInt64(u8 *p, i64 i){
119295   p[0] = (i>>56)&0xFF;
119296   p[1] = (i>>48)&0xFF;
119297   p[2] = (i>>40)&0xFF;
119298   p[3] = (i>>32)&0xFF;
119299   p[4] = (i>>24)&0xFF;
119300   p[5] = (i>>16)&0xFF;
119301   p[6] = (i>> 8)&0xFF;
119302   p[7] = (i>> 0)&0xFF;
119303   return 8;
119304 }
119305
119306 /*
119307 ** Increment the reference count of node p.
119308 */
119309 static void nodeReference(RtreeNode *p){
119310   if( p ){
119311     p->nRef++;
119312   }
119313 }
119314
119315 /*
119316 ** Clear the content of node p (set all bytes to 0x00).
119317 */
119318 static void nodeZero(Rtree *pRtree, RtreeNode *p){
119319   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
119320   p->isDirty = 1;
119321 }
119322
119323 /*
119324 ** Given a node number iNode, return the corresponding key to use
119325 ** in the Rtree.aHash table.
119326 */
119327 static int nodeHash(i64 iNode){
119328   return (
119329     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
119330     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
119331   ) % HASHSIZE;
119332 }
119333
119334 /*
119335 ** Search the node hash table for node iNode. If found, return a pointer
119336 ** to it. Otherwise, return 0.
119337 */
119338 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
119339   RtreeNode *p;
119340   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
119341   return p;
119342 }
119343
119344 /*
119345 ** Add node pNode to the node hash table.
119346 */
119347 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
119348   int iHash;
119349   assert( pNode->pNext==0 );
119350   iHash = nodeHash(pNode->iNode);
119351   pNode->pNext = pRtree->aHash[iHash];
119352   pRtree->aHash[iHash] = pNode;
119353 }
119354
119355 /*
119356 ** Remove node pNode from the node hash table.
119357 */
119358 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
119359   RtreeNode **pp;
119360   if( pNode->iNode!=0 ){
119361     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
119362     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
119363     *pp = pNode->pNext;
119364     pNode->pNext = 0;
119365   }
119366 }
119367
119368 /*
119369 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
119370 ** indicating that node has not yet been assigned a node number. It is
119371 ** assigned a node number when nodeWrite() is called to write the
119372 ** node contents out to the database.
119373 */
119374 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
119375   RtreeNode *pNode;
119376   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
119377   if( pNode ){
119378     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
119379     pNode->zData = (u8 *)&pNode[1];
119380     pNode->nRef = 1;
119381     pNode->pParent = pParent;
119382     pNode->isDirty = 1;
119383     nodeReference(pParent);
119384   }
119385   return pNode;
119386 }
119387
119388 /*
119389 ** Obtain a reference to an r-tree node.
119390 */
119391 static int
119392 nodeAcquire(
119393   Rtree *pRtree,             /* R-tree structure */
119394   i64 iNode,                 /* Node number to load */
119395   RtreeNode *pParent,        /* Either the parent node or NULL */
119396   RtreeNode **ppNode         /* OUT: Acquired node */
119397 ){
119398   int rc;
119399   int rc2 = SQLITE_OK;
119400   RtreeNode *pNode;
119401
119402   /* Check if the requested node is already in the hash table. If so,
119403   ** increase its reference count and return it.
119404   */
119405   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
119406     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
119407     if( pParent && !pNode->pParent ){
119408       nodeReference(pParent);
119409       pNode->pParent = pParent;
119410     }
119411     pNode->nRef++;
119412     *ppNode = pNode;
119413     return SQLITE_OK;
119414   }
119415
119416   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
119417   rc = sqlite3_step(pRtree->pReadNode);
119418   if( rc==SQLITE_ROW ){
119419     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
119420     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
119421       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
119422       if( !pNode ){
119423         rc2 = SQLITE_NOMEM;
119424       }else{
119425         pNode->pParent = pParent;
119426         pNode->zData = (u8 *)&pNode[1];
119427         pNode->nRef = 1;
119428         pNode->iNode = iNode;
119429         pNode->isDirty = 0;
119430         pNode->pNext = 0;
119431         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
119432         nodeReference(pParent);
119433       }
119434     }
119435   }
119436   rc = sqlite3_reset(pRtree->pReadNode);
119437   if( rc==SQLITE_OK ) rc = rc2;
119438
119439   /* If the root node was just loaded, set pRtree->iDepth to the height
119440   ** of the r-tree structure. A height of zero means all data is stored on
119441   ** the root node. A height of one means the children of the root node
119442   ** are the leaves, and so on. If the depth as specified on the root node
119443   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
119444   */
119445   if( pNode && iNode==1 ){
119446     pRtree->iDepth = readInt16(pNode->zData);
119447     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
119448       rc = SQLITE_CORRUPT;
119449     }
119450   }
119451
119452   /* If no error has occurred so far, check if the "number of entries"
119453   ** field on the node is too large. If so, set the return code to 
119454   ** SQLITE_CORRUPT.
119455   */
119456   if( pNode && rc==SQLITE_OK ){
119457     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
119458       rc = SQLITE_CORRUPT;
119459     }
119460   }
119461
119462   if( rc==SQLITE_OK ){
119463     if( pNode!=0 ){
119464       nodeHashInsert(pRtree, pNode);
119465     }else{
119466       rc = SQLITE_CORRUPT;
119467     }
119468     *ppNode = pNode;
119469   }else{
119470     sqlite3_free(pNode);
119471     *ppNode = 0;
119472   }
119473
119474   return rc;
119475 }
119476
119477 /*
119478 ** Overwrite cell iCell of node pNode with the contents of pCell.
119479 */
119480 static void nodeOverwriteCell(
119481   Rtree *pRtree, 
119482   RtreeNode *pNode,  
119483   RtreeCell *pCell, 
119484   int iCell
119485 ){
119486   int ii;
119487   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
119488   p += writeInt64(p, pCell->iRowid);
119489   for(ii=0; ii<(pRtree->nDim*2); ii++){
119490     p += writeCoord(p, &pCell->aCoord[ii]);
119491   }
119492   pNode->isDirty = 1;
119493 }
119494
119495 /*
119496 ** Remove cell the cell with index iCell from node pNode.
119497 */
119498 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
119499   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
119500   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
119501   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
119502   memmove(pDst, pSrc, nByte);
119503   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
119504   pNode->isDirty = 1;
119505 }
119506
119507 /*
119508 ** Insert the contents of cell pCell into node pNode. If the insert
119509 ** is successful, return SQLITE_OK.
119510 **
119511 ** If there is not enough free space in pNode, return SQLITE_FULL.
119512 */
119513 static int
119514 nodeInsertCell(
119515   Rtree *pRtree, 
119516   RtreeNode *pNode, 
119517   RtreeCell *pCell 
119518 ){
119519   int nCell;                    /* Current number of cells in pNode */
119520   int nMaxCell;                 /* Maximum number of cells for pNode */
119521
119522   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
119523   nCell = NCELL(pNode);
119524
119525   assert( nCell<=nMaxCell );
119526   if( nCell<nMaxCell ){
119527     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
119528     writeInt16(&pNode->zData[2], nCell+1);
119529     pNode->isDirty = 1;
119530   }
119531
119532   return (nCell==nMaxCell);
119533 }
119534
119535 /*
119536 ** If the node is dirty, write it out to the database.
119537 */
119538 static int
119539 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
119540   int rc = SQLITE_OK;
119541   if( pNode->isDirty ){
119542     sqlite3_stmt *p = pRtree->pWriteNode;
119543     if( pNode->iNode ){
119544       sqlite3_bind_int64(p, 1, pNode->iNode);
119545     }else{
119546       sqlite3_bind_null(p, 1);
119547     }
119548     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
119549     sqlite3_step(p);
119550     pNode->isDirty = 0;
119551     rc = sqlite3_reset(p);
119552     if( pNode->iNode==0 && rc==SQLITE_OK ){
119553       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
119554       nodeHashInsert(pRtree, pNode);
119555     }
119556   }
119557   return rc;
119558 }
119559
119560 /*
119561 ** Release a reference to a node. If the node is dirty and the reference
119562 ** count drops to zero, the node data is written to the database.
119563 */
119564 static int
119565 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
119566   int rc = SQLITE_OK;
119567   if( pNode ){
119568     assert( pNode->nRef>0 );
119569     pNode->nRef--;
119570     if( pNode->nRef==0 ){
119571       if( pNode->iNode==1 ){
119572         pRtree->iDepth = -1;
119573       }
119574       if( pNode->pParent ){
119575         rc = nodeRelease(pRtree, pNode->pParent);
119576       }
119577       if( rc==SQLITE_OK ){
119578         rc = nodeWrite(pRtree, pNode);
119579       }
119580       nodeHashDelete(pRtree, pNode);
119581       sqlite3_free(pNode);
119582     }
119583   }
119584   return rc;
119585 }
119586
119587 /*
119588 ** Return the 64-bit integer value associated with cell iCell of
119589 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
119590 ** an internal node, then the 64-bit integer is a child page number.
119591 */
119592 static i64 nodeGetRowid(
119593   Rtree *pRtree, 
119594   RtreeNode *pNode, 
119595   int iCell
119596 ){
119597   assert( iCell<NCELL(pNode) );
119598   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
119599 }
119600
119601 /*
119602 ** Return coordinate iCoord from cell iCell in node pNode.
119603 */
119604 static void nodeGetCoord(
119605   Rtree *pRtree, 
119606   RtreeNode *pNode, 
119607   int iCell,
119608   int iCoord,
119609   RtreeCoord *pCoord           /* Space to write result to */
119610 ){
119611   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
119612 }
119613
119614 /*
119615 ** Deserialize cell iCell of node pNode. Populate the structure pointed
119616 ** to by pCell with the results.
119617 */
119618 static void nodeGetCell(
119619   Rtree *pRtree, 
119620   RtreeNode *pNode, 
119621   int iCell,
119622   RtreeCell *pCell
119623 ){
119624   int ii;
119625   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
119626   for(ii=0; ii<pRtree->nDim*2; ii++){
119627     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
119628   }
119629 }
119630
119631
119632 /* Forward declaration for the function that does the work of
119633 ** the virtual table module xCreate() and xConnect() methods.
119634 */
119635 static int rtreeInit(
119636   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
119637 );
119638
119639 /* 
119640 ** Rtree virtual table module xCreate method.
119641 */
119642 static int rtreeCreate(
119643   sqlite3 *db,
119644   void *pAux,
119645   int argc, const char *const*argv,
119646   sqlite3_vtab **ppVtab,
119647   char **pzErr
119648 ){
119649   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
119650 }
119651
119652 /* 
119653 ** Rtree virtual table module xConnect method.
119654 */
119655 static int rtreeConnect(
119656   sqlite3 *db,
119657   void *pAux,
119658   int argc, const char *const*argv,
119659   sqlite3_vtab **ppVtab,
119660   char **pzErr
119661 ){
119662   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
119663 }
119664
119665 /*
119666 ** Increment the r-tree reference count.
119667 */
119668 static void rtreeReference(Rtree *pRtree){
119669   pRtree->nBusy++;
119670 }
119671
119672 /*
119673 ** Decrement the r-tree reference count. When the reference count reaches
119674 ** zero the structure is deleted.
119675 */
119676 static void rtreeRelease(Rtree *pRtree){
119677   pRtree->nBusy--;
119678   if( pRtree->nBusy==0 ){
119679     sqlite3_finalize(pRtree->pReadNode);
119680     sqlite3_finalize(pRtree->pWriteNode);
119681     sqlite3_finalize(pRtree->pDeleteNode);
119682     sqlite3_finalize(pRtree->pReadRowid);
119683     sqlite3_finalize(pRtree->pWriteRowid);
119684     sqlite3_finalize(pRtree->pDeleteRowid);
119685     sqlite3_finalize(pRtree->pReadParent);
119686     sqlite3_finalize(pRtree->pWriteParent);
119687     sqlite3_finalize(pRtree->pDeleteParent);
119688     sqlite3_free(pRtree);
119689   }
119690 }
119691
119692 /* 
119693 ** Rtree virtual table module xDisconnect method.
119694 */
119695 static int rtreeDisconnect(sqlite3_vtab *pVtab){
119696   rtreeRelease((Rtree *)pVtab);
119697   return SQLITE_OK;
119698 }
119699
119700 /* 
119701 ** Rtree virtual table module xDestroy method.
119702 */
119703 static int rtreeDestroy(sqlite3_vtab *pVtab){
119704   Rtree *pRtree = (Rtree *)pVtab;
119705   int rc;
119706   char *zCreate = sqlite3_mprintf(
119707     "DROP TABLE '%q'.'%q_node';"
119708     "DROP TABLE '%q'.'%q_rowid';"
119709     "DROP TABLE '%q'.'%q_parent';",
119710     pRtree->zDb, pRtree->zName, 
119711     pRtree->zDb, pRtree->zName,
119712     pRtree->zDb, pRtree->zName
119713   );
119714   if( !zCreate ){
119715     rc = SQLITE_NOMEM;
119716   }else{
119717     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
119718     sqlite3_free(zCreate);
119719   }
119720   if( rc==SQLITE_OK ){
119721     rtreeRelease(pRtree);
119722   }
119723
119724   return rc;
119725 }
119726
119727 /* 
119728 ** Rtree virtual table module xOpen method.
119729 */
119730 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
119731   int rc = SQLITE_NOMEM;
119732   RtreeCursor *pCsr;
119733
119734   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
119735   if( pCsr ){
119736     memset(pCsr, 0, sizeof(RtreeCursor));
119737     pCsr->base.pVtab = pVTab;
119738     rc = SQLITE_OK;
119739   }
119740   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
119741
119742   return rc;
119743 }
119744
119745
119746 /*
119747 ** Free the RtreeCursor.aConstraint[] array and its contents.
119748 */
119749 static void freeCursorConstraints(RtreeCursor *pCsr){
119750   if( pCsr->aConstraint ){
119751     int i;                        /* Used to iterate through constraint array */
119752     for(i=0; i<pCsr->nConstraint; i++){
119753       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
119754       if( pGeom ){
119755         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
119756         sqlite3_free(pGeom);
119757       }
119758     }
119759     sqlite3_free(pCsr->aConstraint);
119760     pCsr->aConstraint = 0;
119761   }
119762 }
119763
119764 /* 
119765 ** Rtree virtual table module xClose method.
119766 */
119767 static int rtreeClose(sqlite3_vtab_cursor *cur){
119768   Rtree *pRtree = (Rtree *)(cur->pVtab);
119769   int rc;
119770   RtreeCursor *pCsr = (RtreeCursor *)cur;
119771   freeCursorConstraints(pCsr);
119772   rc = nodeRelease(pRtree, pCsr->pNode);
119773   sqlite3_free(pCsr);
119774   return rc;
119775 }
119776
119777 /*
119778 ** Rtree virtual table module xEof method.
119779 **
119780 ** Return non-zero if the cursor does not currently point to a valid 
119781 ** record (i.e if the scan has finished), or zero otherwise.
119782 */
119783 static int rtreeEof(sqlite3_vtab_cursor *cur){
119784   RtreeCursor *pCsr = (RtreeCursor *)cur;
119785   return (pCsr->pNode==0);
119786 }
119787
119788 /*
119789 ** The r-tree constraint passed as the second argument to this function is
119790 ** guaranteed to be a MATCH constraint.
119791 */
119792 static int testRtreeGeom(
119793   Rtree *pRtree,                  /* R-Tree object */
119794   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
119795   RtreeCell *pCell,               /* Cell to test */
119796   int *pbRes                      /* OUT: Test result */
119797 ){
119798   int i;
119799   double aCoord[RTREE_MAX_DIMENSIONS*2];
119800   int nCoord = pRtree->nDim*2;
119801
119802   assert( pConstraint->op==RTREE_MATCH );
119803   assert( pConstraint->pGeom );
119804
119805   for(i=0; i<nCoord; i++){
119806     aCoord[i] = DCOORD(pCell->aCoord[i]);
119807   }
119808   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
119809 }
119810
119811 /* 
119812 ** Cursor pCursor currently points to a cell in a non-leaf page.
119813 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
119814 ** (excluded) by the constraints in the pCursor->aConstraint[] 
119815 ** array, or false otherwise.
119816 **
119817 ** Return SQLITE_OK if successful or an SQLite error code if an error
119818 ** occurs within a geometry callback.
119819 */
119820 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
119821   RtreeCell cell;
119822   int ii;
119823   int bRes = 0;
119824   int rc = SQLITE_OK;
119825
119826   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
119827   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
119828     RtreeConstraint *p = &pCursor->aConstraint[ii];
119829     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
119830     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
119831
119832     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
119833         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
119834     );
119835
119836     switch( p->op ){
119837       case RTREE_LE: case RTREE_LT: 
119838         bRes = p->rValue<cell_min; 
119839         break;
119840
119841       case RTREE_GE: case RTREE_GT: 
119842         bRes = p->rValue>cell_max; 
119843         break;
119844
119845       case RTREE_EQ:
119846         bRes = (p->rValue>cell_max || p->rValue<cell_min);
119847         break;
119848
119849       default: {
119850         assert( p->op==RTREE_MATCH );
119851         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
119852         bRes = !bRes;
119853         break;
119854       }
119855     }
119856   }
119857
119858   *pbEof = bRes;
119859   return rc;
119860 }
119861
119862 /* 
119863 ** Test if the cell that cursor pCursor currently points to
119864 ** would be filtered (excluded) by the constraints in the 
119865 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
119866 ** returning. If the cell is not filtered (excluded) by the constraints,
119867 ** set pbEof to zero.
119868 **
119869 ** Return SQLITE_OK if successful or an SQLite error code if an error
119870 ** occurs within a geometry callback.
119871 **
119872 ** This function assumes that the cell is part of a leaf node.
119873 */
119874 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
119875   RtreeCell cell;
119876   int ii;
119877   *pbEof = 0;
119878
119879   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
119880   for(ii=0; ii<pCursor->nConstraint; ii++){
119881     RtreeConstraint *p = &pCursor->aConstraint[ii];
119882     double coord = DCOORD(cell.aCoord[p->iCoord]);
119883     int res;
119884     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
119885         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
119886     );
119887     switch( p->op ){
119888       case RTREE_LE: res = (coord<=p->rValue); break;
119889       case RTREE_LT: res = (coord<p->rValue);  break;
119890       case RTREE_GE: res = (coord>=p->rValue); break;
119891       case RTREE_GT: res = (coord>p->rValue);  break;
119892       case RTREE_EQ: res = (coord==p->rValue); break;
119893       default: {
119894         int rc;
119895         assert( p->op==RTREE_MATCH );
119896         rc = testRtreeGeom(pRtree, p, &cell, &res);
119897         if( rc!=SQLITE_OK ){
119898           return rc;
119899         }
119900         break;
119901       }
119902     }
119903
119904     if( !res ){
119905       *pbEof = 1;
119906       return SQLITE_OK;
119907     }
119908   }
119909
119910   return SQLITE_OK;
119911 }
119912
119913 /*
119914 ** Cursor pCursor currently points at a node that heads a sub-tree of
119915 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
119916 ** to point to the left-most cell of the sub-tree that matches the 
119917 ** configured constraints.
119918 */
119919 static int descendToCell(
119920   Rtree *pRtree, 
119921   RtreeCursor *pCursor, 
119922   int iHeight,
119923   int *pEof                 /* OUT: Set to true if cannot descend */
119924 ){
119925   int isEof;
119926   int rc;
119927   int ii;
119928   RtreeNode *pChild;
119929   sqlite3_int64 iRowid;
119930
119931   RtreeNode *pSavedNode = pCursor->pNode;
119932   int iSavedCell = pCursor->iCell;
119933
119934   assert( iHeight>=0 );
119935
119936   if( iHeight==0 ){
119937     rc = testRtreeEntry(pRtree, pCursor, &isEof);
119938   }else{
119939     rc = testRtreeCell(pRtree, pCursor, &isEof);
119940   }
119941   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
119942     goto descend_to_cell_out;
119943   }
119944
119945   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
119946   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
119947   if( rc!=SQLITE_OK ){
119948     goto descend_to_cell_out;
119949   }
119950
119951   nodeRelease(pRtree, pCursor->pNode);
119952   pCursor->pNode = pChild;
119953   isEof = 1;
119954   for(ii=0; isEof && ii<NCELL(pChild); ii++){
119955     pCursor->iCell = ii;
119956     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
119957     if( rc!=SQLITE_OK ){
119958       goto descend_to_cell_out;
119959     }
119960   }
119961
119962   if( isEof ){
119963     assert( pCursor->pNode==pChild );
119964     nodeReference(pSavedNode);
119965     nodeRelease(pRtree, pChild);
119966     pCursor->pNode = pSavedNode;
119967     pCursor->iCell = iSavedCell;
119968   }
119969
119970 descend_to_cell_out:
119971   *pEof = isEof;
119972   return rc;
119973 }
119974
119975 /*
119976 ** One of the cells in node pNode is guaranteed to have a 64-bit 
119977 ** integer value equal to iRowid. Return the index of this cell.
119978 */
119979 static int nodeRowidIndex(
119980   Rtree *pRtree, 
119981   RtreeNode *pNode, 
119982   i64 iRowid,
119983   int *piIndex
119984 ){
119985   int ii;
119986   int nCell = NCELL(pNode);
119987   for(ii=0; ii<nCell; ii++){
119988     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
119989       *piIndex = ii;
119990       return SQLITE_OK;
119991     }
119992   }
119993   return SQLITE_CORRUPT;
119994 }
119995
119996 /*
119997 ** Return the index of the cell containing a pointer to node pNode
119998 ** in its parent. If pNode is the root node, return -1.
119999 */
120000 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
120001   RtreeNode *pParent = pNode->pParent;
120002   if( pParent ){
120003     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
120004   }
120005   *piIndex = -1;
120006   return SQLITE_OK;
120007 }
120008
120009 /* 
120010 ** Rtree virtual table module xNext method.
120011 */
120012 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
120013   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
120014   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
120015   int rc = SQLITE_OK;
120016
120017   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
120018   ** already at EOF. It is against the rules to call the xNext() method of
120019   ** a cursor that has already reached EOF.
120020   */
120021   assert( pCsr->pNode );
120022
120023   if( pCsr->iStrategy==1 ){
120024     /* This "scan" is a direct lookup by rowid. There is no next entry. */
120025     nodeRelease(pRtree, pCsr->pNode);
120026     pCsr->pNode = 0;
120027   }else{
120028     /* Move to the next entry that matches the configured constraints. */
120029     int iHeight = 0;
120030     while( pCsr->pNode ){
120031       RtreeNode *pNode = pCsr->pNode;
120032       int nCell = NCELL(pNode);
120033       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
120034         int isEof;
120035         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
120036         if( rc!=SQLITE_OK || !isEof ){
120037           return rc;
120038         }
120039       }
120040       pCsr->pNode = pNode->pParent;
120041       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
120042       if( rc!=SQLITE_OK ){
120043         return rc;
120044       }
120045       nodeReference(pCsr->pNode);
120046       nodeRelease(pRtree, pNode);
120047       iHeight++;
120048     }
120049   }
120050
120051   return rc;
120052 }
120053
120054 /* 
120055 ** Rtree virtual table module xRowid method.
120056 */
120057 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
120058   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
120059   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
120060
120061   assert(pCsr->pNode);
120062   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
120063
120064   return SQLITE_OK;
120065 }
120066
120067 /* 
120068 ** Rtree virtual table module xColumn method.
120069 */
120070 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
120071   Rtree *pRtree = (Rtree *)cur->pVtab;
120072   RtreeCursor *pCsr = (RtreeCursor *)cur;
120073
120074   if( i==0 ){
120075     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
120076     sqlite3_result_int64(ctx, iRowid);
120077   }else{
120078     RtreeCoord c;
120079     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
120080     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
120081       sqlite3_result_double(ctx, c.f);
120082     }else{
120083       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
120084       sqlite3_result_int(ctx, c.i);
120085     }
120086   }
120087
120088   return SQLITE_OK;
120089 }
120090
120091 /* 
120092 ** Use nodeAcquire() to obtain the leaf node containing the record with 
120093 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
120094 ** return SQLITE_OK. If there is no such record in the table, set
120095 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
120096 ** to zero and return an SQLite error code.
120097 */
120098 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
120099   int rc;
120100   *ppLeaf = 0;
120101   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
120102   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
120103     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
120104     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
120105     sqlite3_reset(pRtree->pReadRowid);
120106   }else{
120107     rc = sqlite3_reset(pRtree->pReadRowid);
120108   }
120109   return rc;
120110 }
120111
120112 /*
120113 ** This function is called to configure the RtreeConstraint object passed
120114 ** as the second argument for a MATCH constraint. The value passed as the
120115 ** first argument to this function is the right-hand operand to the MATCH
120116 ** operator.
120117 */
120118 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
120119   RtreeMatchArg *p;
120120   sqlite3_rtree_geometry *pGeom;
120121   int nBlob;
120122
120123   /* Check that value is actually a blob. */
120124   if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
120125
120126   /* Check that the blob is roughly the right size. */
120127   nBlob = sqlite3_value_bytes(pValue);
120128   if( nBlob<(int)sizeof(RtreeMatchArg) 
120129    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
120130   ){
120131     return SQLITE_ERROR;
120132   }
120133
120134   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
120135       sizeof(sqlite3_rtree_geometry) + nBlob
120136   );
120137   if( !pGeom ) return SQLITE_NOMEM;
120138   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
120139   p = (RtreeMatchArg *)&pGeom[1];
120140
120141   memcpy(p, sqlite3_value_blob(pValue), nBlob);
120142   if( p->magic!=RTREE_GEOMETRY_MAGIC 
120143    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
120144   ){
120145     sqlite3_free(pGeom);
120146     return SQLITE_ERROR;
120147   }
120148
120149   pGeom->pContext = p->pContext;
120150   pGeom->nParam = p->nParam;
120151   pGeom->aParam = p->aParam;
120152
120153   pCons->xGeom = p->xGeom;
120154   pCons->pGeom = pGeom;
120155   return SQLITE_OK;
120156 }
120157
120158 /* 
120159 ** Rtree virtual table module xFilter method.
120160 */
120161 static int rtreeFilter(
120162   sqlite3_vtab_cursor *pVtabCursor, 
120163   int idxNum, const char *idxStr,
120164   int argc, sqlite3_value **argv
120165 ){
120166   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
120167   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
120168
120169   RtreeNode *pRoot = 0;
120170   int ii;
120171   int rc = SQLITE_OK;
120172
120173   rtreeReference(pRtree);
120174
120175   freeCursorConstraints(pCsr);
120176   pCsr->iStrategy = idxNum;
120177
120178   if( idxNum==1 ){
120179     /* Special case - lookup by rowid. */
120180     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
120181     i64 iRowid = sqlite3_value_int64(argv[0]);
120182     rc = findLeafNode(pRtree, iRowid, &pLeaf);
120183     pCsr->pNode = pLeaf; 
120184     if( pLeaf ){
120185       assert( rc==SQLITE_OK );
120186       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
120187     }
120188   }else{
120189     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
120190     ** with the configured constraints. 
120191     */
120192     if( argc>0 ){
120193       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
120194       pCsr->nConstraint = argc;
120195       if( !pCsr->aConstraint ){
120196         rc = SQLITE_NOMEM;
120197       }else{
120198         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
120199         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
120200         for(ii=0; ii<argc; ii++){
120201           RtreeConstraint *p = &pCsr->aConstraint[ii];
120202           p->op = idxStr[ii*2];
120203           p->iCoord = idxStr[ii*2+1]-'a';
120204           if( p->op==RTREE_MATCH ){
120205             /* A MATCH operator. The right-hand-side must be a blob that
120206             ** can be cast into an RtreeMatchArg object. One created using
120207             ** an sqlite3_rtree_geometry_callback() SQL user function.
120208             */
120209             rc = deserializeGeometry(argv[ii], p);
120210             if( rc!=SQLITE_OK ){
120211               break;
120212             }
120213           }else{
120214             p->rValue = sqlite3_value_double(argv[ii]);
120215           }
120216         }
120217       }
120218     }
120219   
120220     if( rc==SQLITE_OK ){
120221       pCsr->pNode = 0;
120222       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
120223     }
120224     if( rc==SQLITE_OK ){
120225       int isEof = 1;
120226       int nCell = NCELL(pRoot);
120227       pCsr->pNode = pRoot;
120228       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
120229         assert( pCsr->pNode==pRoot );
120230         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
120231         if( !isEof ){
120232           break;
120233         }
120234       }
120235       if( rc==SQLITE_OK && isEof ){
120236         assert( pCsr->pNode==pRoot );
120237         nodeRelease(pRtree, pRoot);
120238         pCsr->pNode = 0;
120239       }
120240       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
120241     }
120242   }
120243
120244   rtreeRelease(pRtree);
120245   return rc;
120246 }
120247
120248 /*
120249 ** Rtree virtual table module xBestIndex method. There are three
120250 ** table scan strategies to choose from (in order from most to 
120251 ** least desirable):
120252 **
120253 **   idxNum     idxStr        Strategy
120254 **   ------------------------------------------------
120255 **     1        Unused        Direct lookup by rowid.
120256 **     2        See below     R-tree query or full-table scan.
120257 **   ------------------------------------------------
120258 **
120259 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
120260 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
120261 ** constraint used. The first two bytes of idxStr correspond to 
120262 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
120263 ** (argvIndex==1) etc.
120264 **
120265 ** The first of each pair of bytes in idxStr identifies the constraint
120266 ** operator as follows:
120267 **
120268 **   Operator    Byte Value
120269 **   ----------------------
120270 **      =        0x41 ('A')
120271 **     <=        0x42 ('B')
120272 **      <        0x43 ('C')
120273 **     >=        0x44 ('D')
120274 **      >        0x45 ('E')
120275 **   MATCH       0x46 ('F')
120276 **   ----------------------
120277 **
120278 ** The second of each pair of bytes identifies the coordinate column
120279 ** to which the constraint applies. The leftmost coordinate column
120280 ** is 'a', the second from the left 'b' etc.
120281 */
120282 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
120283   int rc = SQLITE_OK;
120284   int ii, cCol;
120285
120286   int iIdx = 0;
120287   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
120288   memset(zIdxStr, 0, sizeof(zIdxStr));
120289   UNUSED_PARAMETER(tab);
120290
120291   assert( pIdxInfo->idxStr==0 );
120292   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
120293     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
120294
120295     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
120296       /* We have an equality constraint on the rowid. Use strategy 1. */
120297       int jj;
120298       for(jj=0; jj<ii; jj++){
120299         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
120300         pIdxInfo->aConstraintUsage[jj].omit = 0;
120301       }
120302       pIdxInfo->idxNum = 1;
120303       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
120304       pIdxInfo->aConstraintUsage[jj].omit = 1;
120305
120306       /* This strategy involves a two rowid lookups on an B-Tree structures
120307       ** and then a linear search of an R-Tree node. This should be 
120308       ** considered almost as quick as a direct rowid lookup (for which 
120309       ** sqlite uses an internal cost of 0.0).
120310       */ 
120311       pIdxInfo->estimatedCost = 10.0;
120312       return SQLITE_OK;
120313     }
120314
120315     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
120316       int j, opmsk;
120317       static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
120318       u8 op = 0;
120319       switch( p->op ){
120320         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
120321         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
120322         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
120323         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
120324         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
120325         default:
120326           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
120327           op = RTREE_MATCH; 
120328           break;
120329       }
120330       assert( op!=0 );
120331
120332       /* Make sure this particular constraint has not been used before.
120333       ** If it has been used before, ignore it.
120334       **
120335       ** A <= or < can be used if there is a prior >= or >.
120336       ** A >= or > can be used if there is a prior < or <=.
120337       ** A <= or < is disqualified if there is a prior <=, <, or ==.
120338       ** A >= or > is disqualified if there is a prior >=, >, or ==.
120339       ** A == is disqualifed if there is any prior constraint.
120340       */
120341       assert( compatible[RTREE_EQ & 7]==0 );
120342       assert( compatible[RTREE_LT & 7]==1 );
120343       assert( compatible[RTREE_LE & 7]==1 );
120344       assert( compatible[RTREE_GT & 7]==2 );
120345       assert( compatible[RTREE_GE & 7]==2 );
120346       cCol = p->iColumn - 1 + 'a';
120347       opmsk = compatible[op & 7];
120348       for(j=0; j<iIdx; j+=2){
120349         if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
120350           op = 0;
120351           break;
120352         }
120353       }
120354       if( op ){
120355         assert( iIdx<sizeof(zIdxStr)-1 );
120356         zIdxStr[iIdx++] = op;
120357         zIdxStr[iIdx++] = cCol;
120358         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
120359         pIdxInfo->aConstraintUsage[ii].omit = 1;
120360       }
120361     }
120362   }
120363
120364   pIdxInfo->idxNum = 2;
120365   pIdxInfo->needToFreeIdxStr = 1;
120366   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
120367     return SQLITE_NOMEM;
120368   }
120369   assert( iIdx>=0 );
120370   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
120371   return rc;
120372 }
120373
120374 /*
120375 ** Return the N-dimensional volumn of the cell stored in *p.
120376 */
120377 static float cellArea(Rtree *pRtree, RtreeCell *p){
120378   float area = 1.0;
120379   int ii;
120380   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
120381     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
120382   }
120383   return area;
120384 }
120385
120386 /*
120387 ** Return the margin length of cell p. The margin length is the sum
120388 ** of the objects size in each dimension.
120389 */
120390 static float cellMargin(Rtree *pRtree, RtreeCell *p){
120391   float margin = 0.0;
120392   int ii;
120393   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
120394     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
120395   }
120396   return margin;
120397 }
120398
120399 /*
120400 ** Store the union of cells p1 and p2 in p1.
120401 */
120402 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
120403   int ii;
120404   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
120405     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
120406       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
120407       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
120408     }
120409   }else{
120410     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
120411       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
120412       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
120413     }
120414   }
120415 }
120416
120417 /*
120418 ** Return true if the area covered by p2 is a subset of the area covered
120419 ** by p1. False otherwise.
120420 */
120421 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
120422   int ii;
120423   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
120424   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
120425     RtreeCoord *a1 = &p1->aCoord[ii];
120426     RtreeCoord *a2 = &p2->aCoord[ii];
120427     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
120428      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
120429     ){
120430       return 0;
120431     }
120432   }
120433   return 1;
120434 }
120435
120436 /*
120437 ** Return the amount cell p would grow by if it were unioned with pCell.
120438 */
120439 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
120440   float area;
120441   RtreeCell cell;
120442   memcpy(&cell, p, sizeof(RtreeCell));
120443   area = cellArea(pRtree, &cell);
120444   cellUnion(pRtree, &cell, pCell);
120445   return (cellArea(pRtree, &cell)-area);
120446 }
120447
120448 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
120449 static float cellOverlap(
120450   Rtree *pRtree, 
120451   RtreeCell *p, 
120452   RtreeCell *aCell, 
120453   int nCell, 
120454   int iExclude
120455 ){
120456   int ii;
120457   float overlap = 0.0;
120458   for(ii=0; ii<nCell; ii++){
120459 #if VARIANT_RSTARTREE_CHOOSESUBTREE
120460     if( ii!=iExclude )
120461 #else
120462     assert( iExclude==-1 );
120463     UNUSED_PARAMETER(iExclude);
120464 #endif
120465     {
120466       int jj;
120467       float o = 1.0;
120468       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
120469         double x1;
120470         double x2;
120471
120472         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
120473         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
120474
120475         if( x2<x1 ){
120476           o = 0.0;
120477           break;
120478         }else{
120479           o = o * (x2-x1);
120480         }
120481       }
120482       overlap += o;
120483     }
120484   }
120485   return overlap;
120486 }
120487 #endif
120488
120489 #if VARIANT_RSTARTREE_CHOOSESUBTREE
120490 static float cellOverlapEnlargement(
120491   Rtree *pRtree, 
120492   RtreeCell *p, 
120493   RtreeCell *pInsert, 
120494   RtreeCell *aCell, 
120495   int nCell, 
120496   int iExclude
120497 ){
120498   float before;
120499   float after;
120500   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
120501   cellUnion(pRtree, p, pInsert);
120502   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
120503   return after-before;
120504 }
120505 #endif
120506
120507
120508 /*
120509 ** This function implements the ChooseLeaf algorithm from Gutman[84].
120510 ** ChooseSubTree in r*tree terminology.
120511 */
120512 static int ChooseLeaf(
120513   Rtree *pRtree,               /* Rtree table */
120514   RtreeCell *pCell,            /* Cell to insert into rtree */
120515   int iHeight,                 /* Height of sub-tree rooted at pCell */
120516   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
120517 ){
120518   int rc;
120519   int ii;
120520   RtreeNode *pNode;
120521   rc = nodeAcquire(pRtree, 1, 0, &pNode);
120522
120523   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
120524     int iCell;
120525     sqlite3_int64 iBest;
120526
120527     float fMinGrowth;
120528     float fMinArea;
120529     float fMinOverlap;
120530
120531     int nCell = NCELL(pNode);
120532     RtreeCell cell;
120533     RtreeNode *pChild;
120534
120535     RtreeCell *aCell = 0;
120536
120537 #if VARIANT_RSTARTREE_CHOOSESUBTREE
120538     if( ii==(pRtree->iDepth-1) ){
120539       int jj;
120540       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
120541       if( !aCell ){
120542         rc = SQLITE_NOMEM;
120543         nodeRelease(pRtree, pNode);
120544         pNode = 0;
120545         continue;
120546       }
120547       for(jj=0; jj<nCell; jj++){
120548         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
120549       }
120550     }
120551 #endif
120552
120553     /* Select the child node which will be enlarged the least if pCell
120554     ** is inserted into it. Resolve ties by choosing the entry with
120555     ** the smallest area.
120556     */
120557     for(iCell=0; iCell<nCell; iCell++){
120558       int bBest = 0;
120559       float growth;
120560       float area;
120561       float overlap = 0.0;
120562       nodeGetCell(pRtree, pNode, iCell, &cell);
120563       growth = cellGrowth(pRtree, &cell, pCell);
120564       area = cellArea(pRtree, &cell);
120565
120566 #if VARIANT_RSTARTREE_CHOOSESUBTREE
120567       if( ii==(pRtree->iDepth-1) ){
120568         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
120569       }
120570       if( (iCell==0) 
120571        || (overlap<fMinOverlap) 
120572        || (overlap==fMinOverlap && growth<fMinGrowth)
120573        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
120574       ){
120575         bBest = 1;
120576       }
120577 #else
120578       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
120579         bBest = 1;
120580       }
120581 #endif
120582       if( bBest ){
120583         fMinOverlap = overlap;
120584         fMinGrowth = growth;
120585         fMinArea = area;
120586         iBest = cell.iRowid;
120587       }
120588     }
120589
120590     sqlite3_free(aCell);
120591     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
120592     nodeRelease(pRtree, pNode);
120593     pNode = pChild;
120594   }
120595
120596   *ppLeaf = pNode;
120597   return rc;
120598 }
120599
120600 /*
120601 ** A cell with the same content as pCell has just been inserted into
120602 ** the node pNode. This function updates the bounding box cells in
120603 ** all ancestor elements.
120604 */
120605 static int AdjustTree(
120606   Rtree *pRtree,                    /* Rtree table */
120607   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
120608   RtreeCell *pCell                  /* This cell was just inserted */
120609 ){
120610   RtreeNode *p = pNode;
120611   while( p->pParent ){
120612     RtreeNode *pParent = p->pParent;
120613     RtreeCell cell;
120614     int iCell;
120615
120616     if( nodeParentIndex(pRtree, p, &iCell) ){
120617       return SQLITE_CORRUPT;
120618     }
120619
120620     nodeGetCell(pRtree, pParent, iCell, &cell);
120621     if( !cellContains(pRtree, &cell, pCell) ){
120622       cellUnion(pRtree, &cell, pCell);
120623       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
120624     }
120625  
120626     p = pParent;
120627   }
120628   return SQLITE_OK;
120629 }
120630
120631 /*
120632 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
120633 */
120634 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
120635   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
120636   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
120637   sqlite3_step(pRtree->pWriteRowid);
120638   return sqlite3_reset(pRtree->pWriteRowid);
120639 }
120640
120641 /*
120642 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
120643 */
120644 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
120645   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
120646   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
120647   sqlite3_step(pRtree->pWriteParent);
120648   return sqlite3_reset(pRtree->pWriteParent);
120649 }
120650
120651 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
120652
120653 #if VARIANT_GUTTMAN_LINEAR_SPLIT
120654 /*
120655 ** Implementation of the linear variant of the PickNext() function from
120656 ** Guttman[84].
120657 */
120658 static RtreeCell *LinearPickNext(
120659   Rtree *pRtree,
120660   RtreeCell *aCell, 
120661   int nCell, 
120662   RtreeCell *pLeftBox, 
120663   RtreeCell *pRightBox,
120664   int *aiUsed
120665 ){
120666   int ii;
120667   for(ii=0; aiUsed[ii]; ii++);
120668   aiUsed[ii] = 1;
120669   return &aCell[ii];
120670 }
120671
120672 /*
120673 ** Implementation of the linear variant of the PickSeeds() function from
120674 ** Guttman[84].
120675 */
120676 static void LinearPickSeeds(
120677   Rtree *pRtree,
120678   RtreeCell *aCell, 
120679   int nCell, 
120680   int *piLeftSeed, 
120681   int *piRightSeed
120682 ){
120683   int i;
120684   int iLeftSeed = 0;
120685   int iRightSeed = 1;
120686   float maxNormalInnerWidth = 0.0;
120687
120688   /* Pick two "seed" cells from the array of cells. The algorithm used
120689   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
120690   ** indices of the two seed cells in the array are stored in local
120691   ** variables iLeftSeek and iRightSeed.
120692   */
120693   for(i=0; i<pRtree->nDim; i++){
120694     float x1 = DCOORD(aCell[0].aCoord[i*2]);
120695     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
120696     float x3 = x1;
120697     float x4 = x2;
120698     int jj;
120699
120700     int iCellLeft = 0;
120701     int iCellRight = 0;
120702
120703     for(jj=1; jj<nCell; jj++){
120704       float left = DCOORD(aCell[jj].aCoord[i*2]);
120705       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
120706
120707       if( left<x1 ) x1 = left;
120708       if( right>x4 ) x4 = right;
120709       if( left>x3 ){
120710         x3 = left;
120711         iCellRight = jj;
120712       }
120713       if( right<x2 ){
120714         x2 = right;
120715         iCellLeft = jj;
120716       }
120717     }
120718
120719     if( x4!=x1 ){
120720       float normalwidth = (x3 - x2) / (x4 - x1);
120721       if( normalwidth>maxNormalInnerWidth ){
120722         iLeftSeed = iCellLeft;
120723         iRightSeed = iCellRight;
120724       }
120725     }
120726   }
120727
120728   *piLeftSeed = iLeftSeed;
120729   *piRightSeed = iRightSeed;
120730 }
120731 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
120732
120733 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
120734 /*
120735 ** Implementation of the quadratic variant of the PickNext() function from
120736 ** Guttman[84].
120737 */
120738 static RtreeCell *QuadraticPickNext(
120739   Rtree *pRtree,
120740   RtreeCell *aCell, 
120741   int nCell, 
120742   RtreeCell *pLeftBox, 
120743   RtreeCell *pRightBox,
120744   int *aiUsed
120745 ){
120746   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
120747
120748   int iSelect = -1;
120749   float fDiff;
120750   int ii;
120751   for(ii=0; ii<nCell; ii++){
120752     if( aiUsed[ii]==0 ){
120753       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
120754       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
120755       float diff = FABS(right-left);
120756       if( iSelect<0 || diff>fDiff ){
120757         fDiff = diff;
120758         iSelect = ii;
120759       }
120760     }
120761   }
120762   aiUsed[iSelect] = 1;
120763   return &aCell[iSelect];
120764 }
120765
120766 /*
120767 ** Implementation of the quadratic variant of the PickSeeds() function from
120768 ** Guttman[84].
120769 */
120770 static void QuadraticPickSeeds(
120771   Rtree *pRtree,
120772   RtreeCell *aCell, 
120773   int nCell, 
120774   int *piLeftSeed, 
120775   int *piRightSeed
120776 ){
120777   int ii;
120778   int jj;
120779
120780   int iLeftSeed = 0;
120781   int iRightSeed = 1;
120782   float fWaste = 0.0;
120783
120784   for(ii=0; ii<nCell; ii++){
120785     for(jj=ii+1; jj<nCell; jj++){
120786       float right = cellArea(pRtree, &aCell[jj]);
120787       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
120788       float waste = growth - right;
120789
120790       if( waste>fWaste ){
120791         iLeftSeed = ii;
120792         iRightSeed = jj;
120793         fWaste = waste;
120794       }
120795     }
120796   }
120797
120798   *piLeftSeed = iLeftSeed;
120799   *piRightSeed = iRightSeed;
120800 }
120801 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
120802
120803 /*
120804 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
120805 ** nIdx. The aIdx array contains the set of integers from 0 to 
120806 ** (nIdx-1) in no particular order. This function sorts the values
120807 ** in aIdx according to the indexed values in aDistance. For
120808 ** example, assuming the inputs:
120809 **
120810 **   aIdx      = { 0,   1,   2,   3 }
120811 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
120812 **
120813 ** this function sets the aIdx array to contain:
120814 **
120815 **   aIdx      = { 0,   1,   2,   3 }
120816 **
120817 ** The aSpare array is used as temporary working space by the
120818 ** sorting algorithm.
120819 */
120820 static void SortByDistance(
120821   int *aIdx, 
120822   int nIdx, 
120823   float *aDistance, 
120824   int *aSpare
120825 ){
120826   if( nIdx>1 ){
120827     int iLeft = 0;
120828     int iRight = 0;
120829
120830     int nLeft = nIdx/2;
120831     int nRight = nIdx-nLeft;
120832     int *aLeft = aIdx;
120833     int *aRight = &aIdx[nLeft];
120834
120835     SortByDistance(aLeft, nLeft, aDistance, aSpare);
120836     SortByDistance(aRight, nRight, aDistance, aSpare);
120837
120838     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
120839     aLeft = aSpare;
120840
120841     while( iLeft<nLeft || iRight<nRight ){
120842       if( iLeft==nLeft ){
120843         aIdx[iLeft+iRight] = aRight[iRight];
120844         iRight++;
120845       }else if( iRight==nRight ){
120846         aIdx[iLeft+iRight] = aLeft[iLeft];
120847         iLeft++;
120848       }else{
120849         float fLeft = aDistance[aLeft[iLeft]];
120850         float fRight = aDistance[aRight[iRight]];
120851         if( fLeft<fRight ){
120852           aIdx[iLeft+iRight] = aLeft[iLeft];
120853           iLeft++;
120854         }else{
120855           aIdx[iLeft+iRight] = aRight[iRight];
120856           iRight++;
120857         }
120858       }
120859     }
120860
120861 #if 0
120862     /* Check that the sort worked */
120863     {
120864       int jj;
120865       for(jj=1; jj<nIdx; jj++){
120866         float left = aDistance[aIdx[jj-1]];
120867         float right = aDistance[aIdx[jj]];
120868         assert( left<=right );
120869       }
120870     }
120871 #endif
120872   }
120873 }
120874
120875 /*
120876 ** Arguments aIdx, aCell and aSpare all point to arrays of size
120877 ** nIdx. The aIdx array contains the set of integers from 0 to 
120878 ** (nIdx-1) in no particular order. This function sorts the values
120879 ** in aIdx according to dimension iDim of the cells in aCell. The
120880 ** minimum value of dimension iDim is considered first, the
120881 ** maximum used to break ties.
120882 **
120883 ** The aSpare array is used as temporary working space by the
120884 ** sorting algorithm.
120885 */
120886 static void SortByDimension(
120887   Rtree *pRtree,
120888   int *aIdx, 
120889   int nIdx, 
120890   int iDim, 
120891   RtreeCell *aCell, 
120892   int *aSpare
120893 ){
120894   if( nIdx>1 ){
120895
120896     int iLeft = 0;
120897     int iRight = 0;
120898
120899     int nLeft = nIdx/2;
120900     int nRight = nIdx-nLeft;
120901     int *aLeft = aIdx;
120902     int *aRight = &aIdx[nLeft];
120903
120904     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
120905     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
120906
120907     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
120908     aLeft = aSpare;
120909     while( iLeft<nLeft || iRight<nRight ){
120910       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
120911       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
120912       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
120913       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
120914       if( (iLeft!=nLeft) && ((iRight==nRight)
120915        || (xleft1<xright1)
120916        || (xleft1==xright1 && xleft2<xright2)
120917       )){
120918         aIdx[iLeft+iRight] = aLeft[iLeft];
120919         iLeft++;
120920       }else{
120921         aIdx[iLeft+iRight] = aRight[iRight];
120922         iRight++;
120923       }
120924     }
120925
120926 #if 0
120927     /* Check that the sort worked */
120928     {
120929       int jj;
120930       for(jj=1; jj<nIdx; jj++){
120931         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
120932         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
120933         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
120934         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
120935         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
120936       }
120937     }
120938 #endif
120939   }
120940 }
120941
120942 #if VARIANT_RSTARTREE_SPLIT
120943 /*
120944 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
120945 */
120946 static int splitNodeStartree(
120947   Rtree *pRtree,
120948   RtreeCell *aCell,
120949   int nCell,
120950   RtreeNode *pLeft,
120951   RtreeNode *pRight,
120952   RtreeCell *pBboxLeft,
120953   RtreeCell *pBboxRight
120954 ){
120955   int **aaSorted;
120956   int *aSpare;
120957   int ii;
120958
120959   int iBestDim;
120960   int iBestSplit;
120961   float fBestMargin;
120962
120963   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
120964
120965   aaSorted = (int **)sqlite3_malloc(nByte);
120966   if( !aaSorted ){
120967     return SQLITE_NOMEM;
120968   }
120969
120970   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
120971   memset(aaSorted, 0, nByte);
120972   for(ii=0; ii<pRtree->nDim; ii++){
120973     int jj;
120974     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
120975     for(jj=0; jj<nCell; jj++){
120976       aaSorted[ii][jj] = jj;
120977     }
120978     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
120979   }
120980
120981   for(ii=0; ii<pRtree->nDim; ii++){
120982     float margin = 0.0;
120983     float fBestOverlap;
120984     float fBestArea;
120985     int iBestLeft;
120986     int nLeft;
120987
120988     for(
120989       nLeft=RTREE_MINCELLS(pRtree); 
120990       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
120991       nLeft++
120992     ){
120993       RtreeCell left;
120994       RtreeCell right;
120995       int kk;
120996       float overlap;
120997       float area;
120998
120999       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
121000       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
121001       for(kk=1; kk<(nCell-1); kk++){
121002         if( kk<nLeft ){
121003           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
121004         }else{
121005           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
121006         }
121007       }
121008       margin += cellMargin(pRtree, &left);
121009       margin += cellMargin(pRtree, &right);
121010       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
121011       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
121012       if( (nLeft==RTREE_MINCELLS(pRtree))
121013        || (overlap<fBestOverlap)
121014        || (overlap==fBestOverlap && area<fBestArea)
121015       ){
121016         iBestLeft = nLeft;
121017         fBestOverlap = overlap;
121018         fBestArea = area;
121019       }
121020     }
121021
121022     if( ii==0 || margin<fBestMargin ){
121023       iBestDim = ii;
121024       fBestMargin = margin;
121025       iBestSplit = iBestLeft;
121026     }
121027   }
121028
121029   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
121030   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
121031   for(ii=0; ii<nCell; ii++){
121032     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
121033     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
121034     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
121035     nodeInsertCell(pRtree, pTarget, pCell);
121036     cellUnion(pRtree, pBbox, pCell);
121037   }
121038
121039   sqlite3_free(aaSorted);
121040   return SQLITE_OK;
121041 }
121042 #endif
121043
121044 #if VARIANT_GUTTMAN_SPLIT
121045 /*
121046 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
121047 */
121048 static int splitNodeGuttman(
121049   Rtree *pRtree,
121050   RtreeCell *aCell,
121051   int nCell,
121052   RtreeNode *pLeft,
121053   RtreeNode *pRight,
121054   RtreeCell *pBboxLeft,
121055   RtreeCell *pBboxRight
121056 ){
121057   int iLeftSeed = 0;
121058   int iRightSeed = 1;
121059   int *aiUsed;
121060   int i;
121061
121062   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
121063   if( !aiUsed ){
121064     return SQLITE_NOMEM;
121065   }
121066   memset(aiUsed, 0, sizeof(int)*nCell);
121067
121068   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
121069
121070   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
121071   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
121072   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
121073   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
121074   aiUsed[iLeftSeed] = 1;
121075   aiUsed[iRightSeed] = 1;
121076
121077   for(i=nCell-2; i>0; i--){
121078     RtreeCell *pNext;
121079     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
121080     float diff =  
121081       cellGrowth(pRtree, pBboxLeft, pNext) - 
121082       cellGrowth(pRtree, pBboxRight, pNext)
121083     ;
121084     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
121085      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
121086     ){
121087       nodeInsertCell(pRtree, pRight, pNext);
121088       cellUnion(pRtree, pBboxRight, pNext);
121089     }else{
121090       nodeInsertCell(pRtree, pLeft, pNext);
121091       cellUnion(pRtree, pBboxLeft, pNext);
121092     }
121093   }
121094
121095   sqlite3_free(aiUsed);
121096   return SQLITE_OK;
121097 }
121098 #endif
121099
121100 static int updateMapping(
121101   Rtree *pRtree, 
121102   i64 iRowid, 
121103   RtreeNode *pNode, 
121104   int iHeight
121105 ){
121106   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
121107   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
121108   if( iHeight>0 ){
121109     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
121110     if( pChild ){
121111       nodeRelease(pRtree, pChild->pParent);
121112       nodeReference(pNode);
121113       pChild->pParent = pNode;
121114     }
121115   }
121116   return xSetMapping(pRtree, iRowid, pNode->iNode);
121117 }
121118
121119 static int SplitNode(
121120   Rtree *pRtree,
121121   RtreeNode *pNode,
121122   RtreeCell *pCell,
121123   int iHeight
121124 ){
121125   int i;
121126   int newCellIsRight = 0;
121127
121128   int rc = SQLITE_OK;
121129   int nCell = NCELL(pNode);
121130   RtreeCell *aCell;
121131   int *aiUsed;
121132
121133   RtreeNode *pLeft = 0;
121134   RtreeNode *pRight = 0;
121135
121136   RtreeCell leftbbox;
121137   RtreeCell rightbbox;
121138
121139   /* Allocate an array and populate it with a copy of pCell and 
121140   ** all cells from node pLeft. Then zero the original node.
121141   */
121142   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
121143   if( !aCell ){
121144     rc = SQLITE_NOMEM;
121145     goto splitnode_out;
121146   }
121147   aiUsed = (int *)&aCell[nCell+1];
121148   memset(aiUsed, 0, sizeof(int)*(nCell+1));
121149   for(i=0; i<nCell; i++){
121150     nodeGetCell(pRtree, pNode, i, &aCell[i]);
121151   }
121152   nodeZero(pRtree, pNode);
121153   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
121154   nCell++;
121155
121156   if( pNode->iNode==1 ){
121157     pRight = nodeNew(pRtree, pNode);
121158     pLeft = nodeNew(pRtree, pNode);
121159     pRtree->iDepth++;
121160     pNode->isDirty = 1;
121161     writeInt16(pNode->zData, pRtree->iDepth);
121162   }else{
121163     pLeft = pNode;
121164     pRight = nodeNew(pRtree, pLeft->pParent);
121165     nodeReference(pLeft);
121166   }
121167
121168   if( !pLeft || !pRight ){
121169     rc = SQLITE_NOMEM;
121170     goto splitnode_out;
121171   }
121172
121173   memset(pLeft->zData, 0, pRtree->iNodeSize);
121174   memset(pRight->zData, 0, pRtree->iNodeSize);
121175
121176   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
121177   if( rc!=SQLITE_OK ){
121178     goto splitnode_out;
121179   }
121180
121181   /* Ensure both child nodes have node numbers assigned to them by calling
121182   ** nodeWrite(). Node pRight always needs a node number, as it was created
121183   ** by nodeNew() above. But node pLeft sometimes already has a node number.
121184   ** In this case avoid the all to nodeWrite().
121185   */
121186   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
121187    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
121188   ){
121189     goto splitnode_out;
121190   }
121191
121192   rightbbox.iRowid = pRight->iNode;
121193   leftbbox.iRowid = pLeft->iNode;
121194
121195   if( pNode->iNode==1 ){
121196     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
121197     if( rc!=SQLITE_OK ){
121198       goto splitnode_out;
121199     }
121200   }else{
121201     RtreeNode *pParent = pLeft->pParent;
121202     int iCell;
121203     rc = nodeParentIndex(pRtree, pLeft, &iCell);
121204     if( rc==SQLITE_OK ){
121205       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
121206       rc = AdjustTree(pRtree, pParent, &leftbbox);
121207     }
121208     if( rc!=SQLITE_OK ){
121209       goto splitnode_out;
121210     }
121211   }
121212   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
121213     goto splitnode_out;
121214   }
121215
121216   for(i=0; i<NCELL(pRight); i++){
121217     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
121218     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
121219     if( iRowid==pCell->iRowid ){
121220       newCellIsRight = 1;
121221     }
121222     if( rc!=SQLITE_OK ){
121223       goto splitnode_out;
121224     }
121225   }
121226   if( pNode->iNode==1 ){
121227     for(i=0; i<NCELL(pLeft); i++){
121228       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
121229       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
121230       if( rc!=SQLITE_OK ){
121231         goto splitnode_out;
121232       }
121233     }
121234   }else if( newCellIsRight==0 ){
121235     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
121236   }
121237
121238   if( rc==SQLITE_OK ){
121239     rc = nodeRelease(pRtree, pRight);
121240     pRight = 0;
121241   }
121242   if( rc==SQLITE_OK ){
121243     rc = nodeRelease(pRtree, pLeft);
121244     pLeft = 0;
121245   }
121246
121247 splitnode_out:
121248   nodeRelease(pRtree, pRight);
121249   nodeRelease(pRtree, pLeft);
121250   sqlite3_free(aCell);
121251   return rc;
121252 }
121253
121254 /*
121255 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
121256 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
121257 ** the pLeaf->pParent chain all the way up to the root node.
121258 **
121259 ** This operation is required when a row is deleted (or updated - an update
121260 ** is implemented as a delete followed by an insert). SQLite provides the
121261 ** rowid of the row to delete, which can be used to find the leaf on which
121262 ** the entry resides (argument pLeaf). Once the leaf is located, this 
121263 ** function is called to determine its ancestry.
121264 */
121265 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
121266   int rc = SQLITE_OK;
121267   RtreeNode *pChild = pLeaf;
121268   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
121269     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
121270     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
121271     rc = sqlite3_step(pRtree->pReadParent);
121272     if( rc==SQLITE_ROW ){
121273       RtreeNode *pTest;           /* Used to test for reference loops */
121274       i64 iNode;                  /* Node number of parent node */
121275
121276       /* Before setting pChild->pParent, test that we are not creating a
121277       ** loop of references (as we would if, say, pChild==pParent). We don't
121278       ** want to do this as it leads to a memory leak when trying to delete
121279       ** the referenced counted node structures.
121280       */
121281       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
121282       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
121283       if( !pTest ){
121284         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
121285       }
121286     }
121287     rc = sqlite3_reset(pRtree->pReadParent);
121288     if( rc==SQLITE_OK ) rc = rc2;
121289     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT;
121290     pChild = pChild->pParent;
121291   }
121292   return rc;
121293 }
121294
121295 static int deleteCell(Rtree *, RtreeNode *, int, int);
121296
121297 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
121298   int rc;
121299   int rc2;
121300   RtreeNode *pParent;
121301   int iCell;
121302
121303   assert( pNode->nRef==1 );
121304
121305   /* Remove the entry in the parent cell. */
121306   rc = nodeParentIndex(pRtree, pNode, &iCell);
121307   if( rc==SQLITE_OK ){
121308     pParent = pNode->pParent;
121309     pNode->pParent = 0;
121310     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
121311   }
121312   rc2 = nodeRelease(pRtree, pParent);
121313   if( rc==SQLITE_OK ){
121314     rc = rc2;
121315   }
121316   if( rc!=SQLITE_OK ){
121317     return rc;
121318   }
121319
121320   /* Remove the xxx_node entry. */
121321   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
121322   sqlite3_step(pRtree->pDeleteNode);
121323   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
121324     return rc;
121325   }
121326
121327   /* Remove the xxx_parent entry. */
121328   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
121329   sqlite3_step(pRtree->pDeleteParent);
121330   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
121331     return rc;
121332   }
121333   
121334   /* Remove the node from the in-memory hash table and link it into
121335   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
121336   */
121337   nodeHashDelete(pRtree, pNode);
121338   pNode->iNode = iHeight;
121339   pNode->pNext = pRtree->pDeleted;
121340   pNode->nRef++;
121341   pRtree->pDeleted = pNode;
121342
121343   return SQLITE_OK;
121344 }
121345
121346 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
121347   RtreeNode *pParent = pNode->pParent;
121348   int rc = SQLITE_OK; 
121349   if( pParent ){
121350     int ii; 
121351     int nCell = NCELL(pNode);
121352     RtreeCell box;                            /* Bounding box for pNode */
121353     nodeGetCell(pRtree, pNode, 0, &box);
121354     for(ii=1; ii<nCell; ii++){
121355       RtreeCell cell;
121356       nodeGetCell(pRtree, pNode, ii, &cell);
121357       cellUnion(pRtree, &box, &cell);
121358     }
121359     box.iRowid = pNode->iNode;
121360     rc = nodeParentIndex(pRtree, pNode, &ii);
121361     if( rc==SQLITE_OK ){
121362       nodeOverwriteCell(pRtree, pParent, &box, ii);
121363       rc = fixBoundingBox(pRtree, pParent);
121364     }
121365   }
121366   return rc;
121367 }
121368
121369 /*
121370 ** Delete the cell at index iCell of node pNode. After removing the
121371 ** cell, adjust the r-tree data structure if required.
121372 */
121373 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
121374   RtreeNode *pParent;
121375   int rc;
121376
121377   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
121378     return rc;
121379   }
121380
121381   /* Remove the cell from the node. This call just moves bytes around
121382   ** the in-memory node image, so it cannot fail.
121383   */
121384   nodeDeleteCell(pRtree, pNode, iCell);
121385
121386   /* If the node is not the tree root and now has less than the minimum
121387   ** number of cells, remove it from the tree. Otherwise, update the
121388   ** cell in the parent node so that it tightly contains the updated
121389   ** node.
121390   */
121391   pParent = pNode->pParent;
121392   assert( pParent || pNode->iNode==1 );
121393   if( pParent ){
121394     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
121395       rc = removeNode(pRtree, pNode, iHeight);
121396     }else{
121397       rc = fixBoundingBox(pRtree, pNode);
121398     }
121399   }
121400
121401   return rc;
121402 }
121403
121404 static int Reinsert(
121405   Rtree *pRtree, 
121406   RtreeNode *pNode, 
121407   RtreeCell *pCell, 
121408   int iHeight
121409 ){
121410   int *aOrder;
121411   int *aSpare;
121412   RtreeCell *aCell;
121413   float *aDistance;
121414   int nCell;
121415   float aCenterCoord[RTREE_MAX_DIMENSIONS];
121416   int iDim;
121417   int ii;
121418   int rc = SQLITE_OK;
121419
121420   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
121421
121422   nCell = NCELL(pNode)+1;
121423
121424   /* Allocate the buffers used by this operation. The allocation is
121425   ** relinquished before this function returns.
121426   */
121427   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
121428     sizeof(RtreeCell) +         /* aCell array */
121429     sizeof(int)       +         /* aOrder array */
121430     sizeof(int)       +         /* aSpare array */
121431     sizeof(float)               /* aDistance array */
121432   ));
121433   if( !aCell ){
121434     return SQLITE_NOMEM;
121435   }
121436   aOrder    = (int *)&aCell[nCell];
121437   aSpare    = (int *)&aOrder[nCell];
121438   aDistance = (float *)&aSpare[nCell];
121439
121440   for(ii=0; ii<nCell; ii++){
121441     if( ii==(nCell-1) ){
121442       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
121443     }else{
121444       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
121445     }
121446     aOrder[ii] = ii;
121447     for(iDim=0; iDim<pRtree->nDim; iDim++){
121448       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
121449       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
121450     }
121451   }
121452   for(iDim=0; iDim<pRtree->nDim; iDim++){
121453     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
121454   }
121455
121456   for(ii=0; ii<nCell; ii++){
121457     aDistance[ii] = 0.0;
121458     for(iDim=0; iDim<pRtree->nDim; iDim++){
121459       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
121460           DCOORD(aCell[ii].aCoord[iDim*2]);
121461       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
121462     }
121463   }
121464
121465   SortByDistance(aOrder, nCell, aDistance, aSpare);
121466   nodeZero(pRtree, pNode);
121467
121468   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
121469     RtreeCell *p = &aCell[aOrder[ii]];
121470     nodeInsertCell(pRtree, pNode, p);
121471     if( p->iRowid==pCell->iRowid ){
121472       if( iHeight==0 ){
121473         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
121474       }else{
121475         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
121476       }
121477     }
121478   }
121479   if( rc==SQLITE_OK ){
121480     rc = fixBoundingBox(pRtree, pNode);
121481   }
121482   for(; rc==SQLITE_OK && ii<nCell; ii++){
121483     /* Find a node to store this cell in. pNode->iNode currently contains
121484     ** the height of the sub-tree headed by the cell.
121485     */
121486     RtreeNode *pInsert;
121487     RtreeCell *p = &aCell[aOrder[ii]];
121488     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
121489     if( rc==SQLITE_OK ){
121490       int rc2;
121491       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
121492       rc2 = nodeRelease(pRtree, pInsert);
121493       if( rc==SQLITE_OK ){
121494         rc = rc2;
121495       }
121496     }
121497   }
121498
121499   sqlite3_free(aCell);
121500   return rc;
121501 }
121502
121503 /*
121504 ** Insert cell pCell into node pNode. Node pNode is the head of a 
121505 ** subtree iHeight high (leaf nodes have iHeight==0).
121506 */
121507 static int rtreeInsertCell(
121508   Rtree *pRtree,
121509   RtreeNode *pNode,
121510   RtreeCell *pCell,
121511   int iHeight
121512 ){
121513   int rc = SQLITE_OK;
121514   if( iHeight>0 ){
121515     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
121516     if( pChild ){
121517       nodeRelease(pRtree, pChild->pParent);
121518       nodeReference(pNode);
121519       pChild->pParent = pNode;
121520     }
121521   }
121522   if( nodeInsertCell(pRtree, pNode, pCell) ){
121523 #if VARIANT_RSTARTREE_REINSERT
121524     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
121525       rc = SplitNode(pRtree, pNode, pCell, iHeight);
121526     }else{
121527       pRtree->iReinsertHeight = iHeight;
121528       rc = Reinsert(pRtree, pNode, pCell, iHeight);
121529     }
121530 #else
121531     rc = SplitNode(pRtree, pNode, pCell, iHeight);
121532 #endif
121533   }else{
121534     rc = AdjustTree(pRtree, pNode, pCell);
121535     if( rc==SQLITE_OK ){
121536       if( iHeight==0 ){
121537         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
121538       }else{
121539         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
121540       }
121541     }
121542   }
121543   return rc;
121544 }
121545
121546 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
121547   int ii;
121548   int rc = SQLITE_OK;
121549   int nCell = NCELL(pNode);
121550
121551   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
121552     RtreeNode *pInsert;
121553     RtreeCell cell;
121554     nodeGetCell(pRtree, pNode, ii, &cell);
121555
121556     /* Find a node to store this cell in. pNode->iNode currently contains
121557     ** the height of the sub-tree headed by the cell.
121558     */
121559     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
121560     if( rc==SQLITE_OK ){
121561       int rc2;
121562       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
121563       rc2 = nodeRelease(pRtree, pInsert);
121564       if( rc==SQLITE_OK ){
121565         rc = rc2;
121566       }
121567     }
121568   }
121569   return rc;
121570 }
121571
121572 /*
121573 ** Select a currently unused rowid for a new r-tree record.
121574 */
121575 static int newRowid(Rtree *pRtree, i64 *piRowid){
121576   int rc;
121577   sqlite3_bind_null(pRtree->pWriteRowid, 1);
121578   sqlite3_bind_null(pRtree->pWriteRowid, 2);
121579   sqlite3_step(pRtree->pWriteRowid);
121580   rc = sqlite3_reset(pRtree->pWriteRowid);
121581   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
121582   return rc;
121583 }
121584
121585 /*
121586 ** The xUpdate method for rtree module virtual tables.
121587 */
121588 static int rtreeUpdate(
121589   sqlite3_vtab *pVtab, 
121590   int nData, 
121591   sqlite3_value **azData, 
121592   sqlite_int64 *pRowid
121593 ){
121594   Rtree *pRtree = (Rtree *)pVtab;
121595   int rc = SQLITE_OK;
121596
121597   rtreeReference(pRtree);
121598
121599   assert(nData>=1);
121600
121601   /* If azData[0] is not an SQL NULL value, it is the rowid of a
121602   ** record to delete from the r-tree table. The following block does
121603   ** just that.
121604   */
121605   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
121606     i64 iDelete;                /* The rowid to delete */
121607     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
121608     int iCell;                  /* Index of iDelete cell in pLeaf */
121609     RtreeNode *pRoot;
121610
121611     /* Obtain a reference to the root node to initialise Rtree.iDepth */
121612     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
121613
121614     /* Obtain a reference to the leaf node that contains the entry 
121615     ** about to be deleted. 
121616     */
121617     if( rc==SQLITE_OK ){
121618       iDelete = sqlite3_value_int64(azData[0]);
121619       rc = findLeafNode(pRtree, iDelete, &pLeaf);
121620     }
121621
121622     /* Delete the cell in question from the leaf node. */
121623     if( rc==SQLITE_OK ){
121624       int rc2;
121625       rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
121626       if( rc==SQLITE_OK ){
121627         rc = deleteCell(pRtree, pLeaf, iCell, 0);
121628       }
121629       rc2 = nodeRelease(pRtree, pLeaf);
121630       if( rc==SQLITE_OK ){
121631         rc = rc2;
121632       }
121633     }
121634
121635     /* Delete the corresponding entry in the <rtree>_rowid table. */
121636     if( rc==SQLITE_OK ){
121637       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
121638       sqlite3_step(pRtree->pDeleteRowid);
121639       rc = sqlite3_reset(pRtree->pDeleteRowid);
121640     }
121641
121642     /* Check if the root node now has exactly one child. If so, remove
121643     ** it, schedule the contents of the child for reinsertion and 
121644     ** reduce the tree height by one.
121645     **
121646     ** This is equivalent to copying the contents of the child into
121647     ** the root node (the operation that Gutman's paper says to perform 
121648     ** in this scenario).
121649     */
121650     if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
121651       int rc2;
121652       RtreeNode *pChild;
121653       i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
121654       rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
121655       if( rc==SQLITE_OK ){
121656         rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
121657       }
121658       rc2 = nodeRelease(pRtree, pChild);
121659       if( rc==SQLITE_OK ) rc = rc2;
121660       if( rc==SQLITE_OK ){
121661         pRtree->iDepth--;
121662         writeInt16(pRoot->zData, pRtree->iDepth);
121663         pRoot->isDirty = 1;
121664       }
121665     }
121666
121667     /* Re-insert the contents of any underfull nodes removed from the tree. */
121668     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
121669       if( rc==SQLITE_OK ){
121670         rc = reinsertNodeContent(pRtree, pLeaf);
121671       }
121672       pRtree->pDeleted = pLeaf->pNext;
121673       sqlite3_free(pLeaf);
121674     }
121675
121676     /* Release the reference to the root node. */
121677     if( rc==SQLITE_OK ){
121678       rc = nodeRelease(pRtree, pRoot);
121679     }else{
121680       nodeRelease(pRtree, pRoot);
121681     }
121682   }
121683
121684   /* If the azData[] array contains more than one element, elements
121685   ** (azData[2]..azData[argc-1]) contain a new record to insert into
121686   ** the r-tree structure.
121687   */
121688   if( rc==SQLITE_OK && nData>1 ){
121689     /* Insert a new record into the r-tree */
121690     RtreeCell cell;
121691     int ii;
121692     RtreeNode *pLeaf;
121693
121694     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
121695     assert( nData==(pRtree->nDim*2 + 3) );
121696     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
121697       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
121698         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
121699         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
121700         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
121701           rc = SQLITE_CONSTRAINT;
121702           goto constraint;
121703         }
121704       }
121705     }else{
121706       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
121707         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
121708         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
121709         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
121710           rc = SQLITE_CONSTRAINT;
121711           goto constraint;
121712         }
121713       }
121714     }
121715
121716     /* Figure out the rowid of the new row. */
121717     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
121718       rc = newRowid(pRtree, &cell.iRowid);
121719     }else{
121720       cell.iRowid = sqlite3_value_int64(azData[2]);
121721       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
121722       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
121723         sqlite3_reset(pRtree->pReadRowid);
121724         rc = SQLITE_CONSTRAINT;
121725         goto constraint;
121726       }
121727       rc = sqlite3_reset(pRtree->pReadRowid);
121728     }
121729     *pRowid = cell.iRowid;
121730
121731     if( rc==SQLITE_OK ){
121732       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
121733     }
121734     if( rc==SQLITE_OK ){
121735       int rc2;
121736       pRtree->iReinsertHeight = -1;
121737       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
121738       rc2 = nodeRelease(pRtree, pLeaf);
121739       if( rc==SQLITE_OK ){
121740         rc = rc2;
121741       }
121742     }
121743   }
121744
121745 constraint:
121746   rtreeRelease(pRtree);
121747   return rc;
121748 }
121749
121750 /*
121751 ** The xRename method for rtree module virtual tables.
121752 */
121753 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
121754   Rtree *pRtree = (Rtree *)pVtab;
121755   int rc = SQLITE_NOMEM;
121756   char *zSql = sqlite3_mprintf(
121757     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
121758     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
121759     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
121760     , pRtree->zDb, pRtree->zName, zNewName 
121761     , pRtree->zDb, pRtree->zName, zNewName 
121762     , pRtree->zDb, pRtree->zName, zNewName
121763   );
121764   if( zSql ){
121765     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
121766     sqlite3_free(zSql);
121767   }
121768   return rc;
121769 }
121770
121771 static sqlite3_module rtreeModule = {
121772   0,                         /* iVersion */
121773   rtreeCreate,                /* xCreate - create a table */
121774   rtreeConnect,               /* xConnect - connect to an existing table */
121775   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
121776   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
121777   rtreeDestroy,               /* xDestroy - Drop a table */
121778   rtreeOpen,                  /* xOpen - open a cursor */
121779   rtreeClose,                 /* xClose - close a cursor */
121780   rtreeFilter,                /* xFilter - configure scan constraints */
121781   rtreeNext,                  /* xNext - advance a cursor */
121782   rtreeEof,                   /* xEof */
121783   rtreeColumn,                /* xColumn - read data */
121784   rtreeRowid,                 /* xRowid - read data */
121785   rtreeUpdate,                /* xUpdate - write data */
121786   0,                          /* xBegin - begin transaction */
121787   0,                          /* xSync - sync transaction */
121788   0,                          /* xCommit - commit transaction */
121789   0,                          /* xRollback - rollback transaction */
121790   0,                          /* xFindFunction - function overloading */
121791   rtreeRename                 /* xRename - rename the table */
121792 };
121793
121794 static int rtreeSqlInit(
121795   Rtree *pRtree, 
121796   sqlite3 *db, 
121797   const char *zDb, 
121798   const char *zPrefix, 
121799   int isCreate
121800 ){
121801   int rc = SQLITE_OK;
121802
121803   #define N_STATEMENT 9
121804   static const char *azSql[N_STATEMENT] = {
121805     /* Read and write the xxx_node table */
121806     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
121807     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
121808     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
121809
121810     /* Read and write the xxx_rowid table */
121811     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
121812     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
121813     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
121814
121815     /* Read and write the xxx_parent table */
121816     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
121817     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
121818     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
121819   };
121820   sqlite3_stmt **appStmt[N_STATEMENT];
121821   int i;
121822
121823   pRtree->db = db;
121824
121825   if( isCreate ){
121826     char *zCreate = sqlite3_mprintf(
121827 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
121828 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
121829 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
121830 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
121831       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
121832     );
121833     if( !zCreate ){
121834       return SQLITE_NOMEM;
121835     }
121836     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
121837     sqlite3_free(zCreate);
121838     if( rc!=SQLITE_OK ){
121839       return rc;
121840     }
121841   }
121842
121843   appStmt[0] = &pRtree->pReadNode;
121844   appStmt[1] = &pRtree->pWriteNode;
121845   appStmt[2] = &pRtree->pDeleteNode;
121846   appStmt[3] = &pRtree->pReadRowid;
121847   appStmt[4] = &pRtree->pWriteRowid;
121848   appStmt[5] = &pRtree->pDeleteRowid;
121849   appStmt[6] = &pRtree->pReadParent;
121850   appStmt[7] = &pRtree->pWriteParent;
121851   appStmt[8] = &pRtree->pDeleteParent;
121852
121853   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
121854     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
121855     if( zSql ){
121856       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
121857     }else{
121858       rc = SQLITE_NOMEM;
121859     }
121860     sqlite3_free(zSql);
121861   }
121862
121863   return rc;
121864 }
121865
121866 /*
121867 ** The second argument to this function contains the text of an SQL statement
121868 ** that returns a single integer value. The statement is compiled and executed
121869 ** using database connection db. If successful, the integer value returned
121870 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
121871 ** code is returned and the value of *piVal after returning is not defined.
121872 */
121873 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
121874   int rc = SQLITE_NOMEM;
121875   if( zSql ){
121876     sqlite3_stmt *pStmt = 0;
121877     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
121878     if( rc==SQLITE_OK ){
121879       if( SQLITE_ROW==sqlite3_step(pStmt) ){
121880         *piVal = sqlite3_column_int(pStmt, 0);
121881       }
121882       rc = sqlite3_finalize(pStmt);
121883     }
121884   }
121885   return rc;
121886 }
121887
121888 /*
121889 ** This function is called from within the xConnect() or xCreate() method to
121890 ** determine the node-size used by the rtree table being created or connected
121891 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
121892 ** Otherwise, an SQLite error code is returned.
121893 **
121894 ** If this function is being called as part of an xConnect(), then the rtree
121895 ** table already exists. In this case the node-size is determined by inspecting
121896 ** the root node of the tree.
121897 **
121898 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
121899 ** This ensures that each node is stored on a single database page. If the 
121900 ** database page-size is so large that more than RTREE_MAXCELLS entries 
121901 ** would fit in a single node, use a smaller node-size.
121902 */
121903 static int getNodeSize(
121904   sqlite3 *db,                    /* Database handle */
121905   Rtree *pRtree,                  /* Rtree handle */
121906   int isCreate                    /* True for xCreate, false for xConnect */
121907 ){
121908   int rc;
121909   char *zSql;
121910   if( isCreate ){
121911     int iPageSize;
121912     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
121913     rc = getIntFromStmt(db, zSql, &iPageSize);
121914     if( rc==SQLITE_OK ){
121915       pRtree->iNodeSize = iPageSize-64;
121916       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
121917         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
121918       }
121919     }
121920   }else{
121921     zSql = sqlite3_mprintf(
121922         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
121923         pRtree->zDb, pRtree->zName
121924     );
121925     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
121926   }
121927
121928   sqlite3_free(zSql);
121929   return rc;
121930 }
121931
121932 /* 
121933 ** This function is the implementation of both the xConnect and xCreate
121934 ** methods of the r-tree virtual table.
121935 **
121936 **   argv[0]   -> module name
121937 **   argv[1]   -> database name
121938 **   argv[2]   -> table name
121939 **   argv[...] -> column names...
121940 */
121941 static int rtreeInit(
121942   sqlite3 *db,                        /* Database connection */
121943   void *pAux,                         /* One of the RTREE_COORD_* constants */
121944   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
121945   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
121946   char **pzErr,                       /* OUT: Error message, if any */
121947   int isCreate                        /* True for xCreate, false for xConnect */
121948 ){
121949   int rc = SQLITE_OK;
121950   Rtree *pRtree;
121951   int nDb;              /* Length of string argv[1] */
121952   int nName;            /* Length of string argv[2] */
121953   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
121954
121955   const char *aErrMsg[] = {
121956     0,                                                    /* 0 */
121957     "Wrong number of columns for an rtree table",         /* 1 */
121958     "Too few columns for an rtree table",                 /* 2 */
121959     "Too many columns for an rtree table"                 /* 3 */
121960   };
121961
121962   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
121963   if( aErrMsg[iErr] ){
121964     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
121965     return SQLITE_ERROR;
121966   }
121967
121968   /* Allocate the sqlite3_vtab structure */
121969   nDb = strlen(argv[1]);
121970   nName = strlen(argv[2]);
121971   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
121972   if( !pRtree ){
121973     return SQLITE_NOMEM;
121974   }
121975   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
121976   pRtree->nBusy = 1;
121977   pRtree->base.pModule = &rtreeModule;
121978   pRtree->zDb = (char *)&pRtree[1];
121979   pRtree->zName = &pRtree->zDb[nDb+1];
121980   pRtree->nDim = (argc-4)/2;
121981   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
121982   pRtree->eCoordType = eCoordType;
121983   memcpy(pRtree->zDb, argv[1], nDb);
121984   memcpy(pRtree->zName, argv[2], nName);
121985
121986   /* Figure out the node size to use. */
121987   rc = getNodeSize(db, pRtree, isCreate);
121988
121989   /* Create/Connect to the underlying relational database schema. If
121990   ** that is successful, call sqlite3_declare_vtab() to configure
121991   ** the r-tree table schema.
121992   */
121993   if( rc==SQLITE_OK ){
121994     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
121995       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
121996     }else{
121997       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
121998       char *zTmp;
121999       int ii;
122000       for(ii=4; zSql && ii<argc; ii++){
122001         zTmp = zSql;
122002         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
122003         sqlite3_free(zTmp);
122004       }
122005       if( zSql ){
122006         zTmp = zSql;
122007         zSql = sqlite3_mprintf("%s);", zTmp);
122008         sqlite3_free(zTmp);
122009       }
122010       if( !zSql ){
122011         rc = SQLITE_NOMEM;
122012       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
122013         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
122014       }
122015       sqlite3_free(zSql);
122016     }
122017   }
122018
122019   if( rc==SQLITE_OK ){
122020     *ppVtab = (sqlite3_vtab *)pRtree;
122021   }else{
122022     rtreeRelease(pRtree);
122023   }
122024   return rc;
122025 }
122026
122027
122028 /*
122029 ** Implementation of a scalar function that decodes r-tree nodes to
122030 ** human readable strings. This can be used for debugging and analysis.
122031 **
122032 ** The scalar function takes two arguments, a blob of data containing
122033 ** an r-tree node, and the number of dimensions the r-tree indexes.
122034 ** For a two-dimensional r-tree structure called "rt", to deserialize
122035 ** all nodes, a statement like:
122036 **
122037 **   SELECT rtreenode(2, data) FROM rt_node;
122038 **
122039 ** The human readable string takes the form of a Tcl list with one
122040 ** entry for each cell in the r-tree node. Each entry is itself a
122041 ** list, containing the 8-byte rowid/pageno followed by the 
122042 ** <num-dimension>*2 coordinates.
122043 */
122044 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
122045   char *zText = 0;
122046   RtreeNode node;
122047   Rtree tree;
122048   int ii;
122049
122050   UNUSED_PARAMETER(nArg);
122051   memset(&node, 0, sizeof(RtreeNode));
122052   memset(&tree, 0, sizeof(Rtree));
122053   tree.nDim = sqlite3_value_int(apArg[0]);
122054   tree.nBytesPerCell = 8 + 8 * tree.nDim;
122055   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
122056
122057   for(ii=0; ii<NCELL(&node); ii++){
122058     char zCell[512];
122059     int nCell = 0;
122060     RtreeCell cell;
122061     int jj;
122062
122063     nodeGetCell(&tree, &node, ii, &cell);
122064     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
122065     nCell = strlen(zCell);
122066     for(jj=0; jj<tree.nDim*2; jj++){
122067       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
122068       nCell = strlen(zCell);
122069     }
122070
122071     if( zText ){
122072       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
122073       sqlite3_free(zText);
122074       zText = zTextNew;
122075     }else{
122076       zText = sqlite3_mprintf("{%s}", zCell);
122077     }
122078   }
122079   
122080   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
122081 }
122082
122083 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
122084   UNUSED_PARAMETER(nArg);
122085   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
122086    || sqlite3_value_bytes(apArg[0])<2
122087   ){
122088     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
122089   }else{
122090     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
122091     sqlite3_result_int(ctx, readInt16(zBlob));
122092   }
122093 }
122094
122095 /*
122096 ** Register the r-tree module with database handle db. This creates the
122097 ** virtual table module "rtree" and the debugging/analysis scalar 
122098 ** function "rtreenode".
122099 */
122100 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
122101   const int utf8 = SQLITE_UTF8;
122102   int rc;
122103
122104   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
122105   if( rc==SQLITE_OK ){
122106     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
122107   }
122108   if( rc==SQLITE_OK ){
122109     void *c = (void *)RTREE_COORD_REAL32;
122110     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
122111   }
122112   if( rc==SQLITE_OK ){
122113     void *c = (void *)RTREE_COORD_INT32;
122114     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
122115   }
122116
122117   return rc;
122118 }
122119
122120 /*
122121 ** A version of sqlite3_free() that can be used as a callback. This is used
122122 ** in two places - as the destructor for the blob value returned by the
122123 ** invocation of a geometry function, and as the destructor for the geometry
122124 ** functions themselves.
122125 */
122126 static void doSqlite3Free(void *p){
122127   sqlite3_free(p);
122128 }
122129
122130 /*
122131 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
122132 ** scalar user function. This C function is the callback used for all such
122133 ** registered SQL functions.
122134 **
122135 ** The scalar user functions return a blob that is interpreted by r-tree
122136 ** table MATCH operators.
122137 */
122138 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
122139   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
122140   RtreeMatchArg *pBlob;
122141   int nBlob;
122142
122143   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
122144   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
122145   if( !pBlob ){
122146     sqlite3_result_error_nomem(ctx);
122147   }else{
122148     int i;
122149     pBlob->magic = RTREE_GEOMETRY_MAGIC;
122150     pBlob->xGeom = pGeomCtx->xGeom;
122151     pBlob->pContext = pGeomCtx->pContext;
122152     pBlob->nParam = nArg;
122153     for(i=0; i<nArg; i++){
122154       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
122155     }
122156     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
122157   }
122158 }
122159
122160 /*
122161 ** Register a new geometry function for use with the r-tree MATCH operator.
122162 */
122163 SQLITE_API int sqlite3_rtree_geometry_callback(
122164   sqlite3 *db,
122165   const char *zGeom,
122166   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
122167   void *pContext
122168 ){
122169   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
122170
122171   /* Allocate and populate the context object. */
122172   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
122173   if( !pGeomCtx ) return SQLITE_NOMEM;
122174   pGeomCtx->xGeom = xGeom;
122175   pGeomCtx->pContext = pContext;
122176
122177   /* Create the new user-function. Register a destructor function to delete
122178   ** the context object when it is no longer required.  */
122179   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
122180       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
122181   );
122182 }
122183
122184 #if !SQLITE_CORE
122185 SQLITE_API int sqlite3_extension_init(
122186   sqlite3 *db,
122187   char **pzErrMsg,
122188   const sqlite3_api_routines *pApi
122189 ){
122190   SQLITE_EXTENSION_INIT2(pApi)
122191   return sqlite3RtreeInit(db);
122192 }
122193 #endif
122194
122195 #endif
122196
122197 /************** End of rtree.c ***********************************************/
122198 /************** Begin file icu.c *********************************************/
122199 /*
122200 ** 2007 May 6
122201 **
122202 ** The author disclaims copyright to this source code.  In place of
122203 ** a legal notice, here is a blessing:
122204 **
122205 **    May you do good and not evil.
122206 **    May you find forgiveness for yourself and forgive others.
122207 **    May you share freely, never taking more than you give.
122208 **
122209 *************************************************************************
122210 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
122211 **
122212 ** This file implements an integration between the ICU library 
122213 ** ("International Components for Unicode", an open-source library 
122214 ** for handling unicode data) and SQLite. The integration uses 
122215 ** ICU to provide the following to SQLite:
122216 **
122217 **   * An implementation of the SQL regexp() function (and hence REGEXP
122218 **     operator) using the ICU uregex_XX() APIs.
122219 **
122220 **   * Implementations of the SQL scalar upper() and lower() functions
122221 **     for case mapping.
122222 **
122223 **   * Integration of ICU and SQLite collation seqences.
122224 **
122225 **   * An implementation of the LIKE operator that uses ICU to 
122226 **     provide case-independent matching.
122227 */
122228
122229 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
122230
122231 /* Include ICU headers */
122232 #include <unicode/utypes.h>
122233 #include <unicode/uregex.h>
122234 #include <unicode/ustring.h>
122235 #include <unicode/ucol.h>
122236
122237
122238 #ifndef SQLITE_CORE
122239   SQLITE_EXTENSION_INIT1
122240 #else
122241 #endif
122242
122243 /*
122244 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
122245 ** operator.
122246 */
122247 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
122248 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
122249 #endif
122250
122251 /*
122252 ** Version of sqlite3_free() that is always a function, never a macro.
122253 */
122254 static void xFree(void *p){
122255   sqlite3_free(p);
122256 }
122257
122258 /*
122259 ** Compare two UTF-8 strings for equality where the first string is
122260 ** a "LIKE" expression. Return true (1) if they are the same and 
122261 ** false (0) if they are different.
122262 */
122263 static int icuLikeCompare(
122264   const uint8_t *zPattern,   /* LIKE pattern */
122265   const uint8_t *zString,    /* The UTF-8 string to compare against */
122266   const UChar32 uEsc         /* The escape character */
122267 ){
122268   static const int MATCH_ONE = (UChar32)'_';
122269   static const int MATCH_ALL = (UChar32)'%';
122270
122271   int iPattern = 0;       /* Current byte index in zPattern */
122272   int iString = 0;        /* Current byte index in zString */
122273
122274   int prevEscape = 0;     /* True if the previous character was uEsc */
122275
122276   while( zPattern[iPattern]!=0 ){
122277
122278     /* Read (and consume) the next character from the input pattern. */
122279     UChar32 uPattern;
122280     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
122281     assert(uPattern!=0);
122282
122283     /* There are now 4 possibilities:
122284     **
122285     **     1. uPattern is an unescaped match-all character "%",
122286     **     2. uPattern is an unescaped match-one character "_",
122287     **     3. uPattern is an unescaped escape character, or
122288     **     4. uPattern is to be handled as an ordinary character
122289     */
122290     if( !prevEscape && uPattern==MATCH_ALL ){
122291       /* Case 1. */
122292       uint8_t c;
122293
122294       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
122295       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
122296       ** test string.
122297       */
122298       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
122299         if( c==MATCH_ONE ){
122300           if( zString[iString]==0 ) return 0;
122301           U8_FWD_1_UNSAFE(zString, iString);
122302         }
122303         iPattern++;
122304       }
122305
122306       if( zPattern[iPattern]==0 ) return 1;
122307
122308       while( zString[iString] ){
122309         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
122310           return 1;
122311         }
122312         U8_FWD_1_UNSAFE(zString, iString);
122313       }
122314       return 0;
122315
122316     }else if( !prevEscape && uPattern==MATCH_ONE ){
122317       /* Case 2. */
122318       if( zString[iString]==0 ) return 0;
122319       U8_FWD_1_UNSAFE(zString, iString);
122320
122321     }else if( !prevEscape && uPattern==uEsc){
122322       /* Case 3. */
122323       prevEscape = 1;
122324
122325     }else{
122326       /* Case 4. */
122327       UChar32 uString;
122328       U8_NEXT_UNSAFE(zString, iString, uString);
122329       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
122330       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
122331       if( uString!=uPattern ){
122332         return 0;
122333       }
122334       prevEscape = 0;
122335     }
122336   }
122337
122338   return zString[iString]==0;
122339 }
122340
122341 /*
122342 ** Implementation of the like() SQL function.  This function implements
122343 ** the build-in LIKE operator.  The first argument to the function is the
122344 ** pattern and the second argument is the string.  So, the SQL statements:
122345 **
122346 **       A LIKE B
122347 **
122348 ** is implemented as like(B, A). If there is an escape character E, 
122349 **
122350 **       A LIKE B ESCAPE E
122351 **
122352 ** is mapped to like(B, A, E).
122353 */
122354 static void icuLikeFunc(
122355   sqlite3_context *context, 
122356   int argc, 
122357   sqlite3_value **argv
122358 ){
122359   const unsigned char *zA = sqlite3_value_text(argv[0]);
122360   const unsigned char *zB = sqlite3_value_text(argv[1]);
122361   UChar32 uEsc = 0;
122362
122363   /* Limit the length of the LIKE or GLOB pattern to avoid problems
122364   ** of deep recursion and N*N behavior in patternCompare().
122365   */
122366   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
122367     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
122368     return;
122369   }
122370
122371
122372   if( argc==3 ){
122373     /* The escape character string must consist of a single UTF-8 character.
122374     ** Otherwise, return an error.
122375     */
122376     int nE= sqlite3_value_bytes(argv[2]);
122377     const unsigned char *zE = sqlite3_value_text(argv[2]);
122378     int i = 0;
122379     if( zE==0 ) return;
122380     U8_NEXT(zE, i, nE, uEsc);
122381     if( i!=nE){
122382       sqlite3_result_error(context, 
122383           "ESCAPE expression must be a single character", -1);
122384       return;
122385     }
122386   }
122387
122388   if( zA && zB ){
122389     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
122390   }
122391 }
122392
122393 /*
122394 ** This function is called when an ICU function called from within
122395 ** the implementation of an SQL scalar function returns an error.
122396 **
122397 ** The scalar function context passed as the first argument is 
122398 ** loaded with an error message based on the following two args.
122399 */
122400 static void icuFunctionError(
122401   sqlite3_context *pCtx,       /* SQLite scalar function context */
122402   const char *zName,           /* Name of ICU function that failed */
122403   UErrorCode e                 /* Error code returned by ICU function */
122404 ){
122405   char zBuf[128];
122406   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
122407   zBuf[127] = '\0';
122408   sqlite3_result_error(pCtx, zBuf, -1);
122409 }
122410
122411 /*
122412 ** Function to delete compiled regexp objects. Registered as
122413 ** a destructor function with sqlite3_set_auxdata().
122414 */
122415 static void icuRegexpDelete(void *p){
122416   URegularExpression *pExpr = (URegularExpression *)p;
122417   uregex_close(pExpr);
122418 }
122419
122420 /*
122421 ** Implementation of SQLite REGEXP operator. This scalar function takes
122422 ** two arguments. The first is a regular expression pattern to compile
122423 ** the second is a string to match against that pattern. If either 
122424 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
122425 ** is 1 if the string matches the pattern, or 0 otherwise.
122426 **
122427 ** SQLite maps the regexp() function to the regexp() operator such
122428 ** that the following two are equivalent:
122429 **
122430 **     zString REGEXP zPattern
122431 **     regexp(zPattern, zString)
122432 **
122433 ** Uses the following ICU regexp APIs:
122434 **
122435 **     uregex_open()
122436 **     uregex_matches()
122437 **     uregex_close()
122438 */
122439 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
122440   UErrorCode status = U_ZERO_ERROR;
122441   URegularExpression *pExpr;
122442   UBool res;
122443   const UChar *zString = sqlite3_value_text16(apArg[1]);
122444
122445   /* If the left hand side of the regexp operator is NULL, 
122446   ** then the result is also NULL. 
122447   */
122448   if( !zString ){
122449     return;
122450   }
122451
122452   pExpr = sqlite3_get_auxdata(p, 0);
122453   if( !pExpr ){
122454     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
122455     if( !zPattern ){
122456       return;
122457     }
122458     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
122459
122460     if( U_SUCCESS(status) ){
122461       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
122462     }else{
122463       assert(!pExpr);
122464       icuFunctionError(p, "uregex_open", status);
122465       return;
122466     }
122467   }
122468
122469   /* Configure the text that the regular expression operates on. */
122470   uregex_setText(pExpr, zString, -1, &status);
122471   if( !U_SUCCESS(status) ){
122472     icuFunctionError(p, "uregex_setText", status);
122473     return;
122474   }
122475
122476   /* Attempt the match */
122477   res = uregex_matches(pExpr, 0, &status);
122478   if( !U_SUCCESS(status) ){
122479     icuFunctionError(p, "uregex_matches", status);
122480     return;
122481   }
122482
122483   /* Set the text that the regular expression operates on to a NULL
122484   ** pointer. This is not really necessary, but it is tidier than 
122485   ** leaving the regular expression object configured with an invalid
122486   ** pointer after this function returns.
122487   */
122488   uregex_setText(pExpr, 0, 0, &status);
122489
122490   /* Return 1 or 0. */
122491   sqlite3_result_int(p, res ? 1 : 0);
122492 }
122493
122494 /*
122495 ** Implementations of scalar functions for case mapping - upper() and 
122496 ** lower(). Function upper() converts its input to upper-case (ABC).
122497 ** Function lower() converts to lower-case (abc).
122498 **
122499 ** ICU provides two types of case mapping, "general" case mapping and
122500 ** "language specific". Refer to ICU documentation for the differences
122501 ** between the two.
122502 **
122503 ** To utilise "general" case mapping, the upper() or lower() scalar 
122504 ** functions are invoked with one argument:
122505 **
122506 **     upper('ABC') -> 'abc'
122507 **     lower('abc') -> 'ABC'
122508 **
122509 ** To access ICU "language specific" case mapping, upper() or lower()
122510 ** should be invoked with two arguments. The second argument is the name
122511 ** of the locale to use. Passing an empty string ("") or SQL NULL value
122512 ** as the second argument is the same as invoking the 1 argument version
122513 ** of upper() or lower().
122514 **
122515 **     lower('I', 'en_us') -> 'i'
122516 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
122517 **
122518 ** http://www.icu-project.org/userguide/posix.html#case_mappings
122519 */
122520 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
122521   const UChar *zInput;
122522   UChar *zOutput;
122523   int nInput;
122524   int nOutput;
122525
122526   UErrorCode status = U_ZERO_ERROR;
122527   const char *zLocale = 0;
122528
122529   assert(nArg==1 || nArg==2);
122530   if( nArg==2 ){
122531     zLocale = (const char *)sqlite3_value_text(apArg[1]);
122532   }
122533
122534   zInput = sqlite3_value_text16(apArg[0]);
122535   if( !zInput ){
122536     return;
122537   }
122538   nInput = sqlite3_value_bytes16(apArg[0]);
122539
122540   nOutput = nInput * 2 + 2;
122541   zOutput = sqlite3_malloc(nOutput);
122542   if( !zOutput ){
122543     return;
122544   }
122545
122546   if( sqlite3_user_data(p) ){
122547     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
122548   }else{
122549     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
122550   }
122551
122552   if( !U_SUCCESS(status) ){
122553     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
122554     return;
122555   }
122556
122557   sqlite3_result_text16(p, zOutput, -1, xFree);
122558 }
122559
122560 /*
122561 ** Collation sequence destructor function. The pCtx argument points to
122562 ** a UCollator structure previously allocated using ucol_open().
122563 */
122564 static void icuCollationDel(void *pCtx){
122565   UCollator *p = (UCollator *)pCtx;
122566   ucol_close(p);
122567 }
122568
122569 /*
122570 ** Collation sequence comparison function. The pCtx argument points to
122571 ** a UCollator structure previously allocated using ucol_open().
122572 */
122573 static int icuCollationColl(
122574   void *pCtx,
122575   int nLeft,
122576   const void *zLeft,
122577   int nRight,
122578   const void *zRight
122579 ){
122580   UCollationResult res;
122581   UCollator *p = (UCollator *)pCtx;
122582   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
122583   switch( res ){
122584     case UCOL_LESS:    return -1;
122585     case UCOL_GREATER: return +1;
122586     case UCOL_EQUAL:   return 0;
122587   }
122588   assert(!"Unexpected return value from ucol_strcoll()");
122589   return 0;
122590 }
122591
122592 /*
122593 ** Implementation of the scalar function icu_load_collation().
122594 **
122595 ** This scalar function is used to add ICU collation based collation 
122596 ** types to an SQLite database connection. It is intended to be called
122597 ** as follows:
122598 **
122599 **     SELECT icu_load_collation(<locale>, <collation-name>);
122600 **
122601 ** Where <locale> is a string containing an ICU locale identifier (i.e.
122602 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
122603 ** collation sequence to create.
122604 */
122605 static void icuLoadCollation(
122606   sqlite3_context *p, 
122607   int nArg, 
122608   sqlite3_value **apArg
122609 ){
122610   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
122611   UErrorCode status = U_ZERO_ERROR;
122612   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
122613   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
122614   UCollator *pUCollator;    /* ICU library collation object */
122615   int rc;                   /* Return code from sqlite3_create_collation_x() */
122616
122617   assert(nArg==2);
122618   zLocale = (const char *)sqlite3_value_text(apArg[0]);
122619   zName = (const char *)sqlite3_value_text(apArg[1]);
122620
122621   if( !zLocale || !zName ){
122622     return;
122623   }
122624
122625   pUCollator = ucol_open(zLocale, &status);
122626   if( !U_SUCCESS(status) ){
122627     icuFunctionError(p, "ucol_open", status);
122628     return;
122629   }
122630   assert(p);
122631
122632   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
122633       icuCollationColl, icuCollationDel
122634   );
122635   if( rc!=SQLITE_OK ){
122636     ucol_close(pUCollator);
122637     sqlite3_result_error(p, "Error registering collation function", -1);
122638   }
122639 }
122640
122641 /*
122642 ** Register the ICU extension functions with database db.
122643 */
122644 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
122645   struct IcuScalar {
122646     const char *zName;                        /* Function name */
122647     int nArg;                                 /* Number of arguments */
122648     int enc;                                  /* Optimal text encoding */
122649     void *pContext;                           /* sqlite3_user_data() context */
122650     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
122651   } scalars[] = {
122652     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
122653
122654     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
122655     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
122656     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
122657     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
122658
122659     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
122660     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
122661     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
122662     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
122663
122664     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
122665     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
122666
122667     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
122668   };
122669
122670   int rc = SQLITE_OK;
122671   int i;
122672
122673   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
122674     struct IcuScalar *p = &scalars[i];
122675     rc = sqlite3_create_function(
122676         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
122677     );
122678   }
122679
122680   return rc;
122681 }
122682
122683 #if !SQLITE_CORE
122684 SQLITE_API int sqlite3_extension_init(
122685   sqlite3 *db, 
122686   char **pzErrMsg,
122687   const sqlite3_api_routines *pApi
122688 ){
122689   SQLITE_EXTENSION_INIT2(pApi)
122690   return sqlite3IcuInit(db);
122691 }
122692 #endif
122693
122694 #endif
122695
122696 /************** End of icu.c *************************************************/
122697 /************** Begin file fts3_icu.c ****************************************/
122698 /*
122699 ** 2007 June 22
122700 **
122701 ** The author disclaims copyright to this source code.  In place of
122702 ** a legal notice, here is a blessing:
122703 **
122704 **    May you do good and not evil.
122705 **    May you find forgiveness for yourself and forgive others.
122706 **    May you share freely, never taking more than you give.
122707 **
122708 *************************************************************************
122709 ** This file implements a tokenizer for fts3 based on the ICU library.
122710 ** 
122711 ** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
122712 */
122713
122714 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122715 #ifdef SQLITE_ENABLE_ICU
122716
122717
122718 #include <unicode/ubrk.h>
122719 #include <unicode/utf16.h>
122720
122721 typedef struct IcuTokenizer IcuTokenizer;
122722 typedef struct IcuCursor IcuCursor;
122723
122724 struct IcuTokenizer {
122725   sqlite3_tokenizer base;
122726   char *zLocale;
122727 };
122728
122729 struct IcuCursor {
122730   sqlite3_tokenizer_cursor base;
122731
122732   UBreakIterator *pIter;      /* ICU break-iterator object */
122733   int nChar;                  /* Number of UChar elements in pInput */
122734   UChar *aChar;               /* Copy of input using utf-16 encoding */
122735   int *aOffset;               /* Offsets of each character in utf-8 input */
122736
122737   int nBuffer;
122738   char *zBuffer;
122739
122740   int iToken;
122741 };
122742
122743 /*
122744 ** Create a new tokenizer instance.
122745 */
122746 static int icuCreate(
122747   int argc,                            /* Number of entries in argv[] */
122748   const char * const *argv,            /* Tokenizer creation arguments */
122749   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
122750 ){
122751   IcuTokenizer *p;
122752   int n = 0;
122753
122754   if( argc>0 ){
122755     n = strlen(argv[0])+1;
122756   }
122757   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
122758   if( !p ){
122759     return SQLITE_NOMEM;
122760   }
122761   memset(p, 0, sizeof(IcuTokenizer));
122762
122763   if( n ){
122764     p->zLocale = (char *)&p[1];
122765     memcpy(p->zLocale, argv[0], n);
122766   }
122767
122768   *ppTokenizer = (sqlite3_tokenizer *)p;
122769
122770   return SQLITE_OK;
122771 }
122772
122773 /*
122774 ** Destroy a tokenizer
122775 */
122776 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
122777   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
122778   sqlite3_free(p);
122779   return SQLITE_OK;
122780 }
122781
122782 /*
122783 ** Prepare to begin tokenizing a particular string.  The input
122784 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
122785 ** used to incrementally tokenize this string is returned in 
122786 ** *ppCursor.
122787 */
122788 static int icuOpen(
122789   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
122790   const char *zInput,                    /* Input string */
122791   int nInput,                            /* Length of zInput in bytes */
122792   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
122793 ){
122794   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
122795   IcuCursor *pCsr;
122796
122797   const int32_t opt = U_FOLD_CASE_DEFAULT;
122798   UErrorCode status = U_ZERO_ERROR;
122799   int nChar;
122800
122801   UChar32 c;
122802   int iInput = 0;
122803   int iOut = 0;
122804
122805   *ppCursor = 0;
122806
122807   if( nInput<0 ){
122808     nInput = strlen(zInput);
122809   }
122810   nChar = nInput+1;
122811   pCsr = (IcuCursor *)sqlite3_malloc(
122812       sizeof(IcuCursor) +                /* IcuCursor */
122813       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
122814       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
122815   );
122816   if( !pCsr ){
122817     return SQLITE_NOMEM;
122818   }
122819   memset(pCsr, 0, sizeof(IcuCursor));
122820   pCsr->aChar = (UChar *)&pCsr[1];
122821   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
122822
122823   pCsr->aOffset[iOut] = iInput;
122824   U8_NEXT(zInput, iInput, nInput, c); 
122825   while( c>0 ){
122826     int isError = 0;
122827     c = u_foldCase(c, opt);
122828     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
122829     if( isError ){
122830       sqlite3_free(pCsr);
122831       return SQLITE_ERROR;
122832     }
122833     pCsr->aOffset[iOut] = iInput;
122834
122835     if( iInput<nInput ){
122836       U8_NEXT(zInput, iInput, nInput, c);
122837     }else{
122838       c = 0;
122839     }
122840   }
122841
122842   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
122843   if( !U_SUCCESS(status) ){
122844     sqlite3_free(pCsr);
122845     return SQLITE_ERROR;
122846   }
122847   pCsr->nChar = iOut;
122848
122849   ubrk_first(pCsr->pIter);
122850   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
122851   return SQLITE_OK;
122852 }
122853
122854 /*
122855 ** Close a tokenization cursor previously opened by a call to icuOpen().
122856 */
122857 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
122858   IcuCursor *pCsr = (IcuCursor *)pCursor;
122859   ubrk_close(pCsr->pIter);
122860   sqlite3_free(pCsr->zBuffer);
122861   sqlite3_free(pCsr);
122862   return SQLITE_OK;
122863 }
122864
122865 /*
122866 ** Extract the next token from a tokenization cursor.
122867 */
122868 static int icuNext(
122869   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
122870   const char **ppToken,               /* OUT: *ppToken is the token text */
122871   int *pnBytes,                       /* OUT: Number of bytes in token */
122872   int *piStartOffset,                 /* OUT: Starting offset of token */
122873   int *piEndOffset,                   /* OUT: Ending offset of token */
122874   int *piPosition                     /* OUT: Position integer of token */
122875 ){
122876   IcuCursor *pCsr = (IcuCursor *)pCursor;
122877
122878   int iStart = 0;
122879   int iEnd = 0;
122880   int nByte = 0;
122881
122882   while( iStart==iEnd ){
122883     UChar32 c;
122884
122885     iStart = ubrk_current(pCsr->pIter);
122886     iEnd = ubrk_next(pCsr->pIter);
122887     if( iEnd==UBRK_DONE ){
122888       return SQLITE_DONE;
122889     }
122890
122891     while( iStart<iEnd ){
122892       int iWhite = iStart;
122893       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
122894       if( u_isspace(c) ){
122895         iStart = iWhite;
122896       }else{
122897         break;
122898       }
122899     }
122900     assert(iStart<=iEnd);
122901   }
122902
122903   do {
122904     UErrorCode status = U_ZERO_ERROR;
122905     if( nByte ){
122906       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
122907       if( !zNew ){
122908         return SQLITE_NOMEM;
122909       }
122910       pCsr->zBuffer = zNew;
122911       pCsr->nBuffer = nByte;
122912     }
122913
122914     u_strToUTF8(
122915         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
122916         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
122917         &status                                  /* Output success/failure */
122918     );
122919   } while( nByte>pCsr->nBuffer );
122920
122921   *ppToken = pCsr->zBuffer;
122922   *pnBytes = nByte;
122923   *piStartOffset = pCsr->aOffset[iStart];
122924   *piEndOffset = pCsr->aOffset[iEnd];
122925   *piPosition = pCsr->iToken++;
122926
122927   return SQLITE_OK;
122928 }
122929
122930 /*
122931 ** The set of routines that implement the simple tokenizer
122932 */
122933 static const sqlite3_tokenizer_module icuTokenizerModule = {
122934   0,                           /* iVersion */
122935   icuCreate,                   /* xCreate  */
122936   icuDestroy,                  /* xCreate  */
122937   icuOpen,                     /* xOpen    */
122938   icuClose,                    /* xClose   */
122939   icuNext,                     /* xNext    */
122940 };
122941
122942 /*
122943 ** Set *ppModule to point at the implementation of the ICU tokenizer.
122944 */
122945 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
122946   sqlite3_tokenizer_module const**ppModule
122947 ){
122948   *ppModule = &icuTokenizerModule;
122949 }
122950
122951 #endif /* defined(SQLITE_ENABLE_ICU) */
122952 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
122953
122954 /************** End of fts3_icu.c ********************************************/